blob: 9b3f5d87742e1ccc8ca4b60f1f3c816b66121024 [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 Bataevcb8e6912020-01-31 16:09:26 -050025#include "clang/Basic/DiagnosticSema.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev0ee89c12019-12-12 14:13:02 -050027#include "clang/Basic/PartialDiagnostic.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000029#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000030#include "clang/Sema/Scope.h"
31#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000032#include "clang/Sema/SemaInternal.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060033#include "llvm/ADT/IndexedMap.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000034#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataev36635632020-01-17 20:39:04 -050035#include "llvm/ADT/STLExtras.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060036#include "llvm/Frontend/OpenMP/OMPConstants.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000037using namespace clang;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060038using namespace llvm::omp;
Alexey Bataeva769e072013-03-22 06:34:35 +000039
Alexey Bataev758e55e2013-09-06 18:03:48 +000040//===----------------------------------------------------------------------===//
41// Stack of data-sharing attributes for variables
42//===----------------------------------------------------------------------===//
43
Alexey Bataeve3727102018-04-18 15:57:46 +000044static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000045 Sema &SemaRef, Expr *E,
46 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000047 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000048
Alexey Bataev758e55e2013-09-06 18:03:48 +000049namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000051enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 DSA_unspecified = 0, /// Data sharing attribute not specified.
53 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
54 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000055};
56
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>;
Alexey Bataevb6e70842019-12-16 15:54:17 -050088 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
Alexey Bataeve3727102018-04-18 15:57:46 +000089 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>;
cchene06f3e02019-11-15 13:02:06 -0500118 struct DefaultmapInfo {
119 OpenMPDefaultmapClauseModifier ImplicitBehavior =
120 OMPC_DEFAULTMAP_MODIFIER_unknown;
121 SourceLocation SLoc;
122 DefaultmapInfo() = default;
123 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
124 : ImplicitBehavior(M), SLoc(Loc) {}
125 };
Alexey Bataev758e55e2013-09-06 18:03:48 +0000126
Alexey Bataeve3727102018-04-18 15:57:46 +0000127 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000129 DeclReductionMapTy ReductionMap;
Alexey Bataevb6e70842019-12-16 15:54:17 -0500130 UsedRefMapTy AlignedMap;
131 UsedRefMapTy NontemporalMap;
Samuel Antao90927002016-04-26 14:54:23 +0000132 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000133 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000134 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000135 SourceLocation DefaultAttrLoc;
cchene06f3e02019-11-15 13:02:06 -0500136 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000138 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000139 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000140 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000141 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
142 /// get the data (loop counters etc.) about enclosing loop-based construct.
143 /// This data is required during codegen.
144 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000145 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000146 /// 'ordered' clause, the second one is true if the regions has 'ordered'
147 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000148 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000149 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000150 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000151 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000152 bool NowaitRegion = false;
153 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000154 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000155 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000156 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000157 /// Reference to the taskgroup task_reduction reference expression.
158 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000159 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataevf3c508f2020-01-23 10:47:16 -0500160 SmallVector<Expr *, 4> InnerUsedAllocators;
Alexey Bataeva495c642019-03-11 19:51:42 +0000161 /// List of globals marked as declare target link in this target region
162 /// (isOpenMPTargetExecutionDirective(Directive) == true).
163 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000164 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000165 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000166 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
167 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000168 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000169 };
170
Alexey Bataeve3727102018-04-18 15:57:46 +0000171 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000172
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000173 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000174 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000175 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
176 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000177 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000178 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000179 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000180 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000181 bool ForceCapturing = false;
Alexey Bataevd1caf932019-09-30 14:05:26 +0000182 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000183 /// captured by reference.
184 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000185 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000186 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187
Richard Smith375dec52019-05-30 23:21:14 +0000188 /// Iterators over the stack iterate in order from innermost to outermost
189 /// directive.
190 using const_iterator = StackTy::const_reverse_iterator;
191 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000192 return Stack.empty() ? const_iterator()
193 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000194 }
195 const_iterator end() const {
196 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
197 }
198 using iterator = StackTy::reverse_iterator;
199 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000200 return Stack.empty() ? iterator()
201 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000202 }
203 iterator end() {
204 return Stack.empty() ? iterator() : Stack.back().first.rend();
205 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000206
Richard Smith375dec52019-05-30 23:21:14 +0000207 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000208
Alexey Bataev4b465392017-04-26 15:06:24 +0000209 bool isStackEmpty() const {
210 return Stack.empty() ||
211 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000212 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000213 }
Richard Smith375dec52019-05-30 23:21:14 +0000214 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000215 return isStackEmpty() ? 0
216 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000217 }
218
219 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000220 size_t Size = getStackSize();
221 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000222 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000223 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000224 }
225 const SharingMapTy *getTopOfStackOrNull() const {
226 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
227 }
228 SharingMapTy &getTopOfStack() {
229 assert(!isStackEmpty() && "no current directive");
230 return *getTopOfStackOrNull();
231 }
232 const SharingMapTy &getTopOfStack() const {
233 return const_cast<DSAStackTy&>(*this).getTopOfStack();
234 }
235
236 SharingMapTy *getSecondOnStackOrNull() {
237 size_t Size = getStackSize();
238 if (Size <= 1)
239 return nullptr;
240 return &Stack.back().first[Size - 2];
241 }
242 const SharingMapTy *getSecondOnStackOrNull() const {
243 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
244 }
245
246 /// Get the stack element at a certain level (previously returned by
247 /// \c getNestingLevel).
248 ///
249 /// Note that nesting levels count from outermost to innermost, and this is
250 /// the reverse of our iteration order where new inner levels are pushed at
251 /// the front of the stack.
252 SharingMapTy &getStackElemAtLevel(unsigned Level) {
253 assert(Level < getStackSize() && "no such stack element");
254 return Stack.back().first[Level];
255 }
256 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
257 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
258 }
259
260 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
261
262 /// Checks if the variable is a local for OpenMP region.
263 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000264
Kelvin Li1408f912018-09-26 04:28:39 +0000265 /// Vector of previously declared requires directives
266 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000267 /// omp_allocator_handle_t type.
268 QualType OMPAllocatorHandleT;
269 /// Expression for the predefined allocators.
270 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
271 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000272 /// Vector of previously encountered target directives
273 SmallVector<SourceLocation, 2> TargetLocations;
Alexey Bataev2d4f80f2020-02-11 15:15:21 -0500274 SourceLocation AtomicLocation;
Kelvin Li1408f912018-09-26 04:28:39 +0000275
Alexey Bataev758e55e2013-09-06 18:03:48 +0000276public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000277 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000278
Alexey Bataev27ef9512019-03-20 20:14:22 +0000279 /// Sets omp_allocator_handle_t type.
280 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
281 /// Gets omp_allocator_handle_t type.
282 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
283 /// Sets the given default allocator.
284 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
285 Expr *Allocator) {
286 OMPPredefinedAllocators[AllocatorKind] = Allocator;
287 }
288 /// Returns the specified default allocator.
289 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
290 return OMPPredefinedAllocators[AllocatorKind];
291 }
292
Alexey Bataevaac108a2015-06-23 04:51:00 +0000293 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000294 OpenMPClauseKind getClauseParsingMode() const {
295 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
296 return ClauseKindMode;
297 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000298 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000299
Richard Smith0621a8f2019-05-31 00:45:10 +0000300 bool isBodyComplete() const {
301 const SharingMapTy *Top = getTopOfStackOrNull();
302 return Top && Top->BodyComplete;
303 }
304 void setBodyComplete() {
305 getTopOfStack().BodyComplete = true;
306 }
307
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000308 bool isForceVarCapturing() const { return ForceCapturing; }
309 void setForceVarCapturing(bool V) { ForceCapturing = V; }
310
Alexey Bataev60705422018-10-30 15:50:12 +0000311 void setForceCaptureByReferenceInTargetExecutable(bool V) {
312 ForceCaptureByReferenceInTargetExecutable = V;
313 }
314 bool isForceCaptureByReferenceInTargetExecutable() const {
315 return ForceCaptureByReferenceInTargetExecutable;
316 }
317
Alexey Bataev758e55e2013-09-06 18:03:48 +0000318 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000319 Scope *CurScope, SourceLocation Loc) {
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 if (Stack.empty() ||
323 Stack.back().second != CurrentNonCapturingFunctionScope)
324 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
325 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
326 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000327 }
328
329 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000330 assert(!IgnoredStackElements &&
331 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000332 assert(!Stack.back().first.empty() &&
333 "Data-sharing attributes stack is empty!");
334 Stack.back().first.pop_back();
335 }
336
Richard Smith0621a8f2019-05-31 00:45:10 +0000337 /// RAII object to temporarily leave the scope of a directive when we want to
338 /// logically operate in its parent.
339 class ParentDirectiveScope {
340 DSAStackTy &Self;
341 bool Active;
342 public:
343 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
344 : Self(Self), Active(false) {
345 if (Activate)
346 enable();
347 }
348 ~ParentDirectiveScope() { disable(); }
349 void disable() {
350 if (Active) {
351 --Self.IgnoredStackElements;
352 Active = false;
353 }
354 }
355 void enable() {
356 if (!Active) {
357 ++Self.IgnoredStackElements;
358 Active = true;
359 }
360 }
361 };
362
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000363 /// Marks that we're started loop parsing.
364 void loopInit() {
365 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
366 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000367 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000368 }
369 /// Start capturing of the variables in the loop context.
370 void loopStart() {
371 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
372 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000373 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000374 }
375 /// true, if variables are captured, false otherwise.
376 bool isLoopStarted() const {
377 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
378 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000379 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000380 }
381 /// Marks (or clears) declaration as possibly loop counter.
382 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000383 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000384 D ? D->getCanonicalDecl() : D;
385 }
386 /// Gets the possible loop counter decl.
387 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000388 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000389 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000390 /// Start new OpenMP region stack in new non-capturing function.
391 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000392 assert(!IgnoredStackElements &&
393 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000394 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
395 assert(!isa<CapturingScopeInfo>(CurFnScope));
396 CurrentNonCapturingFunctionScope = CurFnScope;
397 }
398 /// Pop region stack for non-capturing function.
399 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000400 assert(!IgnoredStackElements &&
401 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000402 if (!Stack.empty() && Stack.back().second == OldFSI) {
403 assert(Stack.back().first.empty());
404 Stack.pop_back();
405 }
406 CurrentNonCapturingFunctionScope = nullptr;
407 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
408 if (!isa<CapturingScopeInfo>(FSI)) {
409 CurrentNonCapturingFunctionScope = FSI;
410 break;
411 }
412 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000413 }
414
Alexey Bataeve3727102018-04-18 15:57:46 +0000415 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000416 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000417 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000418 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000419 getCriticalWithHint(const DeclarationNameInfo &Name) const {
420 auto I = Criticals.find(Name.getAsString());
421 if (I != Criticals.end())
422 return I->second;
423 return std::make_pair(nullptr, llvm::APSInt());
424 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000425 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000426 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000427 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000428 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexey Bataevb6e70842019-12-16 15:54:17 -0500429 /// If 'nontemporal' declaration for given variable \a D was not seen yet,
430 /// add it and return NULL; otherwise return previous occurrence's expression
431 /// for diagnostics.
432 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000433
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000434 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000435 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000437 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000438 /// \return The index of the loop control variable in the list of associated
439 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000440 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000442 /// parent region.
443 /// \return The index of the loop control variable in the list of associated
444 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000445 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000446 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000447 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000448 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000449
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000450 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000451 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000452 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453
Alexey Bataevfa312f32017-07-21 18:48:21 +0000454 /// Adds additional information for the reduction items with the reduction id
455 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000456 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000457 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000458 /// Adds additional information for the reduction items with the reduction id
459 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000460 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000461 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000462 /// Returns the location and reduction operation from the innermost parent
463 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000464 const DSAVarData
465 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
466 BinaryOperatorKind &BOK,
467 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000468 /// Returns the location and reduction operation from the innermost parent
469 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000470 const DSAVarData
471 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
472 const Expr *&ReductionRef,
473 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000474 /// Return reduction reference expression for the current taskgroup.
475 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000476 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000477 "taskgroup reference expression requested for non taskgroup "
478 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000479 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000480 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000481 /// Checks if the given \p VD declaration is actually a taskgroup reduction
482 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000483 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000484 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
485 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000486 ->getDecl() == VD;
487 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000488
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000489 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000490 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000491 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000492 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000493 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000494 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000495 /// match specified \a CPred predicate in any directive which matches \a DPred
496 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000497 const DSAVarData
498 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
499 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
500 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000501 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000502 /// match specified \a CPred predicate in any innermost directive which
503 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000504 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000505 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000506 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
507 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000508 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000509 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000510 /// attributes which match specified \a CPred predicate at the specified
511 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000512 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000513 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000514 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000516 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000517 /// specified \a DPred predicate.
518 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000519 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000520 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000521
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000522 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000523 bool hasDirective(
524 const llvm::function_ref<bool(
525 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
526 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000527 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000528
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000529 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000530 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000531 const SharingMapTy *Top = getTopOfStackOrNull();
532 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000533 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000534 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000535 OpenMPDirectiveKind getDirective(unsigned Level) const {
536 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000537 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000538 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000539 /// Returns the capture region at the specified level.
540 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
541 unsigned OpenMPCaptureLevel) const {
542 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
543 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
544 return CaptureRegions[OpenMPCaptureLevel];
545 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000546 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000547 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000548 const SharingMapTy *Parent = getSecondOnStackOrNull();
549 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000550 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000551
Kelvin Li1408f912018-09-26 04:28:39 +0000552 /// Add requires decl to internal vector
553 void addRequiresDecl(OMPRequiresDecl *RD) {
554 RequiresDecls.push_back(RD);
555 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000556
Alexey Bataev318f431b2019-03-22 15:25:12 +0000557 /// Checks if the defined 'requires' directive has specified type of clause.
558 template <typename ClauseType>
Alexey Bataev2d4f80f2020-02-11 15:15:21 -0500559 bool hasRequiresDeclWithClause() const {
Alexey Bataev318f431b2019-03-22 15:25:12 +0000560 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
561 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
562 return isa<ClauseType>(C);
563 });
564 });
565 }
566
Kelvin Li1408f912018-09-26 04:28:39 +0000567 /// Checks for a duplicate clause amongst previously declared requires
568 /// directives
569 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
570 bool IsDuplicate = false;
571 for (OMPClause *CNew : ClauseList) {
572 for (const OMPRequiresDecl *D : RequiresDecls) {
573 for (const OMPClause *CPrev : D->clauselists()) {
574 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
575 SemaRef.Diag(CNew->getBeginLoc(),
576 diag::err_omp_requires_clause_redeclaration)
577 << getOpenMPClauseName(CNew->getClauseKind());
578 SemaRef.Diag(CPrev->getBeginLoc(),
579 diag::note_omp_requires_previous_clause)
580 << getOpenMPClauseName(CPrev->getClauseKind());
581 IsDuplicate = true;
582 }
583 }
584 }
585 }
586 return IsDuplicate;
587 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000588
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000589 /// Add location of previously encountered target to internal vector
590 void addTargetDirLocation(SourceLocation LocStart) {
591 TargetLocations.push_back(LocStart);
592 }
593
Alexey Bataev2d4f80f2020-02-11 15:15:21 -0500594 /// Add location for the first encountered atomicc directive.
595 void addAtomicDirectiveLoc(SourceLocation Loc) {
596 if (AtomicLocation.isInvalid())
597 AtomicLocation = Loc;
598 }
599
600 /// Returns the location of the first encountered atomic directive in the
601 /// module.
602 SourceLocation getAtomicDirectiveLoc() const {
603 return AtomicLocation;
604 }
605
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000606 // Return previously encountered target region locations.
607 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
608 return TargetLocations;
609 }
610
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000611 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000612 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000613 getTopOfStack().DefaultAttr = DSA_none;
614 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000615 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000616 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000617 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000618 getTopOfStack().DefaultAttr = DSA_shared;
619 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000620 }
cchene06f3e02019-11-15 13:02:06 -0500621 /// Set default data mapping attribute to Modifier:Kind
622 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
623 OpenMPDefaultmapClauseKind Kind,
624 SourceLocation Loc) {
625 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
626 DMI.ImplicitBehavior = M;
627 DMI.SLoc = Loc;
628 }
629 /// Check whether the implicit-behavior has been set in defaultmap
630 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
631 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
632 OMPC_DEFAULTMAP_MODIFIER_unknown;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000633 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000634
635 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000636 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000637 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000638 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000639 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000640 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000641 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000642 }
cchene06f3e02019-11-15 13:02:06 -0500643 OpenMPDefaultmapClauseModifier
644 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
645 return isStackEmpty()
646 ? OMPC_DEFAULTMAP_MODIFIER_unknown
647 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000648 }
cchene06f3e02019-11-15 13:02:06 -0500649 OpenMPDefaultmapClauseModifier
650 getDefaultmapModifierAtLevel(unsigned Level,
651 OpenMPDefaultmapClauseKind Kind) const {
652 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000653 }
cchene06f3e02019-11-15 13:02:06 -0500654 bool isDefaultmapCapturedByRef(unsigned Level,
655 OpenMPDefaultmapClauseKind Kind) const {
656 OpenMPDefaultmapClauseModifier M =
657 getDefaultmapModifierAtLevel(Level, Kind);
658 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
659 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
660 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
661 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
662 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
663 }
664 return true;
665 }
666 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
667 OpenMPDefaultmapClauseKind Kind) {
668 switch (Kind) {
669 case OMPC_DEFAULTMAP_scalar:
670 case OMPC_DEFAULTMAP_pointer:
671 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
672 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
673 (M == OMPC_DEFAULTMAP_MODIFIER_default);
674 case OMPC_DEFAULTMAP_aggregate:
675 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000676 default:
677 break;
cchene06f3e02019-11-15 13:02:06 -0500678 }
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000679 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
cchene06f3e02019-11-15 13:02:06 -0500680 }
681 bool mustBeFirstprivateAtLevel(unsigned Level,
682 OpenMPDefaultmapClauseKind Kind) const {
683 OpenMPDefaultmapClauseModifier M =
684 getDefaultmapModifierAtLevel(Level, Kind);
685 return mustBeFirstprivateBase(M, Kind);
686 }
687 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
688 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
689 return mustBeFirstprivateBase(M, Kind);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000690 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000692 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000693 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000694 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000695 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000696 }
697
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000698 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000699 void setOrderedRegion(bool IsOrdered, const Expr *Param,
700 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000701 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000702 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000703 else
Richard Smith375dec52019-05-30 23:21:14 +0000704 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000705 }
706 /// Returns true, if region is ordered (has associated 'ordered' clause),
707 /// false - otherwise.
708 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000709 if (const SharingMapTy *Top = getTopOfStackOrNull())
710 return Top->OrderedRegion.hasValue();
711 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000712 }
713 /// Returns optional parameter for the ordered region.
714 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000715 if (const SharingMapTy *Top = getTopOfStackOrNull())
716 if (Top->OrderedRegion.hasValue())
717 return Top->OrderedRegion.getValue();
718 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000719 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000720 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000721 /// 'ordered' clause), false - otherwise.
722 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000723 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
724 return Parent->OrderedRegion.hasValue();
725 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000726 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000727 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000728 std::pair<const Expr *, OMPOrderedClause *>
729 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000730 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
731 if (Parent->OrderedRegion.hasValue())
732 return Parent->OrderedRegion.getValue();
733 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000734 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000735 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000736 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000737 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000738 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000739 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000740 /// 'nowait' clause), false - otherwise.
741 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000742 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
743 return Parent->NowaitRegion;
744 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000745 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000746 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000747 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000748 if (SharingMapTy *Parent = getSecondOnStackOrNull())
749 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000750 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000751 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000752 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000753 const SharingMapTy *Top = getTopOfStackOrNull();
754 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000755 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000756
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000757 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000758 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000759 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000760 if (Val > 1)
761 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000762 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000763 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000764 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000765 const SharingMapTy *Top = getTopOfStackOrNull();
766 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000767 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000768 /// Returns true if the construct is associated with multiple loops.
769 bool hasMutipleLoops() const {
770 const SharingMapTy *Top = getTopOfStackOrNull();
771 return Top ? Top->HasMutipleLoops : false;
772 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000773
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000774 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000775 /// region.
776 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000777 if (SharingMapTy *Parent = getSecondOnStackOrNull())
778 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000779 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000780 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000781 bool hasInnerTeamsRegion() const {
782 return getInnerTeamsRegionLoc().isValid();
783 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000784 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000785 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000786 const SharingMapTy *Top = getTopOfStackOrNull();
787 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000788 }
789
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000790 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000791 const SharingMapTy *Top = getTopOfStackOrNull();
792 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000793 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000794 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000795 const SharingMapTy *Top = getTopOfStackOrNull();
796 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000797 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000798
Samuel Antao4c8035b2016-12-12 18:00:20 +0000799 /// Do the check specified in \a Check to all component lists and return true
800 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000801 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000802 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000803 const llvm::function_ref<
804 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000805 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000806 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000807 if (isStackEmpty())
808 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000809 auto SI = begin();
810 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000811
812 if (SI == SE)
813 return false;
814
Alexey Bataeve3727102018-04-18 15:57:46 +0000815 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000816 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000817 else
818 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000819
820 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000821 auto MI = SI->MappedExprComponents.find(VD);
822 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000823 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
824 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000825 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000826 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000827 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000828 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000829 }
830
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000831 /// Do the check specified in \a Check to all component lists at a given level
832 /// and return true if any issue is found.
833 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000834 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000835 const llvm::function_ref<
836 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000837 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000838 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000839 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000840 return false;
841
Richard Smith375dec52019-05-30 23:21:14 +0000842 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
843 auto MI = StackElem.MappedExprComponents.find(VD);
844 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000845 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
846 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000847 if (Check(L, MI->second.Kind))
848 return true;
849 return false;
850 }
851
Samuel Antao4c8035b2016-12-12 18:00:20 +0000852 /// Create a new mappable expression component list associated with a given
853 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000854 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000855 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000856 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
857 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000858 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000859 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000860 MEC.Components.resize(MEC.Components.size() + 1);
861 MEC.Components.back().append(Components.begin(), Components.end());
862 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000863 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000864
865 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000866 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000867 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000868 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000869 void addDoacrossDependClause(OMPDependClause *C,
870 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000871 SharingMapTy *Parent = getSecondOnStackOrNull();
872 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
873 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000874 }
875 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
876 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000877 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000878 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000879 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000880 return llvm::make_range(Ref.begin(), Ref.end());
881 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000882 return llvm::make_range(StackElem.DoacrossDepends.end(),
883 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000884 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000885
886 // Store types of classes which have been explicitly mapped
887 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000888 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000889 StackElem.MappedClassesQualTypes.insert(QT);
890 }
891
892 // Return set of mapped classes types
893 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000894 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000895 return StackElem.MappedClassesQualTypes.count(QT) != 0;
896 }
897
Alexey Bataeva495c642019-03-11 19:51:42 +0000898 /// Adds global declare target to the parent target region.
899 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
900 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
901 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
902 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000903 for (auto &Elem : *this) {
904 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
905 Elem.DeclareTargetLinkVarDecls.push_back(E);
906 return;
907 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000908 }
909 }
910
911 /// Returns the list of globals with declare target link if current directive
912 /// is target.
913 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
914 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
915 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000916 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000917 }
Alexey Bataevf3c508f2020-01-23 10:47:16 -0500918
919 /// Adds list of allocators expressions.
920 void addInnerAllocatorExpr(Expr *E) {
921 getTopOfStack().InnerUsedAllocators.push_back(E);
922 }
923 /// Return list of used allocators.
924 ArrayRef<Expr *> getInnerAllocators() const {
925 return getTopOfStack().InnerUsedAllocators;
926 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000927};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000928
929bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
930 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
931}
932
933bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000934 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
935 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000936}
Alexey Bataeve3727102018-04-18 15:57:46 +0000937
Alexey Bataeved09d242014-05-28 05:53:51 +0000938} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000939
Alexey Bataeve3727102018-04-18 15:57:46 +0000940static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000941 if (const auto *FE = dyn_cast<FullExpr>(E))
942 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000943
Alexey Bataeve3727102018-04-18 15:57:46 +0000944 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +0100945 E = MTE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000946
Alexey Bataeve3727102018-04-18 15:57:46 +0000947 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000948 E = Binder->getSubExpr();
949
Alexey Bataeve3727102018-04-18 15:57:46 +0000950 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000951 E = ICE->getSubExprAsWritten();
952 return E->IgnoreParens();
953}
954
Alexey Bataeve3727102018-04-18 15:57:46 +0000955static Expr *getExprAsWritten(Expr *E) {
956 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
957}
958
959static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
960 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
961 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000962 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000963 const auto *VD = dyn_cast<VarDecl>(D);
964 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000965 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000966 VD = VD->getCanonicalDecl();
967 D = VD;
968 } else {
969 assert(FD);
970 FD = FD->getCanonicalDecl();
971 D = FD;
972 }
973 return D;
974}
975
Alexey Bataeve3727102018-04-18 15:57:46 +0000976static ValueDecl *getCanonicalDecl(ValueDecl *D) {
977 return const_cast<ValueDecl *>(
978 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
979}
980
Richard Smith375dec52019-05-30 23:21:14 +0000981DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000982 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000983 D = getCanonicalDecl(D);
984 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000985 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000986 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000987 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000988 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
989 // in a region but not in construct]
990 // File-scope or namespace-scope variables referenced in called routines
991 // in the region are shared unless they appear in a threadprivate
992 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000993 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000994 DVar.CKind = OMPC_shared;
995
996 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
997 // in a region but not in construct]
998 // Variables with static storage duration that are declared in called
999 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001000 if (VD && VD->hasGlobalStorage())
1001 DVar.CKind = OMPC_shared;
1002
1003 // Non-static data members are shared by default.
1004 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +00001005 DVar.CKind = OMPC_shared;
1006
Alexey Bataev758e55e2013-09-06 18:03:48 +00001007 return DVar;
1008 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001009
Alexey Bataevec3da872014-01-31 05:15:34 +00001010 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1011 // in a Construct, C/C++, predetermined, p.1]
1012 // Variables with automatic storage duration that are declared in a scope
1013 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001014 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1015 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001016 DVar.CKind = OMPC_private;
1017 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +00001018 }
1019
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001020 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001021 // Explicitly specified attributes and local variables with predetermined
1022 // attributes.
1023 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001024 const DSAInfo &Data = Iter->SharingMap.lookup(D);
1025 DVar.RefExpr = Data.RefExpr.getPointer();
1026 DVar.PrivateCopy = Data.PrivateCopy;
1027 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001028 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001029 return DVar;
1030 }
1031
1032 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1033 // in a Construct, C/C++, implicitly determined, p.1]
1034 // In a parallel or task construct, the data-sharing attributes of these
1035 // variables are determined by the default clause, if present.
1036 switch (Iter->DefaultAttr) {
1037 case DSA_shared:
1038 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001039 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001040 return DVar;
1041 case DSA_none:
1042 return DVar;
1043 case DSA_unspecified:
1044 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1045 // in a Construct, implicitly determined, p.2]
1046 // In a parallel construct, if no default clause is present, these
1047 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +00001048 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001049 if ((isOpenMPParallelDirective(DVar.DKind) &&
1050 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001051 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001052 DVar.CKind = OMPC_shared;
1053 return DVar;
1054 }
1055
1056 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1057 // in a Construct, implicitly determined, p.4]
1058 // In a task construct, if no default clause is present, a variable that in
1059 // the enclosing context is determined to be shared by all implicit tasks
1060 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001061 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001062 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +00001063 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001064 do {
1065 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001066 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +00001067 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +00001068 // In a task construct, if no default clause is present, a variable
1069 // whose data-sharing attribute is not determined by the rules above is
1070 // firstprivate.
1071 DVarTemp = getDSA(I, D);
1072 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001073 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001074 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001075 return DVar;
1076 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001077 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +00001078 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +00001079 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001080 return DVar;
1081 }
1082 }
1083 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1084 // in a Construct, implicitly determined, p.3]
1085 // For constructs other than task, if no default clause is present, these
1086 // variables inherit their data-sharing attributes from the enclosing
1087 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001088 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001089}
1090
Alexey Bataeve3727102018-04-18 15:57:46 +00001091const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1092 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001093 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001094 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001095 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001096 auto It = StackElem.AlignedMap.find(D);
1097 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001098 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001099 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001100 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001101 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001102 assert(It->second && "Unexpected nullptr expr in the aligned map");
1103 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001104}
1105
Alexey Bataevb6e70842019-12-16 15:54:17 -05001106const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1107 const Expr *NewDE) {
1108 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1109 D = getCanonicalDecl(D);
1110 SharingMapTy &StackElem = getTopOfStack();
1111 auto It = StackElem.NontemporalMap.find(D);
1112 if (It == StackElem.NontemporalMap.end()) {
1113 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1114 StackElem.NontemporalMap[D] = NewDE;
1115 return nullptr;
1116 }
1117 assert(It->second && "Unexpected nullptr expr in the aligned map");
1118 return It->second;
1119}
1120
Alexey Bataeve3727102018-04-18 15:57:46 +00001121void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001122 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001123 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001124 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001125 StackElem.LCVMap.try_emplace(
1126 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001127}
1128
Alexey Bataeve3727102018-04-18 15:57:46 +00001129const DSAStackTy::LCDeclInfo
1130DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001131 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001132 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001133 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001134 auto It = StackElem.LCVMap.find(D);
1135 if (It != StackElem.LCVMap.end())
1136 return It->second;
1137 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001138}
1139
Alexey Bataeve3727102018-04-18 15:57:46 +00001140const DSAStackTy::LCDeclInfo
1141DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001142 const SharingMapTy *Parent = getSecondOnStackOrNull();
1143 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001144 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001145 auto It = Parent->LCVMap.find(D);
1146 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001147 return It->second;
1148 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001149}
1150
Alexey Bataeve3727102018-04-18 15:57:46 +00001151const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001152 const SharingMapTy *Parent = getSecondOnStackOrNull();
1153 assert(Parent && "Data-sharing attributes stack is empty");
1154 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001155 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001156 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001157 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001158 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001159 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001160}
1161
Alexey Bataeve3727102018-04-18 15:57:46 +00001162void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001163 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001164 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001165 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001166 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001167 Data.Attributes = A;
1168 Data.RefExpr.setPointer(E);
1169 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001170 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001171 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001172 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1173 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1174 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1175 (isLoopControlVariable(D).first && A == OMPC_private));
1176 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1177 Data.RefExpr.setInt(/*IntVal=*/true);
1178 return;
1179 }
1180 const bool IsLastprivate =
1181 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1182 Data.Attributes = A;
1183 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1184 Data.PrivateCopy = PrivateCopy;
1185 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001186 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001187 Data.Attributes = A;
1188 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1189 Data.PrivateCopy = nullptr;
1190 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001191 }
1192}
1193
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001194/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001195static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001196 StringRef Name, const AttrVec *Attrs = nullptr,
1197 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001198 DeclContext *DC = SemaRef.CurContext;
1199 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1200 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001201 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001202 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1203 if (Attrs) {
1204 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1205 I != E; ++I)
1206 Decl->addAttr(*I);
1207 }
1208 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001209 if (OrigRef) {
1210 Decl->addAttr(
1211 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1212 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001213 return Decl;
1214}
1215
1216static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1217 SourceLocation Loc,
1218 bool RefersToCapture = false) {
1219 D->setReferenced();
1220 D->markUsed(S.Context);
1221 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1222 SourceLocation(), D, RefersToCapture, Loc, Ty,
1223 VK_LValue);
1224}
1225
Alexey Bataeve3727102018-04-18 15:57:46 +00001226void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001227 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001228 D = getCanonicalDecl(D);
1229 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001230 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001231 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001232 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001233 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001234 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001235 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001236 "Additional reduction info may be specified only once for reduction "
1237 "items.");
1238 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001239 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001240 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001241 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001242 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1243 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001244 TaskgroupReductionRef =
1245 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001246 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001247}
1248
Alexey Bataeve3727102018-04-18 15:57:46 +00001249void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001250 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001251 D = getCanonicalDecl(D);
1252 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001253 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001254 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001255 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001256 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001257 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001258 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001259 "Additional reduction info may be specified only once for reduction "
1260 "items.");
1261 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001262 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001263 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001264 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001265 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1266 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001267 TaskgroupReductionRef =
1268 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001269 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001270}
1271
Alexey Bataeve3727102018-04-18 15:57:46 +00001272const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1273 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1274 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001275 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001276 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001277 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001278 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001279 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001280 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001281 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001282 if (!ReductionData.ReductionOp ||
1283 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001284 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001285 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001286 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001287 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1288 "expression for the descriptor is not "
1289 "set.");
1290 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001291 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1292 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001293 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001294 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001295}
1296
Alexey Bataeve3727102018-04-18 15:57:46 +00001297const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1298 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1299 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001300 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001301 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001302 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001303 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001304 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001305 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001306 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001307 if (!ReductionData.ReductionOp ||
1308 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001309 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001310 SR = ReductionData.ReductionRange;
1311 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001312 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1313 "expression for the descriptor is not "
1314 "set.");
1315 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001316 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1317 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001318 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001319 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001320}
1321
Richard Smith375dec52019-05-30 23:21:14 +00001322bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001323 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001324 for (const_iterator E = end(); I != E; ++I) {
1325 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1326 isOpenMPTargetExecutionDirective(I->Directive)) {
1327 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1328 Scope *CurScope = getCurScope();
1329 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1330 CurScope = CurScope->getParent();
1331 return CurScope != TopScope;
1332 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001333 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001334 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001335}
1336
Joel E. Dennyd2649292019-01-04 22:11:56 +00001337static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1338 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001339 bool *IsClassType = nullptr) {
1340 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001341 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001342 bool IsConstant = Type.isConstant(Context);
1343 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001344 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1345 ? Type->getAsCXXRecordDecl()
1346 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001347 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1348 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1349 RD = CTD->getTemplatedDecl();
1350 if (IsClassType)
1351 *IsClassType = RD;
1352 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1353 RD->hasDefinition() && RD->hasMutableFields());
1354}
1355
Joel E. Dennyd2649292019-01-04 22:11:56 +00001356static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1357 QualType Type, OpenMPClauseKind CKind,
1358 SourceLocation ELoc,
1359 bool AcceptIfMutable = true,
1360 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001361 ASTContext &Context = SemaRef.getASTContext();
1362 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001363 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1364 unsigned Diag = ListItemNotVar
1365 ? diag::err_omp_const_list_item
1366 : IsClassType ? diag::err_omp_const_not_mutable_variable
1367 : diag::err_omp_const_variable;
1368 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1369 if (!ListItemNotVar && D) {
1370 const VarDecl *VD = dyn_cast<VarDecl>(D);
1371 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1372 VarDecl::DeclarationOnly;
1373 SemaRef.Diag(D->getLocation(),
1374 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1375 << D;
1376 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001377 return true;
1378 }
1379 return false;
1380}
1381
Alexey Bataeve3727102018-04-18 15:57:46 +00001382const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1383 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001384 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001385 DSAVarData DVar;
1386
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001387 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001388 auto TI = Threadprivates.find(D);
1389 if (TI != Threadprivates.end()) {
1390 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001391 DVar.CKind = OMPC_threadprivate;
1392 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001393 }
1394 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001395 DVar.RefExpr = buildDeclRefExpr(
1396 SemaRef, VD, D->getType().getNonReferenceType(),
1397 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1398 DVar.CKind = OMPC_threadprivate;
1399 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001400 return DVar;
1401 }
1402 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1403 // in a Construct, C/C++, predetermined, p.1]
1404 // Variables appearing in threadprivate directives are threadprivate.
1405 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1406 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1407 SemaRef.getLangOpts().OpenMPUseTLS &&
1408 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1409 (VD && VD->getStorageClass() == SC_Register &&
1410 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1411 DVar.RefExpr = buildDeclRefExpr(
1412 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1413 DVar.CKind = OMPC_threadprivate;
1414 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1415 return DVar;
1416 }
1417 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1418 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1419 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001420 const_iterator IterTarget =
1421 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1422 return isOpenMPTargetExecutionDirective(Data.Directive);
1423 });
1424 if (IterTarget != end()) {
1425 const_iterator ParentIterTarget = IterTarget + 1;
1426 for (const_iterator Iter = begin();
1427 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001428 if (isOpenMPLocal(VD, Iter)) {
1429 DVar.RefExpr =
1430 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1431 D->getLocation());
1432 DVar.CKind = OMPC_threadprivate;
1433 return DVar;
1434 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001435 }
Richard Smith375dec52019-05-30 23:21:14 +00001436 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001437 auto DSAIter = IterTarget->SharingMap.find(D);
1438 if (DSAIter != IterTarget->SharingMap.end() &&
1439 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1440 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1441 DVar.CKind = OMPC_threadprivate;
1442 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001443 }
Richard Smith375dec52019-05-30 23:21:14 +00001444 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001445 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001446 D, std::distance(ParentIterTarget, End),
1447 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001448 DVar.RefExpr =
1449 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1450 IterTarget->ConstructLoc);
1451 DVar.CKind = OMPC_threadprivate;
1452 return DVar;
1453 }
1454 }
1455 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001456 }
1457
Alexey Bataev4b465392017-04-26 15:06:24 +00001458 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001459 // Not in OpenMP execution region and top scope was already checked.
1460 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001461
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001463 // in a Construct, C/C++, predetermined, p.4]
1464 // Static data members are shared.
1465 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1466 // in a Construct, C/C++, predetermined, p.7]
1467 // Variables with static storage duration that are declared in a scope
1468 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001469 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001470 // Check for explicitly specified attributes.
1471 const_iterator I = begin();
1472 const_iterator EndI = end();
1473 if (FromParent && I != EndI)
1474 ++I;
1475 auto It = I->SharingMap.find(D);
1476 if (It != I->SharingMap.end()) {
1477 const DSAInfo &Data = It->getSecond();
1478 DVar.RefExpr = Data.RefExpr.getPointer();
1479 DVar.PrivateCopy = Data.PrivateCopy;
1480 DVar.CKind = Data.Attributes;
1481 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1482 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001483 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001484 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001485
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001486 DVar.CKind = OMPC_shared;
1487 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001488 }
1489
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001490 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001491 // The predetermined shared attribute for const-qualified types having no
1492 // mutable members was removed after OpenMP 3.1.
1493 if (SemaRef.LangOpts.OpenMP <= 31) {
1494 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1495 // in a Construct, C/C++, predetermined, p.6]
1496 // Variables with const qualified type having no mutable member are
1497 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001498 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001499 // Variables with const-qualified type having no mutable member may be
1500 // listed in a firstprivate clause, even if they are static data members.
1501 DSAVarData DVarTemp = hasInnermostDSA(
1502 D,
1503 [](OpenMPClauseKind C) {
1504 return C == OMPC_firstprivate || C == OMPC_shared;
1505 },
1506 MatchesAlways, FromParent);
1507 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1508 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001509
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001510 DVar.CKind = OMPC_shared;
1511 return DVar;
1512 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001513 }
1514
Alexey Bataev758e55e2013-09-06 18:03:48 +00001515 // Explicitly specified attributes and local variables with predetermined
1516 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001517 const_iterator I = begin();
1518 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001519 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001520 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001521 auto It = I->SharingMap.find(D);
1522 if (It != I->SharingMap.end()) {
1523 const DSAInfo &Data = It->getSecond();
1524 DVar.RefExpr = Data.RefExpr.getPointer();
1525 DVar.PrivateCopy = Data.PrivateCopy;
1526 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001527 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001528 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001529 }
1530
1531 return DVar;
1532}
1533
Alexey Bataeve3727102018-04-18 15:57:46 +00001534const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1535 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001536 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001537 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001538 return getDSA(I, D);
1539 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001540 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001541 const_iterator StartI = begin();
1542 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001543 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001544 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001545 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001546}
1547
Alexey Bataeve3727102018-04-18 15:57:46 +00001548const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001549DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001550 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1551 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001552 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001553 if (isStackEmpty())
1554 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001555 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001556 const_iterator I = begin();
1557 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001558 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001559 ++I;
1560 for (; I != EndI; ++I) {
1561 if (!DPred(I->Directive) &&
1562 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001563 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001564 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001565 DSAVarData DVar = getDSA(NewI, D);
1566 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001567 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001568 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001569 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001570}
1571
Alexey Bataeve3727102018-04-18 15:57:46 +00001572const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001573 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1574 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001575 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001576 if (isStackEmpty())
1577 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001578 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001579 const_iterator StartI = begin();
1580 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001581 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001582 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001583 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001584 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001585 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001586 DSAVarData DVar = getDSA(NewI, D);
1587 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001588}
1589
Alexey Bataevaac108a2015-06-23 04:51:00 +00001590bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001591 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1592 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001593 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001594 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001595 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001596 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1597 auto I = StackElem.SharingMap.find(D);
1598 if (I != StackElem.SharingMap.end() &&
1599 I->getSecond().RefExpr.getPointer() &&
1600 CPred(I->getSecond().Attributes) &&
1601 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001602 return true;
1603 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001604 auto LI = StackElem.LCVMap.find(D);
1605 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001606 return CPred(OMPC_private);
1607 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001608}
1609
Samuel Antao4be30e92015-10-02 17:14:03 +00001610bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001611 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1612 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001613 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001614 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001615 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1616 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001617}
1618
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001619bool DSAStackTy::hasDirective(
1620 const llvm::function_ref<bool(OpenMPDirectiveKind,
1621 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001622 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001623 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001624 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001625 size_t Skip = FromParent ? 2 : 1;
1626 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1627 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001628 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1629 return true;
1630 }
1631 return false;
1632}
1633
Alexey Bataev758e55e2013-09-06 18:03:48 +00001634void Sema::InitDataSharingAttributesStack() {
1635 VarDataSharingAttributesStack = new DSAStackTy(*this);
1636}
1637
1638#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1639
Alexey Bataev4b465392017-04-26 15:06:24 +00001640void Sema::pushOpenMPFunctionRegion() {
1641 DSAStack->pushFunction();
1642}
1643
1644void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1645 DSAStack->popFunction(OldFSI);
1646}
1647
Alexey Bataevc416e642019-02-08 18:02:25 +00001648static bool isOpenMPDeviceDelayedContext(Sema &S) {
1649 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1650 "Expected OpenMP device compilation.");
1651 return !S.isInOpenMPTargetExecutionDirective() &&
1652 !S.isInOpenMPDeclareTargetContext();
1653}
1654
Alexey Bataev729e2422019-08-23 16:11:14 +00001655namespace {
1656/// Status of the function emission on the host/device.
1657enum class FunctionEmissionStatus {
1658 Emitted,
1659 Discarded,
1660 Unknown,
1661};
1662} // anonymous namespace
1663
Alexey Bataevc416e642019-02-08 18:02:25 +00001664Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1665 unsigned DiagID) {
1666 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1667 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001668 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001669 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1670 switch (FES) {
1671 case FunctionEmissionStatus::Emitted:
1672 Kind = DeviceDiagBuilder::K_Immediate;
1673 break;
1674 case FunctionEmissionStatus::Unknown:
1675 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1676 : DeviceDiagBuilder::K_Immediate;
1677 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001678 case FunctionEmissionStatus::TemplateDiscarded:
1679 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001680 Kind = DeviceDiagBuilder::K_Nop;
1681 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001682 case FunctionEmissionStatus::CUDADiscarded:
1683 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1684 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001685 }
1686
1687 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1688}
1689
Alexey Bataev729e2422019-08-23 16:11:14 +00001690Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1691 unsigned DiagID) {
1692 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1693 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001694 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001695 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1696 switch (FES) {
1697 case FunctionEmissionStatus::Emitted:
1698 Kind = DeviceDiagBuilder::K_Immediate;
1699 break;
1700 case FunctionEmissionStatus::Unknown:
1701 Kind = DeviceDiagBuilder::K_Deferred;
1702 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001703 case FunctionEmissionStatus::TemplateDiscarded:
1704 case FunctionEmissionStatus::OMPDiscarded:
1705 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001706 Kind = DeviceDiagBuilder::K_Nop;
1707 break;
1708 }
1709
1710 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001711}
1712
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001713void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1714 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001715 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1716 "Expected OpenMP device compilation.");
1717 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001718 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001719 FunctionDecl *Caller = getCurFunctionDecl();
1720
Alexey Bataev729e2422019-08-23 16:11:14 +00001721 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001722 if (Caller) {
1723 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1724 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1725 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1726 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1727 "CUDADiscarded unexpected in OpenMP device function check");
1728 if ((CallerS == FunctionEmissionStatus::Emitted ||
1729 (!isOpenMPDeviceDelayedContext(*this) &&
1730 CallerS == FunctionEmissionStatus::Unknown)) &&
1731 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1732 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1733 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1734 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1735 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1736 diag::note_omp_marked_device_type_here)
1737 << HostDevTy;
1738 return;
1739 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001740 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001741 // If the caller is known-emitted, mark the callee as known-emitted.
1742 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001743 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1744 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001745 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001746 markKnownEmitted(*this, Caller, Callee, Loc,
1747 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001748 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001749 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001750 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001751 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001752 else if (Caller)
1753 DeviceCallGraph[Caller].insert({Callee, Loc});
1754}
1755
Alexey Bataev729e2422019-08-23 16:11:14 +00001756void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1757 bool CheckCaller) {
1758 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1759 "Expected OpenMP host compilation.");
1760 assert(Callee && "Callee may not be null.");
1761 Callee = Callee->getMostRecentDecl();
1762 FunctionDecl *Caller = getCurFunctionDecl();
1763
1764 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001765 if (Caller) {
1766 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1767 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1768 assert(
1769 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1770 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1771 "CUDADiscarded unexpected in OpenMP host function check");
1772 if (CallerS == FunctionEmissionStatus::Emitted &&
1773 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1774 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1775 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1776 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1777 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1778 diag::note_omp_marked_device_type_here)
1779 << NoHostDevTy;
1780 return;
1781 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001782 }
1783 // If the caller is known-emitted, mark the callee as known-emitted.
1784 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001785 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1786 if ((!CheckCaller && !Caller) ||
1787 (Caller &&
1788 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1789 markKnownEmitted(
1790 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1791 return CheckCaller &&
1792 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1793 });
1794 else if (Caller)
1795 DeviceCallGraph[Caller].insert({Callee, Loc});
1796 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001797}
1798
Alexey Bataev123ad192019-02-27 20:29:45 +00001799void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1800 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1801 "OpenMP device compilation mode is expected.");
1802 QualType Ty = E->getType();
1803 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001804 ((Ty->isFloat128Type() ||
1805 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1806 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001807 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1808 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001809 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1810 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1811 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001812}
1813
cchene06f3e02019-11-15 13:02:06 -05001814static OpenMPDefaultmapClauseKind
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001815getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1816 if (LO.OpenMP <= 45) {
1817 if (VD->getType().getNonReferenceType()->isScalarType())
1818 return OMPC_DEFAULTMAP_scalar;
1819 return OMPC_DEFAULTMAP_aggregate;
1820 }
cchene06f3e02019-11-15 13:02:06 -05001821 if (VD->getType().getNonReferenceType()->isAnyPointerType())
1822 return OMPC_DEFAULTMAP_pointer;
1823 if (VD->getType().getNonReferenceType()->isScalarType())
1824 return OMPC_DEFAULTMAP_scalar;
1825 return OMPC_DEFAULTMAP_aggregate;
1826}
1827
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001828bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1829 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001830 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1831
Alexey Bataeve3727102018-04-18 15:57:46 +00001832 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001833 bool IsByRef = true;
1834
1835 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001836 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001837 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001838
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001839 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001840 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001841 // This table summarizes how a given variable should be passed to the device
1842 // given its type and the clauses where it appears. This table is based on
1843 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1844 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1845 //
1846 // =========================================================================
1847 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1848 // | |(tofrom:scalar)| | pvt | | | |
1849 // =========================================================================
1850 // | scl | | | | - | | bycopy|
1851 // | scl | | - | x | - | - | bycopy|
1852 // | scl | | x | - | - | - | null |
1853 // | scl | x | | | - | | byref |
1854 // | scl | x | - | x | - | - | bycopy|
1855 // | scl | x | x | - | - | - | null |
1856 // | scl | | - | - | - | x | byref |
1857 // | scl | x | - | - | - | x | byref |
1858 //
1859 // | agg | n.a. | | | - | | byref |
1860 // | agg | n.a. | - | x | - | - | byref |
1861 // | agg | n.a. | x | - | - | - | null |
1862 // | agg | n.a. | - | - | - | x | byref |
1863 // | agg | n.a. | - | - | - | x[] | byref |
1864 //
1865 // | ptr | n.a. | | | - | | bycopy|
1866 // | ptr | n.a. | - | x | - | - | bycopy|
1867 // | ptr | n.a. | x | - | - | - | null |
1868 // | ptr | n.a. | - | - | - | x | byref |
1869 // | ptr | n.a. | - | - | - | x[] | bycopy|
1870 // | ptr | n.a. | - | - | x | | bycopy|
1871 // | ptr | n.a. | - | - | x | x | bycopy|
1872 // | ptr | n.a. | - | - | x | x[] | bycopy|
1873 // =========================================================================
1874 // Legend:
1875 // scl - scalar
1876 // ptr - pointer
1877 // agg - aggregate
1878 // x - applies
1879 // - - invalid in this combination
1880 // [] - mapped with an array section
1881 // byref - should be mapped by reference
1882 // byval - should be mapped by value
1883 // null - initialize a local variable to null on the device
1884 //
1885 // Observations:
1886 // - All scalar declarations that show up in a map clause have to be passed
1887 // by reference, because they may have been mapped in the enclosing data
1888 // environment.
1889 // - If the scalar value does not fit the size of uintptr, it has to be
1890 // passed by reference, regardless the result in the table above.
1891 // - For pointers mapped by value that have either an implicit map or an
1892 // array section, the runtime library may pass the NULL value to the
1893 // device instead of the value passed to it by the compiler.
1894
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001895 if (Ty->isReferenceType())
1896 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001897
1898 // Locate map clauses and see if the variable being captured is referred to
1899 // in any of those clauses. Here we only care about variables, not fields,
1900 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001901 bool IsVariableAssociatedWithSection = false;
1902
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001903 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001904 D, Level,
1905 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1906 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001907 MapExprComponents,
1908 OpenMPClauseKind WhereFoundClauseKind) {
1909 // Only the map clause information influences how a variable is
1910 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001911 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001912 if (WhereFoundClauseKind != OMPC_map)
1913 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001914
1915 auto EI = MapExprComponents.rbegin();
1916 auto EE = MapExprComponents.rend();
1917
1918 assert(EI != EE && "Invalid map expression!");
1919
1920 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1921 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1922
1923 ++EI;
1924 if (EI == EE)
1925 return false;
1926
1927 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1928 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1929 isa<MemberExpr>(EI->getAssociatedExpression())) {
1930 IsVariableAssociatedWithSection = true;
1931 // There is nothing more we need to know about this variable.
1932 return true;
1933 }
1934
1935 // Keep looking for more map info.
1936 return false;
1937 });
1938
1939 if (IsVariableUsedInMapClause) {
1940 // If variable is identified in a map clause it is always captured by
1941 // reference except if it is a pointer that is dereferenced somehow.
1942 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1943 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001944 // By default, all the data that has a scalar type is mapped by copy
1945 // (except for reduction variables).
cchene06f3e02019-11-15 13:02:06 -05001946 // Defaultmap scalar is mutual exclusive to defaultmap pointer
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001947 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001948 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1949 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001950 !Ty->isScalarType() ||
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001951 DSAStack->isDefaultmapCapturedByRef(
1952 Level, getVariableCategoryFromDecl(LangOpts, D)) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001953 DSAStack->hasExplicitDSA(
1954 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001955 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001956 }
1957
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001958 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001959 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001960 ((IsVariableUsedInMapClause &&
1961 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1962 OMPD_target) ||
1963 !DSAStack->hasExplicitDSA(
1964 D,
1965 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1966 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001967 // If the variable is artificial and must be captured by value - try to
1968 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001969 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1970 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001971 }
1972
Samuel Antao86ace552016-04-27 22:40:57 +00001973 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001974 // and alignment, because the runtime library only deals with uintptr types.
1975 // If it does not fit the uintptr size, we need to pass the data by reference
1976 // instead.
1977 if (!IsByRef &&
1978 (Ctx.getTypeSizeInChars(Ty) >
1979 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001980 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001981 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001982 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001983
1984 return IsByRef;
1985}
1986
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001987unsigned Sema::getOpenMPNestingLevel() const {
1988 assert(getLangOpts().OpenMP);
1989 return DSAStack->getNestingLevel();
1990}
1991
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001992bool Sema::isInOpenMPTargetExecutionDirective() const {
1993 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1994 !DSAStack->isClauseParsingMode()) ||
1995 DSAStack->hasDirective(
1996 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1997 SourceLocation) -> bool {
1998 return isOpenMPTargetExecutionDirective(K);
1999 },
2000 false);
2001}
2002
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002003VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2004 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00002005 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002006 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00002007
Alexey Bataev7c860692019-10-25 16:35:32 -04002008 auto *VD = dyn_cast<VarDecl>(D);
2009 // Do not capture constexpr variables.
2010 if (VD && VD->isConstexpr())
2011 return nullptr;
2012
Richard Smith0621a8f2019-05-31 00:45:10 +00002013 // If we want to determine whether the variable should be captured from the
2014 // perspective of the current capturing scope, and we've already left all the
2015 // capturing scopes of the top directive on the stack, check from the
2016 // perspective of its parent directive (if any) instead.
2017 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2018 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2019
Samuel Antao4be30e92015-10-02 17:14:03 +00002020 // If we are attempting to capture a global variable in a directive with
2021 // 'target' we return true so that this global is also mapped to the device.
2022 //
Richard Smith0621a8f2019-05-31 00:45:10 +00002023 if (VD && !VD->hasLocalStorage() &&
2024 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2025 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002026 // Try to mark variable as declare target if it is used in capturing
2027 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00002028 if (LangOpts.OpenMP <= 45 &&
2029 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002030 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002031 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002032 } else if (isInOpenMPTargetExecutionDirective()) {
2033 // If the declaration is enclosed in a 'declare target' directive,
2034 // then it should not be captured.
2035 //
Alexey Bataev97b72212018-08-14 18:31:20 +00002036 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002037 return nullptr;
Alexey Bataev36635632020-01-17 20:39:04 -05002038 CapturedRegionScopeInfo *CSI = nullptr;
2039 for (FunctionScopeInfo *FSI : llvm::drop_begin(
2040 llvm::reverse(FunctionScopes),
2041 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2042 if (!isa<CapturingScopeInfo>(FSI))
2043 return nullptr;
2044 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2045 if (RSI->CapRegionKind == CR_OpenMP) {
2046 CSI = RSI;
2047 break;
2048 }
2049 }
2050 SmallVector<OpenMPDirectiveKind, 4> Regions;
2051 getOpenMPCaptureRegions(Regions,
2052 DSAStack->getDirective(CSI->OpenMPLevel));
2053 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2054 return VD;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002055 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002056 }
Samuel Antao4be30e92015-10-02 17:14:03 +00002057
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002058 if (CheckScopeInfo) {
2059 bool OpenMPFound = false;
2060 for (unsigned I = StopAt + 1; I > 0; --I) {
2061 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2062 if(!isa<CapturingScopeInfo>(FSI))
2063 return nullptr;
2064 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2065 if (RSI->CapRegionKind == CR_OpenMP) {
2066 OpenMPFound = true;
2067 break;
2068 }
2069 }
2070 if (!OpenMPFound)
2071 return nullptr;
2072 }
2073
Alexey Bataev48977c32015-08-04 08:10:48 +00002074 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2075 (!DSAStack->isClauseParsingMode() ||
2076 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002077 auto &&Info = DSAStack->isLoopControlVariable(D);
2078 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002079 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002080 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002081 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002082 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00002083 DSAStackTy::DSAVarData DVarPrivate =
2084 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002085 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002086 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00002087 // Threadprivate variables must not be captured.
2088 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
2089 return nullptr;
2090 // The variable is not private or it is the variable in the directive with
2091 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002092 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
2093 [](OpenMPDirectiveKind) { return true; },
2094 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002095 if (DVarPrivate.CKind != OMPC_unknown ||
2096 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002097 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002098 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00002099 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00002100}
2101
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002102void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2103 unsigned Level) const {
2104 SmallVector<OpenMPDirectiveKind, 4> Regions;
2105 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2106 FunctionScopesIndex -= Regions.size();
2107}
2108
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002109void Sema::startOpenMPLoop() {
2110 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2111 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2112 DSAStack->loopInit();
2113}
2114
Alexey Bataevbef93a92019-10-07 18:54:57 +00002115void Sema::startOpenMPCXXRangeFor() {
2116 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2117 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2118 DSAStack->resetPossibleLoopCounter();
2119 DSAStack->loopStart();
2120 }
2121}
2122
Alexey Bataeve3727102018-04-18 15:57:46 +00002123bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002124 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002125 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2126 if (DSAStack->getAssociatedLoops() > 0 &&
2127 !DSAStack->isLoopStarted()) {
2128 DSAStack->resetPossibleLoopCounter(D);
2129 DSAStack->loopStart();
2130 return true;
2131 }
2132 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2133 DSAStack->isLoopControlVariable(D).first) &&
2134 !DSAStack->hasExplicitDSA(
2135 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2136 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2137 return true;
2138 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002139 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2140 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2141 DSAStack->isForceVarCapturing() &&
2142 !DSAStack->hasExplicitDSA(
2143 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2144 return true;
2145 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002146 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002147 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002148 (DSAStack->isClauseParsingMode() &&
2149 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002150 // Consider taskgroup reduction descriptor variable a private to avoid
2151 // possible capture in the region.
2152 (DSAStack->hasExplicitDirective(
2153 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2154 Level) &&
2155 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002156}
2157
Alexey Bataeve3727102018-04-18 15:57:46 +00002158void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2159 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002160 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2161 D = getCanonicalDecl(D);
2162 OpenMPClauseKind OMPC = OMPC_unknown;
2163 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2164 const unsigned NewLevel = I - 1;
2165 if (DSAStack->hasExplicitDSA(D,
2166 [&OMPC](const OpenMPClauseKind K) {
2167 if (isOpenMPPrivate(K)) {
2168 OMPC = K;
2169 return true;
2170 }
2171 return false;
2172 },
2173 NewLevel))
2174 break;
2175 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2176 D, NewLevel,
2177 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2178 OpenMPClauseKind) { return true; })) {
2179 OMPC = OMPC_map;
2180 break;
2181 }
2182 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2183 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002184 OMPC = OMPC_map;
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002185 if (DSAStack->mustBeFirstprivateAtLevel(
2186 NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002187 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002188 break;
2189 }
2190 }
2191 if (OMPC != OMPC_unknown)
2192 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2193}
2194
Alexey Bataev36635632020-01-17 20:39:04 -05002195bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2196 unsigned CaptureLevel) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002197 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2198 // Return true if the current level is no longer enclosed in a target region.
2199
Alexey Bataev36635632020-01-17 20:39:04 -05002200 SmallVector<OpenMPDirectiveKind, 4> Regions;
2201 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
Alexey Bataeve3727102018-04-18 15:57:46 +00002202 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002203 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002204 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
Alexey Bataev36635632020-01-17 20:39:04 -05002205 Level) &&
2206 Regions[CaptureLevel] != OMPD_task;
Samuel Antao4be30e92015-10-02 17:14:03 +00002207}
2208
Alexey Bataeved09d242014-05-28 05:53:51 +00002209void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002210
Alexey Bataev729e2422019-08-23 16:11:14 +00002211void Sema::finalizeOpenMPDelayedAnalysis() {
2212 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2213 // Diagnose implicit declare target functions and their callees.
2214 for (const auto &CallerCallees : DeviceCallGraph) {
2215 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2216 OMPDeclareTargetDeclAttr::getDeviceType(
2217 CallerCallees.getFirst()->getMostRecentDecl());
2218 // Ignore host functions during device analyzis.
2219 if (LangOpts.OpenMPIsDevice && DevTy &&
2220 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2221 continue;
2222 // Ignore nohost functions during host analyzis.
2223 if (!LangOpts.OpenMPIsDevice && DevTy &&
2224 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2225 continue;
2226 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2227 &Callee : CallerCallees.getSecond()) {
2228 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2229 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2230 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2231 if (LangOpts.OpenMPIsDevice && DevTy &&
2232 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2233 // Diagnose host function called during device codegen.
2234 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2235 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2236 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2237 << HostDevTy << 0;
2238 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2239 diag::note_omp_marked_device_type_here)
2240 << HostDevTy;
2241 continue;
2242 }
2243 if (!LangOpts.OpenMPIsDevice && DevTy &&
2244 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2245 // Diagnose nohost function called during host codegen.
2246 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2247 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2248 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2249 << NoHostDevTy << 1;
2250 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2251 diag::note_omp_marked_device_type_here)
2252 << NoHostDevTy;
2253 continue;
2254 }
2255 }
2256 }
2257}
2258
Alexey Bataev758e55e2013-09-06 18:03:48 +00002259void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2260 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002261 Scope *CurScope, SourceLocation Loc) {
2262 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002263 PushExpressionEvaluationContext(
2264 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002265}
2266
Alexey Bataevaac108a2015-06-23 04:51:00 +00002267void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2268 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002269}
2270
Alexey Bataevaac108a2015-06-23 04:51:00 +00002271void Sema::EndOpenMPClause() {
2272 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002273}
2274
Alexey Bataeve106f252019-04-01 14:25:31 +00002275static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2276 ArrayRef<OMPClause *> Clauses);
Alexey Bataev0860db92019-12-19 10:01:10 -05002277static std::pair<ValueDecl *, bool>
2278getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2279 SourceRange &ERange, bool AllowArraySection = false);
2280static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2281 bool WithInit);
Alexey Bataeve106f252019-04-01 14:25:31 +00002282
Alexey Bataev758e55e2013-09-06 18:03:48 +00002283void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002284 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2285 // A variable of class type (or array thereof) that appears in a lastprivate
2286 // clause requires an accessible, unambiguous default constructor for the
2287 // class type, unless the list item is also specified in a firstprivate
2288 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002289 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2290 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002291 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2292 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002293 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002294 if (DE->isValueDependent() || DE->isTypeDependent()) {
2295 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002296 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002297 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002298 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002299 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002300 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002301 const DSAStackTy::DSAVarData DVar =
2302 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002303 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002304 // Generate helper private variable and initialize it with the
2305 // default value. The address of the original variable is replaced
2306 // by the address of the new private variable in CodeGen. This new
2307 // variable is not added to IdResolver, so the code in the OpenMP
2308 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002309 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002310 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002311 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002312 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002313 if (VDPrivate->isInvalidDecl()) {
2314 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002315 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002316 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002317 PrivateCopies.push_back(buildDeclRefExpr(
2318 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002319 } else {
2320 // The variable is also a firstprivate, so initialization sequence
2321 // for private copy is generated already.
2322 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002323 }
2324 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002325 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataev0860db92019-12-19 10:01:10 -05002326 continue;
2327 }
2328 // Finalize nontemporal clause by handling private copies, if any.
2329 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2330 SmallVector<Expr *, 8> PrivateRefs;
2331 for (Expr *RefExpr : Clause->varlists()) {
2332 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2333 SourceLocation ELoc;
2334 SourceRange ERange;
2335 Expr *SimpleRefExpr = RefExpr;
2336 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2337 if (Res.second)
2338 // It will be analyzed later.
2339 PrivateRefs.push_back(RefExpr);
2340 ValueDecl *D = Res.first;
2341 if (!D)
2342 continue;
2343
2344 const DSAStackTy::DSAVarData DVar =
2345 DSAStack->getTopDSA(D, /*FromParent=*/false);
2346 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2347 : SimpleRefExpr);
2348 }
2349 Clause->setPrivateRefs(PrivateRefs);
2350 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002351 }
2352 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002353 // Check allocate clauses.
2354 if (!CurContext->isDependentContext())
2355 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002356 }
2357
Alexey Bataev758e55e2013-09-06 18:03:48 +00002358 DSAStack->pop();
2359 DiscardCleanupsInEvaluationContext();
2360 PopExpressionEvaluationContext();
2361}
2362
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002363static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2364 Expr *NumIterations, Sema &SemaRef,
2365 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002366
Alexey Bataeva769e072013-03-22 06:34:35 +00002367namespace {
2368
Alexey Bataeve3727102018-04-18 15:57:46 +00002369class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002370private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002371 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002372
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002373public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002374 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002375 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002376 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002377 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002378 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002379 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2380 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002381 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002382 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002383 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002384
2385 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002386 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002387 }
2388
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002389};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002390
Alexey Bataeve3727102018-04-18 15:57:46 +00002391class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002392private:
2393 Sema &SemaRef;
2394
2395public:
2396 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2397 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2398 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002399 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2400 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002401 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2402 SemaRef.getCurScope());
2403 }
2404 return false;
2405 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002406
2407 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002408 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002409 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002410};
2411
Alexey Bataeved09d242014-05-28 05:53:51 +00002412} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002413
2414ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2415 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002416 const DeclarationNameInfo &Id,
2417 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002418 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2419 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2420
2421 if (Lookup.isAmbiguous())
2422 return ExprError();
2423
2424 VarDecl *VD;
2425 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002426 VarDeclFilterCCC CCC(*this);
2427 if (TypoCorrection Corrected =
2428 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2429 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002430 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002431 PDiag(Lookup.empty()
2432 ? diag::err_undeclared_var_use_suggest
2433 : diag::err_omp_expected_var_arg_suggest)
2434 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002435 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002436 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002437 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2438 : diag::err_omp_expected_var_arg)
2439 << Id.getName();
2440 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002441 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002442 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2443 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2444 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2445 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002446 }
2447 Lookup.suppressDiagnostics();
2448
2449 // OpenMP [2.9.2, Syntax, C/C++]
2450 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002451 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002452 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002453 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002454 bool IsDecl =
2455 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002456 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002457 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2458 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002459 return ExprError();
2460 }
2461
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002462 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002463 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002464 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2465 // A threadprivate directive for file-scope variables must appear outside
2466 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002467 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2468 !getCurLexicalContext()->isTranslationUnit()) {
2469 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002470 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002471 bool IsDecl =
2472 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2473 Diag(VD->getLocation(),
2474 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2475 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002476 return ExprError();
2477 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002478 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2479 // A threadprivate directive for static class member variables must appear
2480 // in the class definition, in the same scope in which the member
2481 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002482 if (CanonicalVD->isStaticDataMember() &&
2483 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2484 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002485 << getOpenMPDirectiveName(Kind) << VD;
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 Bataev7d2960b2013-09-26 03:24:06 +00002491 return ExprError();
2492 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002493 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2494 // A threadprivate directive for namespace-scope variables must appear
2495 // outside any definition or declaration other than the namespace
2496 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002497 if (CanonicalVD->getDeclContext()->isNamespace() &&
2498 (!getCurLexicalContext()->isFileContext() ||
2499 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2500 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002501 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002502 bool IsDecl =
2503 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2504 Diag(VD->getLocation(),
2505 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2506 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002507 return ExprError();
2508 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002509 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2510 // A threadprivate directive for static block-scope variables must appear
2511 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002512 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002513 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002514 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002515 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002516 bool IsDecl =
2517 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2518 Diag(VD->getLocation(),
2519 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2520 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002521 return ExprError();
2522 }
2523
2524 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2525 // A threadprivate directive must lexically precede all references to any
2526 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002527 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2528 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002529 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002530 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002531 return ExprError();
2532 }
2533
2534 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002535 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2536 SourceLocation(), VD,
2537 /*RefersToEnclosingVariableOrCapture=*/false,
2538 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002539}
2540
Alexey Bataeved09d242014-05-28 05:53:51 +00002541Sema::DeclGroupPtrTy
2542Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2543 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002544 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002545 CurContext->addDecl(D);
2546 return DeclGroupPtrTy::make(DeclGroupRef(D));
2547 }
David Blaikie0403cb12016-01-15 23:43:25 +00002548 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002549}
2550
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002551namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002552class LocalVarRefChecker final
2553 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002554 Sema &SemaRef;
2555
2556public:
2557 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002558 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002559 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002560 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002561 diag::err_omp_local_var_in_threadprivate_init)
2562 << E->getSourceRange();
2563 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2564 << VD << VD->getSourceRange();
2565 return true;
2566 }
2567 }
2568 return false;
2569 }
2570 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002571 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002572 if (Child && Visit(Child))
2573 return true;
2574 }
2575 return false;
2576 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002577 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002578};
2579} // namespace
2580
Alexey Bataeved09d242014-05-28 05:53:51 +00002581OMPThreadPrivateDecl *
2582Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002583 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002584 for (Expr *RefExpr : VarList) {
2585 auto *DE = cast<DeclRefExpr>(RefExpr);
2586 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002587 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002588
Alexey Bataev376b4a42016-02-09 09:41:09 +00002589 // Mark variable as used.
2590 VD->setReferenced();
2591 VD->markUsed(Context);
2592
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002593 QualType QType = VD->getType();
2594 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2595 // It will be analyzed later.
2596 Vars.push_back(DE);
2597 continue;
2598 }
2599
Alexey Bataeva769e072013-03-22 06:34:35 +00002600 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2601 // A threadprivate variable must not have an incomplete type.
2602 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002603 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002604 continue;
2605 }
2606
2607 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2608 // A threadprivate variable must not have a reference type.
2609 if (VD->getType()->isReferenceType()) {
2610 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002611 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2612 bool IsDecl =
2613 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2614 Diag(VD->getLocation(),
2615 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2616 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002617 continue;
2618 }
2619
Samuel Antaof8b50122015-07-13 22:54:53 +00002620 // Check if this is a TLS variable. If TLS is not being supported, produce
2621 // the corresponding diagnostic.
2622 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2623 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2624 getLangOpts().OpenMPUseTLS &&
2625 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002626 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2627 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002628 Diag(ILoc, diag::err_omp_var_thread_local)
2629 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002630 bool IsDecl =
2631 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2632 Diag(VD->getLocation(),
2633 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2634 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002635 continue;
2636 }
2637
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002638 // Check if initial value of threadprivate variable reference variable with
2639 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002640 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002641 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002642 if (Checker.Visit(Init))
2643 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002644 }
2645
Alexey Bataeved09d242014-05-28 05:53:51 +00002646 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002647 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002648 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2649 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002650 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002651 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002652 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002653 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002654 if (!Vars.empty()) {
2655 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2656 Vars);
2657 D->setAccess(AS_public);
2658 }
2659 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002660}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002661
Alexey Bataev27ef9512019-03-20 20:14:22 +00002662static OMPAllocateDeclAttr::AllocatorTypeTy
2663getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2664 if (!Allocator)
2665 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2666 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2667 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002668 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002669 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002670 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002671 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002672 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2673 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2674 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002675 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002676 llvm::FoldingSetNodeID AEId, DAEId;
2677 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2678 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2679 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002680 AllocatorKindRes = AllocatorKind;
2681 break;
2682 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002683 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002684 return AllocatorKindRes;
2685}
2686
Alexey Bataeve106f252019-04-01 14:25:31 +00002687static bool checkPreviousOMPAllocateAttribute(
2688 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2689 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2690 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2691 return false;
2692 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2693 Expr *PrevAllocator = A->getAllocator();
2694 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2695 getAllocatorKind(S, Stack, PrevAllocator);
2696 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2697 if (AllocatorsMatch &&
2698 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2699 Allocator && PrevAllocator) {
2700 const Expr *AE = Allocator->IgnoreParenImpCasts();
2701 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2702 llvm::FoldingSetNodeID AEId, PAEId;
2703 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2704 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2705 AllocatorsMatch = AEId == PAEId;
2706 }
2707 if (!AllocatorsMatch) {
2708 SmallString<256> AllocatorBuffer;
2709 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2710 if (Allocator)
2711 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2712 SmallString<256> PrevAllocatorBuffer;
2713 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2714 if (PrevAllocator)
2715 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2716 S.getPrintingPolicy());
2717
2718 SourceLocation AllocatorLoc =
2719 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2720 SourceRange AllocatorRange =
2721 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2722 SourceLocation PrevAllocatorLoc =
2723 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2724 SourceRange PrevAllocatorRange =
2725 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2726 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2727 << (Allocator ? 1 : 0) << AllocatorStream.str()
2728 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2729 << AllocatorRange;
2730 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2731 << PrevAllocatorRange;
2732 return true;
2733 }
2734 return false;
2735}
2736
2737static void
2738applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2739 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2740 Expr *Allocator, SourceRange SR) {
2741 if (VD->hasAttr<OMPAllocateDeclAttr>())
2742 return;
2743 if (Allocator &&
2744 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2745 Allocator->isInstantiationDependent() ||
2746 Allocator->containsUnexpandedParameterPack()))
2747 return;
2748 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2749 Allocator, SR);
2750 VD->addAttr(A);
2751 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2752 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2753}
2754
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002755Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2756 SourceLocation Loc, ArrayRef<Expr *> VarList,
2757 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2758 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2759 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002760 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002761 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2762 // allocate directives that appear in a target region must specify an
2763 // allocator clause unless a requires directive with the dynamic_allocators
2764 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002765 if (LangOpts.OpenMPIsDevice &&
2766 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002767 targetDiag(Loc, diag::err_expected_allocator_clause);
2768 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002769 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002770 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002771 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2772 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002773 SmallVector<Expr *, 8> Vars;
2774 for (Expr *RefExpr : VarList) {
2775 auto *DE = cast<DeclRefExpr>(RefExpr);
2776 auto *VD = cast<VarDecl>(DE->getDecl());
2777
2778 // Check if this is a TLS variable or global register.
2779 if (VD->getTLSKind() != VarDecl::TLS_None ||
2780 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2781 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2782 !VD->isLocalVarDecl()))
2783 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002784
Alexey Bataev282555a2019-03-19 20:33:44 +00002785 // If the used several times in the allocate directive, the same allocator
2786 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002787 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2788 AllocatorKind, Allocator))
2789 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002790
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002791 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2792 // If a list item has a static storage type, the allocator expression in the
2793 // allocator clause must be a constant expression that evaluates to one of
2794 // the predefined memory allocator values.
2795 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002796 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002797 Diag(Allocator->getExprLoc(),
2798 diag::err_omp_expected_predefined_allocator)
2799 << Allocator->getSourceRange();
2800 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2801 VarDecl::DeclarationOnly;
2802 Diag(VD->getLocation(),
2803 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2804 << VD;
2805 continue;
2806 }
2807 }
2808
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002809 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002810 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2811 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002812 }
2813 if (Vars.empty())
2814 return nullptr;
2815 if (!Owner)
2816 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002817 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002818 D->setAccess(AS_public);
2819 Owner->addDecl(D);
2820 return DeclGroupPtrTy::make(DeclGroupRef(D));
2821}
2822
2823Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002824Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2825 ArrayRef<OMPClause *> ClauseList) {
2826 OMPRequiresDecl *D = nullptr;
2827 if (!CurContext->isFileContext()) {
2828 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2829 } else {
2830 D = CheckOMPRequiresDecl(Loc, ClauseList);
2831 if (D) {
2832 CurContext->addDecl(D);
2833 DSAStack->addRequiresDecl(D);
2834 }
2835 }
2836 return DeclGroupPtrTy::make(DeclGroupRef(D));
2837}
2838
2839OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2840 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002841 /// For target specific clauses, the requires directive cannot be
2842 /// specified after the handling of any of the target regions in the
2843 /// current compilation unit.
2844 ArrayRef<SourceLocation> TargetLocations =
2845 DSAStack->getEncounteredTargetLocs();
Alexey Bataev2d4f80f2020-02-11 15:15:21 -05002846 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
2847 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002848 for (const OMPClause *CNew : ClauseList) {
2849 // Check if any of the requires clauses affect target regions.
2850 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2851 isa<OMPUnifiedAddressClause>(CNew) ||
2852 isa<OMPReverseOffloadClause>(CNew) ||
2853 isa<OMPDynamicAllocatorsClause>(CNew)) {
Alexey Bataev2d4f80f2020-02-11 15:15:21 -05002854 Diag(Loc, diag::err_omp_directive_before_requires)
2855 << "target" << getOpenMPClauseName(CNew->getClauseKind());
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002856 for (SourceLocation TargetLoc : TargetLocations) {
Alexey Bataev2d4f80f2020-02-11 15:15:21 -05002857 Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
2858 << "target";
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002859 }
Alexey Bataev2d4f80f2020-02-11 15:15:21 -05002860 } else if (!AtomicLoc.isInvalid() &&
2861 isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
2862 Diag(Loc, diag::err_omp_directive_before_requires)
2863 << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
2864 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
2865 << "atomic";
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002866 }
2867 }
2868 }
2869
Kelvin Li1408f912018-09-26 04:28:39 +00002870 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2871 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2872 ClauseList);
2873 return nullptr;
2874}
2875
Alexey Bataeve3727102018-04-18 15:57:46 +00002876static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2877 const ValueDecl *D,
2878 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002879 bool IsLoopIterVar = false) {
2880 if (DVar.RefExpr) {
2881 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2882 << getOpenMPClauseName(DVar.CKind);
2883 return;
2884 }
2885 enum {
2886 PDSA_StaticMemberShared,
2887 PDSA_StaticLocalVarShared,
2888 PDSA_LoopIterVarPrivate,
2889 PDSA_LoopIterVarLinear,
2890 PDSA_LoopIterVarLastprivate,
2891 PDSA_ConstVarShared,
2892 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002893 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002894 PDSA_LocalVarPrivate,
2895 PDSA_Implicit
2896 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002897 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002898 auto ReportLoc = D->getLocation();
2899 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002900 if (IsLoopIterVar) {
2901 if (DVar.CKind == OMPC_private)
2902 Reason = PDSA_LoopIterVarPrivate;
2903 else if (DVar.CKind == OMPC_lastprivate)
2904 Reason = PDSA_LoopIterVarLastprivate;
2905 else
2906 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002907 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2908 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002909 Reason = PDSA_TaskVarFirstprivate;
2910 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002911 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002912 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002913 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002914 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002915 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002916 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002917 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002918 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002919 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002920 ReportHint = true;
2921 Reason = PDSA_LocalVarPrivate;
2922 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002923 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002924 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002925 << Reason << ReportHint
2926 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2927 } else if (DVar.ImplicitDSALoc.isValid()) {
2928 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2929 << getOpenMPClauseName(DVar.CKind);
2930 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002931}
2932
cchene06f3e02019-11-15 13:02:06 -05002933static OpenMPMapClauseKind
2934getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
2935 bool IsAggregateOrDeclareTarget) {
2936 OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
2937 switch (M) {
2938 case OMPC_DEFAULTMAP_MODIFIER_alloc:
2939 Kind = OMPC_MAP_alloc;
2940 break;
2941 case OMPC_DEFAULTMAP_MODIFIER_to:
2942 Kind = OMPC_MAP_to;
2943 break;
2944 case OMPC_DEFAULTMAP_MODIFIER_from:
2945 Kind = OMPC_MAP_from;
2946 break;
2947 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
2948 Kind = OMPC_MAP_tofrom;
2949 break;
2950 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
2951 case OMPC_DEFAULTMAP_MODIFIER_last:
2952 llvm_unreachable("Unexpected defaultmap implicit behavior");
2953 case OMPC_DEFAULTMAP_MODIFIER_none:
2954 case OMPC_DEFAULTMAP_MODIFIER_default:
2955 case OMPC_DEFAULTMAP_MODIFIER_unknown:
2956 // IsAggregateOrDeclareTarget could be true if:
2957 // 1. the implicit behavior for aggregate is tofrom
2958 // 2. it's a declare target link
2959 if (IsAggregateOrDeclareTarget) {
2960 Kind = OMPC_MAP_tofrom;
2961 break;
2962 }
2963 llvm_unreachable("Unexpected defaultmap implicit behavior");
2964 }
2965 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
2966 return Kind;
2967}
2968
Alexey Bataev758e55e2013-09-06 18:03:48 +00002969namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002970class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002971 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002972 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002973 bool ErrorFound = false;
Alexey Bataevc09c0652019-10-29 10:06:11 -04002974 bool TryCaptureCXXThisMembers = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00002975 CapturedStmt *CS = nullptr;
2976 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
cchene06f3e02019-11-15 13:02:06 -05002977 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
Alexey Bataeve3727102018-04-18 15:57:46 +00002978 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2979 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002980
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002981 void VisitSubCaptures(OMPExecutableDirective *S) {
2982 // Check implicitly captured variables.
2983 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2984 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002985 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataevc09c0652019-10-29 10:06:11 -04002986 // Try to capture inner this->member references to generate correct mappings
2987 // and diagnostics.
2988 if (TryCaptureCXXThisMembers ||
2989 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2990 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2991 [](const CapturedStmt::Capture &C) {
2992 return C.capturesThis();
2993 }))) {
2994 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2995 TryCaptureCXXThisMembers = true;
2996 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2997 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2998 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002999 }
3000
Alexey Bataev758e55e2013-09-06 18:03:48 +00003001public:
3002 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataevc09c0652019-10-29 10:06:11 -04003003 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3004 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3005 E->isInstantiationDependent())
Alexey Bataev07b79c22016-04-29 09:56:11 +00003006 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003007 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00003008 // Check the datasharing rules for the expressions in the clauses.
3009 if (!CS) {
3010 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3011 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3012 Visit(CED->getInit());
3013 return;
3014 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003015 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3016 // Do not analyze internal variables and do not enclose them into
3017 // implicit clauses.
3018 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003019 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003020 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00003021 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00003022 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003023
Alexey Bataeve3727102018-04-18 15:57:46 +00003024 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003025 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003026 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00003027 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003028
Alexey Bataevafe50572017-10-06 17:00:28 +00003029 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00003030 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00003031 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00003032 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00003033 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3034 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00003035 return;
3036
Alexey Bataeve3727102018-04-18 15:57:46 +00003037 SourceLocation ELoc = E->getExprLoc();
3038 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003039 // The default(none) clause requires that each variable that is referenced
3040 // in the construct, and does not have a predetermined data-sharing
3041 // attribute, must have its data-sharing attribute explicitly determined
3042 // by being listed in a data-sharing attribute clause.
3043 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00003044 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00003045 VarsWithInheritedDSA.count(VD) == 0) {
3046 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003047 return;
3048 }
3049
cchene06f3e02019-11-15 13:02:06 -05003050 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3051 // If implicit-behavior is none, each variable referenced in the
3052 // construct that does not have a predetermined data-sharing attribute
3053 // and does not appear in a to or link clause on a declare target
3054 // directive must be listed in a data-mapping attribute clause, a
3055 // data-haring attribute clause (including a data-sharing attribute
3056 // clause on a combined construct where target. is one of the
3057 // constituent constructs), or an is_device_ptr clause.
Alexey Bataev6f7c8762019-11-22 11:09:33 -05003058 OpenMPDefaultmapClauseKind ClauseKind =
3059 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
cchene06f3e02019-11-15 13:02:06 -05003060 if (SemaRef.getLangOpts().OpenMP >= 50) {
3061 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3062 OMPC_DEFAULTMAP_MODIFIER_none;
3063 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3064 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3065 // Only check for data-mapping attribute and is_device_ptr here
3066 // since we have already make sure that the declaration does not
3067 // have a data-sharing attribute above
3068 if (!Stack->checkMappableExprComponentListsForDecl(
3069 VD, /*CurrentRegionOnly=*/true,
3070 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3071 MapExprComponents,
3072 OpenMPClauseKind) {
3073 auto MI = MapExprComponents.rbegin();
3074 auto ME = MapExprComponents.rend();
3075 return MI != ME && MI->getAssociatedDeclaration() == VD;
3076 })) {
3077 VarsWithInheritedDSA[VD] = E;
3078 return;
3079 }
3080 }
3081 }
3082
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003083 if (isOpenMPTargetExecutionDirective(DKind) &&
3084 !Stack->isLoopControlVariable(VD).first) {
3085 if (!Stack->checkMappableExprComponentListsForDecl(
3086 VD, /*CurrentRegionOnly=*/true,
3087 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3088 StackComponents,
3089 OpenMPClauseKind) {
3090 // Variable is used if it has been marked as an array, array
3091 // section or the variable iself.
3092 return StackComponents.size() == 1 ||
3093 std::all_of(
3094 std::next(StackComponents.rbegin()),
3095 StackComponents.rend(),
3096 [](const OMPClauseMappableExprCommon::
3097 MappableComponent &MC) {
3098 return MC.getAssociatedDeclaration() ==
3099 nullptr &&
3100 (isa<OMPArraySectionExpr>(
3101 MC.getAssociatedExpression()) ||
3102 isa<ArraySubscriptExpr>(
3103 MC.getAssociatedExpression()));
3104 });
3105 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003106 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003107 // By default lambdas are captured as firstprivates.
3108 if (const auto *RD =
3109 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003110 IsFirstprivate = RD->isLambda();
3111 IsFirstprivate =
cchene06f3e02019-11-15 13:02:06 -05003112 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3113 if (IsFirstprivate) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003114 ImplicitFirstprivate.emplace_back(E);
cchene06f3e02019-11-15 13:02:06 -05003115 } else {
3116 OpenMPDefaultmapClauseModifier M =
3117 Stack->getDefaultmapModifier(ClauseKind);
3118 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3119 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3120 ImplicitMap[Kind].emplace_back(E);
3121 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003122 return;
3123 }
3124 }
3125
Alexey Bataev758e55e2013-09-06 18:03:48 +00003126 // OpenMP [2.9.3.6, Restrictions, p.2]
3127 // A list item that appears in a reduction clause of the innermost
3128 // enclosing worksharing or parallel construct may not be accessed in an
3129 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003130 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003131 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3132 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003133 return isOpenMPParallelDirective(K) ||
3134 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3135 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00003136 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003137 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00003138 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00003139 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003140 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00003141 return;
3142 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003143
3144 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003145 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003146 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00003147 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003148 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00003149 return;
3150 }
3151
3152 // Store implicitly used globals with declare target link for parent
3153 // target.
3154 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3155 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3156 Stack->addToParentTargetRegionLinkGlobals(E);
3157 return;
3158 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003159 }
3160 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003161 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00003162 if (E->isTypeDependent() || E->isValueDependent() ||
3163 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3164 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003165 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003166 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00003167 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003168 if (!FD)
3169 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003170 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003171 // Check if the variable has explicit DSA set and stop analysis if it
3172 // so.
3173 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3174 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003175
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003176 if (isOpenMPTargetExecutionDirective(DKind) &&
3177 !Stack->isLoopControlVariable(FD).first &&
3178 !Stack->checkMappableExprComponentListsForDecl(
3179 FD, /*CurrentRegionOnly=*/true,
3180 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3181 StackComponents,
3182 OpenMPClauseKind) {
3183 return isa<CXXThisExpr>(
3184 cast<MemberExpr>(
3185 StackComponents.back().getAssociatedExpression())
3186 ->getBase()
3187 ->IgnoreParens());
3188 })) {
3189 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3190 // A bit-field cannot appear in a map clause.
3191 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003192 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003193 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00003194
3195 // Check to see if the member expression is referencing a class that
3196 // has already been explicitly mapped
3197 if (Stack->isClassPreviouslyMapped(TE->getType()))
3198 return;
3199
cchene06f3e02019-11-15 13:02:06 -05003200 OpenMPDefaultmapClauseModifier Modifier =
3201 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3202 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3203 Modifier, /*IsAggregateOrDeclareTarget*/ true);
3204 ImplicitMap[Kind].emplace_back(E);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003205 return;
3206 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003207
Alexey Bataeve3727102018-04-18 15:57:46 +00003208 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003209 // OpenMP [2.9.3.6, Restrictions, p.2]
3210 // A list item that appears in a reduction clause of the innermost
3211 // enclosing worksharing or parallel construct may not be accessed in
3212 // an explicit task.
3213 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003214 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3215 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003216 return isOpenMPParallelDirective(K) ||
3217 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3218 },
3219 /*FromParent=*/true);
3220 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3221 ErrorFound = true;
3222 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003223 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003224 return;
3225 }
3226
3227 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003228 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003229 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00003230 !Stack->isLoopControlVariable(FD).first) {
3231 // Check if there is a captured expression for the current field in the
3232 // region. Do not mark it as firstprivate unless there is no captured
3233 // expression.
3234 // TODO: try to make it firstprivate.
3235 if (DVar.CKind != OMPC_unknown)
3236 ImplicitFirstprivate.push_back(E);
3237 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003238 return;
3239 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003240 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003241 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00003242 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003243 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003244 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003245 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003246 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3247 if (!Stack->checkMappableExprComponentListsForDecl(
3248 VD, /*CurrentRegionOnly=*/true,
3249 [&CurComponents](
3250 OMPClauseMappableExprCommon::MappableExprComponentListRef
3251 StackComponents,
3252 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003253 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003254 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003255 for (const auto &SC : llvm::reverse(StackComponents)) {
3256 // Do both expressions have the same kind?
3257 if (CCI->getAssociatedExpression()->getStmtClass() !=
3258 SC.getAssociatedExpression()->getStmtClass())
3259 if (!(isa<OMPArraySectionExpr>(
3260 SC.getAssociatedExpression()) &&
3261 isa<ArraySubscriptExpr>(
3262 CCI->getAssociatedExpression())))
3263 return false;
3264
Alexey Bataeve3727102018-04-18 15:57:46 +00003265 const Decl *CCD = CCI->getAssociatedDeclaration();
3266 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003267 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3268 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3269 if (SCD != CCD)
3270 return false;
3271 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003272 if (CCI == CCE)
3273 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003274 }
3275 return true;
3276 })) {
3277 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003278 }
Alexey Bataevc09c0652019-10-29 10:06:11 -04003279 } else if (!TryCaptureCXXThisMembers) {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003280 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003281 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003282 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003283 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003284 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003285 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003286 // for task|target directives.
3287 // Skip analysis of arguments of implicitly defined map clause for target
3288 // directives.
3289 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3290 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003291 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003292 if (CC)
3293 Visit(CC);
3294 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003295 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003296 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003297 // Check implicitly captured variables.
3298 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003299 }
3300 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003301 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003302 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003303 // Check implicitly captured variables in the task-based directives to
3304 // check if they must be firstprivatized.
3305 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003306 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003307 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003308 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003309
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003310 void visitSubCaptures(CapturedStmt *S) {
3311 for (const CapturedStmt::Capture &Cap : S->captures()) {
3312 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3313 continue;
3314 VarDecl *VD = Cap.getCapturedVar();
3315 // Do not try to map the variable if it or its sub-component was mapped
3316 // already.
3317 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3318 Stack->checkMappableExprComponentListsForDecl(
3319 VD, /*CurrentRegionOnly=*/true,
3320 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3321 OpenMPClauseKind) { return true; }))
3322 continue;
3323 DeclRefExpr *DRE = buildDeclRefExpr(
3324 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3325 Cap.getLocation(), /*RefersToCapture=*/true);
3326 Visit(DRE);
3327 }
3328 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003329 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003330 ArrayRef<Expr *> getImplicitFirstprivate() const {
3331 return ImplicitFirstprivate;
3332 }
cchene06f3e02019-11-15 13:02:06 -05003333 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3334 return ImplicitMap[Kind];
3335 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003336 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003337 return VarsWithInheritedDSA;
3338 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003339
Alexey Bataev7ff55242014-06-19 09:13:45 +00003340 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003341 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3342 // Process declare target link variables for the target directives.
3343 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3344 for (DeclRefExpr *E : Stack->getLinkGlobals())
3345 Visit(E);
3346 }
3347 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003348};
Alexey Bataeved09d242014-05-28 05:53:51 +00003349} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003350
Alexey Bataevbae9a792014-06-27 10:37:06 +00003351void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003352 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003353 case OMPD_parallel:
3354 case OMPD_parallel_for:
3355 case OMPD_parallel_for_simd:
3356 case OMPD_parallel_sections:
cchen47d60942019-12-05 13:43:48 -05003357 case OMPD_parallel_master:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003358 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003359 case OMPD_teams_distribute:
3360 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003361 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003362 QualType KmpInt32PtrTy =
3363 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003364 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003365 std::make_pair(".global_tid.", KmpInt32PtrTy),
3366 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3367 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003368 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003369 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3370 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003371 break;
3372 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003373 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003374 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003375 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003376 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003377 case OMPD_target_teams_distribute:
3378 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003379 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3380 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3381 QualType KmpInt32PtrTy =
3382 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3383 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003384 FunctionProtoType::ExtProtoInfo EPI;
3385 EPI.Variadic = true;
3386 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3387 Sema::CapturedParamNameType Params[] = {
3388 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003389 std::make_pair(".part_id.", KmpInt32PtrTy),
3390 std::make_pair(".privates.", VoidPtrTy),
3391 std::make_pair(
3392 ".copy_fn.",
3393 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003394 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3395 std::make_pair(StringRef(), QualType()) // __context with shared vars
3396 };
3397 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003398 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003399 // Mark this captured region as inlined, because we don't use outlined
3400 // function directly.
3401 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3402 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003403 Context, {}, AttributeCommonInfo::AS_Keyword,
3404 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003405 Sema::CapturedParamNameType ParamsTarget[] = {
3406 std::make_pair(StringRef(), QualType()) // __context with shared vars
3407 };
3408 // Start a captured region for 'target' with no implicit parameters.
3409 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003410 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003411 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003412 std::make_pair(".global_tid.", KmpInt32PtrTy),
3413 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3414 std::make_pair(StringRef(), QualType()) // __context with shared vars
3415 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003416 // Start a captured region for 'teams' or 'parallel'. Both regions have
3417 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003418 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003419 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003420 break;
3421 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003422 case OMPD_target:
3423 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003424 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3425 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3426 QualType KmpInt32PtrTy =
3427 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3428 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003429 FunctionProtoType::ExtProtoInfo EPI;
3430 EPI.Variadic = true;
3431 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3432 Sema::CapturedParamNameType Params[] = {
3433 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003434 std::make_pair(".part_id.", KmpInt32PtrTy),
3435 std::make_pair(".privates.", VoidPtrTy),
3436 std::make_pair(
3437 ".copy_fn.",
3438 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003439 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3440 std::make_pair(StringRef(), QualType()) // __context with shared vars
3441 };
3442 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003443 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003444 // Mark this captured region as inlined, because we don't use outlined
3445 // function directly.
3446 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3447 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003448 Context, {}, AttributeCommonInfo::AS_Keyword,
3449 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003450 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003451 std::make_pair(StringRef(), QualType()),
3452 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003453 break;
3454 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003455 case OMPD_simd:
3456 case OMPD_for:
3457 case OMPD_for_simd:
3458 case OMPD_sections:
3459 case OMPD_section:
3460 case OMPD_single:
3461 case OMPD_master:
3462 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003463 case OMPD_taskgroup:
3464 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003465 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003466 case OMPD_ordered:
3467 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003468 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003469 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003470 std::make_pair(StringRef(), QualType()) // __context with shared vars
3471 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003472 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3473 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003474 break;
3475 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003476 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003477 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3478 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3479 QualType KmpInt32PtrTy =
3480 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3481 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003482 FunctionProtoType::ExtProtoInfo EPI;
3483 EPI.Variadic = true;
3484 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003485 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003486 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003487 std::make_pair(".part_id.", KmpInt32PtrTy),
3488 std::make_pair(".privates.", VoidPtrTy),
3489 std::make_pair(
3490 ".copy_fn.",
3491 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003492 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003493 std::make_pair(StringRef(), QualType()) // __context with shared vars
3494 };
3495 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3496 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003497 // Mark this captured region as inlined, because we don't use outlined
3498 // function directly.
3499 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3500 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003501 Context, {}, AttributeCommonInfo::AS_Keyword,
3502 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003503 break;
3504 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003505 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003506 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003507 case OMPD_master_taskloop:
3508 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003509 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003510 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3511 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003512 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003513 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3514 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003515 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003516 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3517 .withConst();
3518 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3519 QualType KmpInt32PtrTy =
3520 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3521 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003522 FunctionProtoType::ExtProtoInfo EPI;
3523 EPI.Variadic = true;
3524 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003525 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003526 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003527 std::make_pair(".part_id.", KmpInt32PtrTy),
3528 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003529 std::make_pair(
3530 ".copy_fn.",
3531 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3532 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3533 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003534 std::make_pair(".ub.", KmpUInt64Ty),
3535 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003536 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003537 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003538 std::make_pair(StringRef(), QualType()) // __context with shared vars
3539 };
3540 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3541 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003542 // Mark this captured region as inlined, because we don't use outlined
3543 // function directly.
3544 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3545 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003546 Context, {}, AttributeCommonInfo::AS_Keyword,
3547 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003548 break;
3549 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04003550 case OMPD_parallel_master_taskloop:
3551 case OMPD_parallel_master_taskloop_simd: {
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003552 QualType KmpInt32Ty =
3553 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3554 .withConst();
3555 QualType KmpUInt64Ty =
3556 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3557 .withConst();
3558 QualType KmpInt64Ty =
3559 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3560 .withConst();
3561 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3562 QualType KmpInt32PtrTy =
3563 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3564 Sema::CapturedParamNameType ParamsParallel[] = {
3565 std::make_pair(".global_tid.", KmpInt32PtrTy),
3566 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3567 std::make_pair(StringRef(), QualType()) // __context with shared vars
3568 };
3569 // Start a captured region for 'parallel'.
3570 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3571 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3572 QualType Args[] = {VoidPtrTy};
3573 FunctionProtoType::ExtProtoInfo EPI;
3574 EPI.Variadic = true;
3575 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3576 Sema::CapturedParamNameType Params[] = {
3577 std::make_pair(".global_tid.", KmpInt32Ty),
3578 std::make_pair(".part_id.", KmpInt32PtrTy),
3579 std::make_pair(".privates.", VoidPtrTy),
3580 std::make_pair(
3581 ".copy_fn.",
3582 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3583 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3584 std::make_pair(".lb.", KmpUInt64Ty),
3585 std::make_pair(".ub.", KmpUInt64Ty),
3586 std::make_pair(".st.", KmpInt64Ty),
3587 std::make_pair(".liter.", KmpInt32Ty),
3588 std::make_pair(".reductions.", VoidPtrTy),
3589 std::make_pair(StringRef(), QualType()) // __context with shared vars
3590 };
3591 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3592 Params, /*OpenMPCaptureLevel=*/2);
3593 // Mark this captured region as inlined, because we don't use outlined
3594 // function directly.
3595 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3596 AlwaysInlineAttr::CreateImplicit(
3597 Context, {}, AttributeCommonInfo::AS_Keyword,
3598 AlwaysInlineAttr::Keyword_forceinline));
3599 break;
3600 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003601 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003602 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003603 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003604 QualType KmpInt32PtrTy =
3605 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3606 Sema::CapturedParamNameType Params[] = {
3607 std::make_pair(".global_tid.", KmpInt32PtrTy),
3608 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003609 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3610 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003611 std::make_pair(StringRef(), QualType()) // __context with shared vars
3612 };
3613 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3614 Params);
3615 break;
3616 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003617 case OMPD_target_teams_distribute_parallel_for:
3618 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003619 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003620 QualType KmpInt32PtrTy =
3621 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003622 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003623
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003624 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003625 FunctionProtoType::ExtProtoInfo EPI;
3626 EPI.Variadic = true;
3627 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3628 Sema::CapturedParamNameType Params[] = {
3629 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003630 std::make_pair(".part_id.", KmpInt32PtrTy),
3631 std::make_pair(".privates.", VoidPtrTy),
3632 std::make_pair(
3633 ".copy_fn.",
3634 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003635 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3636 std::make_pair(StringRef(), QualType()) // __context with shared vars
3637 };
3638 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003639 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003640 // Mark this captured region as inlined, because we don't use outlined
3641 // function directly.
3642 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3643 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003644 Context, {}, AttributeCommonInfo::AS_Keyword,
3645 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003646 Sema::CapturedParamNameType ParamsTarget[] = {
3647 std::make_pair(StringRef(), QualType()) // __context with shared vars
3648 };
3649 // Start a captured region for 'target' with no implicit parameters.
3650 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003651 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003652
3653 Sema::CapturedParamNameType ParamsTeams[] = {
3654 std::make_pair(".global_tid.", KmpInt32PtrTy),
3655 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3656 std::make_pair(StringRef(), QualType()) // __context with shared vars
3657 };
3658 // Start a captured region for 'target' with no implicit parameters.
3659 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003660 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003661
3662 Sema::CapturedParamNameType ParamsParallel[] = {
3663 std::make_pair(".global_tid.", KmpInt32PtrTy),
3664 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003665 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3666 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003667 std::make_pair(StringRef(), QualType()) // __context with shared vars
3668 };
3669 // Start a captured region for 'teams' or 'parallel'. Both regions have
3670 // the same implicit parameters.
3671 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003672 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003673 break;
3674 }
3675
Alexey Bataev46506272017-12-05 17:41:34 +00003676 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003677 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003678 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003679 QualType KmpInt32PtrTy =
3680 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3681
3682 Sema::CapturedParamNameType ParamsTeams[] = {
3683 std::make_pair(".global_tid.", KmpInt32PtrTy),
3684 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3685 std::make_pair(StringRef(), QualType()) // __context with shared vars
3686 };
3687 // Start a captured region for 'target' with no implicit parameters.
3688 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003689 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003690
3691 Sema::CapturedParamNameType ParamsParallel[] = {
3692 std::make_pair(".global_tid.", KmpInt32PtrTy),
3693 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003694 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3695 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003696 std::make_pair(StringRef(), QualType()) // __context with shared vars
3697 };
3698 // Start a captured region for 'teams' or 'parallel'. Both regions have
3699 // the same implicit parameters.
3700 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003701 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003702 break;
3703 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003704 case OMPD_target_update:
3705 case OMPD_target_enter_data:
3706 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003707 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3708 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3709 QualType KmpInt32PtrTy =
3710 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3711 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003712 FunctionProtoType::ExtProtoInfo EPI;
3713 EPI.Variadic = true;
3714 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3715 Sema::CapturedParamNameType Params[] = {
3716 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003717 std::make_pair(".part_id.", KmpInt32PtrTy),
3718 std::make_pair(".privates.", VoidPtrTy),
3719 std::make_pair(
3720 ".copy_fn.",
3721 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003722 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3723 std::make_pair(StringRef(), QualType()) // __context with shared vars
3724 };
3725 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3726 Params);
3727 // Mark this captured region as inlined, because we don't use outlined
3728 // function directly.
3729 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3730 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003731 Context, {}, AttributeCommonInfo::AS_Keyword,
3732 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003733 break;
3734 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003735 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003736 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003737 case OMPD_taskyield:
3738 case OMPD_barrier:
3739 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003740 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003741 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003742 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003743 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003744 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003745 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003746 case OMPD_declare_target:
3747 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003748 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003749 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003750 llvm_unreachable("OpenMP Directive is not allowed");
3751 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003752 llvm_unreachable("Unknown OpenMP directive");
3753 }
3754}
3755
Alexey Bataev0e100032019-10-14 16:44:01 +00003756int Sema::getNumberOfConstructScopes(unsigned Level) const {
3757 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3758}
3759
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003760int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3761 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3762 getOpenMPCaptureRegions(CaptureRegions, DKind);
3763 return CaptureRegions.size();
3764}
3765
Alexey Bataev3392d762016-02-16 11:18:12 +00003766static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003767 Expr *CaptureExpr, bool WithInit,
3768 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003769 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003770 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003771 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003772 QualType Ty = Init->getType();
3773 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003774 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003775 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003776 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003777 Ty = C.getPointerType(Ty);
3778 ExprResult Res =
3779 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3780 if (!Res.isUsable())
3781 return nullptr;
3782 Init = Res.get();
3783 }
Alexey Bataev61205072016-03-02 04:57:40 +00003784 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003785 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003786 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003787 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003788 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003789 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003790 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003791 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003792 return CED;
3793}
3794
Alexey Bataev61205072016-03-02 04:57:40 +00003795static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3796 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003797 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003798 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003799 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003800 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003801 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3802 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003803 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003804 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003805}
3806
Alexey Bataev5a3af132016-03-29 08:58:54 +00003807static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003808 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003809 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003810 OMPCapturedExprDecl *CD = buildCaptureDecl(
3811 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3812 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003813 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3814 CaptureExpr->getExprLoc());
3815 }
3816 ExprResult Res = Ref;
3817 if (!S.getLangOpts().CPlusPlus &&
3818 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003819 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003820 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003821 if (!Res.isUsable())
3822 return ExprError();
3823 }
3824 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003825}
3826
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003827namespace {
3828// OpenMP directives parsed in this section are represented as a
3829// CapturedStatement with an associated statement. If a syntax error
3830// is detected during the parsing of the associated statement, the
3831// compiler must abort processing and close the CapturedStatement.
3832//
3833// Combined directives such as 'target parallel' have more than one
3834// nested CapturedStatements. This RAII ensures that we unwind out
3835// of all the nested CapturedStatements when an error is found.
3836class CaptureRegionUnwinderRAII {
3837private:
3838 Sema &S;
3839 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003840 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003841
3842public:
3843 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3844 OpenMPDirectiveKind DKind)
3845 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3846 ~CaptureRegionUnwinderRAII() {
3847 if (ErrorFound) {
3848 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3849 while (--ThisCaptureLevel >= 0)
3850 S.ActOnCapturedRegionError();
3851 }
3852 }
3853};
3854} // namespace
3855
Alexey Bataevb600ae32019-07-01 17:46:52 +00003856void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3857 // Capture variables captured by reference in lambdas for target-based
3858 // directives.
3859 if (!CurContext->isDependentContext() &&
3860 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3861 isOpenMPTargetDataManagementDirective(
3862 DSAStack->getCurrentDirective()))) {
3863 QualType Type = V->getType();
3864 if (const auto *RD = Type.getCanonicalType()
3865 .getNonReferenceType()
3866 ->getAsCXXRecordDecl()) {
3867 bool SavedForceCaptureByReferenceInTargetExecutable =
3868 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3869 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3870 /*V=*/true);
3871 if (RD->isLambda()) {
3872 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3873 FieldDecl *ThisCapture;
3874 RD->getCaptureFields(Captures, ThisCapture);
3875 for (const LambdaCapture &LC : RD->captures()) {
3876 if (LC.getCaptureKind() == LCK_ByRef) {
3877 VarDecl *VD = LC.getCapturedVar();
3878 DeclContext *VDC = VD->getDeclContext();
3879 if (!VDC->Encloses(CurContext))
3880 continue;
3881 MarkVariableReferenced(LC.getLocation(), VD);
3882 } else if (LC.getCaptureKind() == LCK_This) {
3883 QualType ThisTy = getCurrentThisType();
3884 if (!ThisTy.isNull() &&
3885 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3886 CheckCXXThisCapture(LC.getLocation());
3887 }
3888 }
3889 }
3890 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3891 SavedForceCaptureByReferenceInTargetExecutable);
3892 }
3893 }
3894}
3895
Alexey Bataevcb8e6912020-01-31 16:09:26 -05003896static bool checkOrderedOrderSpecified(Sema &S,
3897 const ArrayRef<OMPClause *> Clauses) {
3898 const OMPOrderedClause *Ordered = nullptr;
3899 const OMPOrderClause *Order = nullptr;
3900
3901 for (const OMPClause *Clause : Clauses) {
3902 if (Clause->getClauseKind() == OMPC_ordered)
3903 Ordered = cast<OMPOrderedClause>(Clause);
3904 else if (Clause->getClauseKind() == OMPC_order) {
3905 Order = cast<OMPOrderClause>(Clause);
3906 if (Order->getKind() != OMPC_ORDER_concurrent)
3907 Order = nullptr;
3908 }
3909 if (Ordered && Order)
3910 break;
3911 }
3912
3913 if (Ordered && Order) {
3914 S.Diag(Order->getKindKwLoc(),
3915 diag::err_omp_simple_clause_incompatible_with_ordered)
3916 << getOpenMPClauseName(OMPC_order)
3917 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
3918 << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
3919 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
3920 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
3921 return true;
3922 }
3923 return false;
3924}
3925
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003926StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3927 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003928 bool ErrorFound = false;
3929 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3930 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003931 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003932 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003933 return StmtError();
3934 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003935
Alexey Bataev2ba67042017-11-28 21:11:44 +00003936 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3937 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003938 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003939 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003940 SmallVector<const OMPLinearClause *, 4> LCs;
3941 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003942 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003943 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003944 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3945 Clause->getClauseKind() == OMPC_in_reduction) {
3946 // Capture taskgroup task_reduction descriptors inside the tasking regions
3947 // with the corresponding in_reduction items.
3948 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003949 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003950 if (E)
3951 MarkDeclarationsReferencedInExpr(E);
3952 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003953 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003954 Clause->getClauseKind() == OMPC_copyprivate ||
3955 (getLangOpts().OpenMPUseTLS &&
3956 getASTContext().getTargetInfo().isTLSSupported() &&
3957 Clause->getClauseKind() == OMPC_copyin)) {
3958 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003959 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003960 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003961 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003962 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003963 }
3964 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003965 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003966 } else if (CaptureRegions.size() > 1 ||
3967 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003968 if (auto *C = OMPClauseWithPreInit::get(Clause))
3969 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003970 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003971 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003972 MarkDeclarationsReferencedInExpr(E);
3973 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003974 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003975 if (Clause->getClauseKind() == OMPC_schedule)
3976 SC = cast<OMPScheduleClause>(Clause);
3977 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003978 OC = cast<OMPOrderedClause>(Clause);
3979 else if (Clause->getClauseKind() == OMPC_linear)
3980 LCs.push_back(cast<OMPLinearClause>(Clause));
3981 }
Alexey Bataevf3c508f2020-01-23 10:47:16 -05003982 // Capture allocator expressions if used.
3983 for (Expr *E : DSAStack->getInnerAllocators())
3984 MarkDeclarationsReferencedInExpr(E);
Alexey Bataev6402bca2015-12-28 07:25:51 +00003985 // OpenMP, 2.7.1 Loop Construct, Restrictions
3986 // The nonmonotonic modifier cannot be specified if an ordered clause is
3987 // specified.
3988 if (SC &&
3989 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3990 SC->getSecondScheduleModifier() ==
3991 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3992 OC) {
3993 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3994 ? SC->getFirstScheduleModifierLoc()
3995 : SC->getSecondScheduleModifierLoc(),
Alexey Bataevcb8e6912020-01-31 16:09:26 -05003996 diag::err_omp_simple_clause_incompatible_with_ordered)
3997 << getOpenMPClauseName(OMPC_schedule)
3998 << getOpenMPSimpleClauseTypeName(OMPC_schedule,
3999 OMPC_SCHEDULE_MODIFIER_nonmonotonic)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004000 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00004001 ErrorFound = true;
4002 }
Alexey Bataevcb8e6912020-01-31 16:09:26 -05004003 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4004 // If an order(concurrent) clause is present, an ordered clause may not appear
4005 // on the same directive.
4006 if (checkOrderedOrderSpecified(*this, Clauses))
4007 ErrorFound = true;
Alexey Bataev993d2802015-12-28 06:23:08 +00004008 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004009 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004010 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004011 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00004012 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00004013 ErrorFound = true;
4014 }
Alexey Bataev113438c2015-12-30 12:06:23 +00004015 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
4016 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
4017 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004018 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00004019 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
4020 ErrorFound = true;
4021 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00004022 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00004023 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00004024 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004025 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00004026 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00004027 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004028 // Mark all variables in private list clauses as used in inner region.
4029 // Required for proper codegen of combined directives.
4030 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00004031 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004032 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004033 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4034 // Find the particular capture region for the clause if the
4035 // directive is a combined one with multiple capture regions.
4036 // If the directive is not a combined one, the capture region
4037 // associated with the clause is OMPD_unknown and is generated
4038 // only once.
4039 if (CaptureRegion == ThisCaptureRegion ||
4040 CaptureRegion == OMPD_unknown) {
4041 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004042 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004043 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4044 }
4045 }
4046 }
4047 }
Richard Smith0621a8f2019-05-31 00:45:10 +00004048 if (++CompletedRegions == CaptureRegions.size())
4049 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004050 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004051 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004052 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00004053}
4054
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004055static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4056 OpenMPDirectiveKind CancelRegion,
4057 SourceLocation StartLoc) {
4058 // CancelRegion is only needed for cancel and cancellation_point.
4059 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4060 return false;
4061
4062 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4063 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4064 return false;
4065
4066 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4067 << getOpenMPDirectiveName(CancelRegion);
4068 return true;
4069}
4070
Alexey Bataeve3727102018-04-18 15:57:46 +00004071static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004072 OpenMPDirectiveKind CurrentRegion,
4073 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004074 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004075 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004076 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004077 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4078 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004079 bool NestingProhibited = false;
4080 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00004081 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004082 enum {
4083 NoRecommend,
4084 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00004085 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004086 ShouldBeInTargetRegion,
4087 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004088 } Recommend = NoRecommend;
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004089 if (isOpenMPSimdDirective(ParentRegion) &&
4090 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4091 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4092 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004093 // OpenMP [2.16, Nesting of Regions]
4094 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004095 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00004096 // An ordered construct with the simd clause is the only OpenMP
4097 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00004098 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00004099 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4100 // message.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004101 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4102 // The only OpenMP constructs that can be encountered during execution of
4103 // a simd region are the atomic construct, the loop construct, the simd
4104 // construct and the ordered construct with the simd clause.
Kelvin Lifd8b5742016-07-01 14:30:25 +00004105 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4106 ? diag::err_omp_prohibited_region_simd
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004107 : diag::warn_omp_nesting_simd)
4108 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
Kelvin Lifd8b5742016-07-01 14:30:25 +00004109 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00004110 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004111 if (ParentRegion == OMPD_atomic) {
4112 // OpenMP [2.16, Nesting of Regions]
4113 // OpenMP constructs may not be nested inside an atomic region.
4114 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4115 return true;
4116 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004117 if (CurrentRegion == OMPD_section) {
4118 // OpenMP [2.7.2, sections Construct, Restrictions]
4119 // Orphaned section directives are prohibited. That is, the section
4120 // directives must appear within the sections construct and must not be
4121 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004122 if (ParentRegion != OMPD_sections &&
4123 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004124 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4125 << (ParentRegion != OMPD_unknown)
4126 << getOpenMPDirectiveName(ParentRegion);
4127 return true;
4128 }
4129 return false;
4130 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00004131 // Allow some constructs (except teams and cancellation constructs) to be
4132 // orphaned (they could be used in functions, called from OpenMP regions
4133 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00004134 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00004135 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4136 CurrentRegion != OMPD_cancellation_point &&
4137 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004138 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00004139 if (CurrentRegion == OMPD_cancellation_point ||
4140 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004141 // OpenMP [2.16, Nesting of Regions]
4142 // A cancellation point construct for which construct-type-clause is
4143 // taskgroup must be nested inside a task construct. A cancellation
4144 // point construct for which construct-type-clause is not taskgroup must
4145 // be closely nested inside an OpenMP construct that matches the type
4146 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00004147 // A cancel construct for which construct-type-clause is taskgroup must be
4148 // nested inside a task construct. A cancel construct for which
4149 // construct-type-clause is not taskgroup must be closely nested inside an
4150 // OpenMP construct that matches the type specified in
4151 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004152 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004153 !((CancelRegion == OMPD_parallel &&
4154 (ParentRegion == OMPD_parallel ||
4155 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00004156 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004157 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004158 ParentRegion == OMPD_target_parallel_for ||
4159 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004160 ParentRegion == OMPD_teams_distribute_parallel_for ||
4161 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataeve0ca4792020-02-12 16:12:53 -05004162 (CancelRegion == OMPD_taskgroup &&
4163 (ParentRegion == OMPD_task ||
4164 (SemaRef.getLangOpts().OpenMP >= 50 &&
4165 (ParentRegion == OMPD_taskloop ||
4166 ParentRegion == OMPD_master_taskloop ||
4167 ParentRegion == OMPD_parallel_master_taskloop)))) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004168 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00004169 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4170 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00004171 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004172 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00004173 // OpenMP [2.16, Nesting of Regions]
4174 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004175 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00004176 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004177 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004178 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4179 // OpenMP [2.16, Nesting of Regions]
4180 // A critical region may not be nested (closely or otherwise) inside a
4181 // critical region with the same name. Note that this restriction is not
4182 // sufficient to prevent deadlock.
4183 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00004184 bool DeadLock = Stack->hasDirective(
4185 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4186 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00004187 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00004188 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4189 PreviousCriticalLoc = Loc;
4190 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004191 }
4192 return false;
David Majnemer9d168222016-08-05 17:44:54 +00004193 },
4194 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004195 if (DeadLock) {
4196 SemaRef.Diag(StartLoc,
4197 diag::err_omp_prohibited_region_critical_same_name)
4198 << CurrentName.getName();
4199 if (PreviousCriticalLoc.isValid())
4200 SemaRef.Diag(PreviousCriticalLoc,
4201 diag::note_omp_previous_critical_region);
4202 return true;
4203 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004204 } else if (CurrentRegion == OMPD_barrier) {
4205 // OpenMP [2.16, Nesting of Regions]
4206 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004207 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004208 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4209 isOpenMPTaskingDirective(ParentRegion) ||
4210 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004211 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004212 ParentRegion == OMPD_critical ||
4213 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00004214 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00004215 !isOpenMPParallelDirective(CurrentRegion) &&
4216 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004217 // OpenMP [2.16, Nesting of Regions]
4218 // A worksharing region may not be closely nested inside a worksharing,
4219 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004220 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4221 isOpenMPTaskingDirective(ParentRegion) ||
4222 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004223 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004224 ParentRegion == OMPD_critical ||
4225 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004226 Recommend = ShouldBeInParallelRegion;
4227 } else if (CurrentRegion == OMPD_ordered) {
4228 // OpenMP [2.16, Nesting of Regions]
4229 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00004230 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004231 // An ordered region must be closely nested inside a loop region (or
4232 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004233 // OpenMP [2.8.1,simd Construct, Restrictions]
4234 // An ordered construct with the simd clause is the only OpenMP construct
4235 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004236 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004237 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004238 !(isOpenMPSimdDirective(ParentRegion) ||
4239 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004240 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00004241 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004242 // OpenMP [2.16, Nesting of Regions]
4243 // If specified, a teams construct must be contained within a target
4244 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00004245 NestingProhibited =
4246 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4247 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4248 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00004249 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004250 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004251 }
Kelvin Libf594a52016-12-17 05:48:59 +00004252 if (!NestingProhibited &&
4253 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4254 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4255 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004256 // OpenMP [2.16, Nesting of Regions]
4257 // distribute, parallel, parallel sections, parallel workshare, and the
4258 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4259 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004260 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4261 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00004262 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004263 }
David Majnemer9d168222016-08-05 17:44:54 +00004264 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00004265 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004266 // OpenMP 4.5 [2.17 Nesting of Regions]
4267 // The region associated with the distribute construct must be strictly
4268 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00004269 NestingProhibited =
4270 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004271 Recommend = ShouldBeInTeamsRegion;
4272 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004273 if (!NestingProhibited &&
4274 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4275 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4276 // OpenMP 4.5 [2.17 Nesting of Regions]
4277 // If a target, target update, target data, target enter data, or
4278 // target exit data construct is encountered during execution of a
4279 // target region, the behavior is unspecified.
4280 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004281 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00004282 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004283 if (isOpenMPTargetExecutionDirective(K)) {
4284 OffendingRegion = K;
4285 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004286 }
4287 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004288 },
4289 false /* don't skip top directive */);
4290 CloseNesting = false;
4291 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004292 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00004293 if (OrphanSeen) {
4294 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4295 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4296 } else {
4297 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4298 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4299 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4300 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004301 return true;
4302 }
4303 }
4304 return false;
4305}
4306
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004307struct Kind2Unsigned {
4308 using argument_type = OpenMPDirectiveKind;
4309 unsigned operator()(argument_type DK) { return unsigned(DK); }
4310};
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004311static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4312 ArrayRef<OMPClause *> Clauses,
4313 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4314 bool ErrorFound = false;
4315 unsigned NamedModifiersNumber = 0;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004316 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4317 FoundNameModifiers.resize(unsigned(OMPD_unknown) + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004318 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004319 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004320 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4321 // At most one if clause without a directive-name-modifier can appear on
4322 // the directive.
4323 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4324 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004325 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004326 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4327 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4328 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004329 } else if (CurNM != OMPD_unknown) {
4330 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004331 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004332 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004333 FoundNameModifiers[CurNM] = IC;
4334 if (CurNM == OMPD_unknown)
4335 continue;
4336 // Check if the specified name modifier is allowed for the current
4337 // directive.
4338 // At most one if clause with the particular directive-name-modifier can
4339 // appear on the directive.
4340 bool MatchFound = false;
4341 for (auto NM : AllowedNameModifiers) {
4342 if (CurNM == NM) {
4343 MatchFound = true;
4344 break;
4345 }
4346 }
4347 if (!MatchFound) {
4348 S.Diag(IC->getNameModifierLoc(),
4349 diag::err_omp_wrong_if_directive_name_modifier)
4350 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4351 ErrorFound = true;
4352 }
4353 }
4354 }
4355 // If any if clause on the directive includes a directive-name-modifier then
4356 // all if clauses on the directive must include a directive-name-modifier.
4357 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4358 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004359 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004360 diag::err_omp_no_more_if_clause);
4361 } else {
4362 std::string Values;
4363 std::string Sep(", ");
4364 unsigned AllowedCnt = 0;
4365 unsigned TotalAllowedNum =
4366 AllowedNameModifiers.size() - NamedModifiersNumber;
4367 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4368 ++Cnt) {
4369 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4370 if (!FoundNameModifiers[NM]) {
4371 Values += "'";
4372 Values += getOpenMPDirectiveName(NM);
4373 Values += "'";
4374 if (AllowedCnt + 2 == TotalAllowedNum)
4375 Values += " or ";
4376 else if (AllowedCnt + 1 != TotalAllowedNum)
4377 Values += Sep;
4378 ++AllowedCnt;
4379 }
4380 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004381 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004382 diag::err_omp_unnamed_if_clause)
4383 << (TotalAllowedNum > 1) << Values;
4384 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004385 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004386 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4387 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004388 ErrorFound = true;
4389 }
4390 return ErrorFound;
4391}
4392
Alexey Bataev0860db92019-12-19 10:01:10 -05004393static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4394 SourceLocation &ELoc,
4395 SourceRange &ERange,
4396 bool AllowArraySection) {
Alexey Bataeve106f252019-04-01 14:25:31 +00004397 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4398 RefExpr->containsUnexpandedParameterPack())
4399 return std::make_pair(nullptr, true);
4400
4401 // OpenMP [3.1, C/C++]
4402 // A list item is a variable name.
4403 // OpenMP [2.9.3.3, Restrictions, p.1]
4404 // A variable that is part of another variable (as an array or
4405 // structure element) cannot appear in a private clause.
4406 RefExpr = RefExpr->IgnoreParens();
4407 enum {
4408 NoArrayExpr = -1,
4409 ArraySubscript = 0,
4410 OMPArraySection = 1
4411 } IsArrayExpr = NoArrayExpr;
4412 if (AllowArraySection) {
4413 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4414 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4415 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4416 Base = TempASE->getBase()->IgnoreParenImpCasts();
4417 RefExpr = Base;
4418 IsArrayExpr = ArraySubscript;
4419 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4420 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4421 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4422 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4423 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4424 Base = TempASE->getBase()->IgnoreParenImpCasts();
4425 RefExpr = Base;
4426 IsArrayExpr = OMPArraySection;
4427 }
4428 }
4429 ELoc = RefExpr->getExprLoc();
4430 ERange = RefExpr->getSourceRange();
4431 RefExpr = RefExpr->IgnoreParenImpCasts();
4432 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4433 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4434 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4435 (S.getCurrentThisType().isNull() || !ME ||
4436 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4437 !isa<FieldDecl>(ME->getMemberDecl()))) {
4438 if (IsArrayExpr != NoArrayExpr) {
4439 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4440 << ERange;
4441 } else {
4442 S.Diag(ELoc,
4443 AllowArraySection
4444 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4445 : diag::err_omp_expected_var_name_member_expr)
4446 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4447 }
4448 return std::make_pair(nullptr, false);
4449 }
4450 return std::make_pair(
4451 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4452}
4453
4454static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004455 ArrayRef<OMPClause *> Clauses) {
4456 assert(!S.CurContext->isDependentContext() &&
4457 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004458 auto AllocateRange =
4459 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004460 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4461 DeclToCopy;
4462 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4463 return isOpenMPPrivate(C->getClauseKind());
4464 });
4465 for (OMPClause *Cl : PrivateRange) {
4466 MutableArrayRef<Expr *>::iterator I, It, Et;
4467 if (Cl->getClauseKind() == OMPC_private) {
4468 auto *PC = cast<OMPPrivateClause>(Cl);
4469 I = PC->private_copies().begin();
4470 It = PC->varlist_begin();
4471 Et = PC->varlist_end();
4472 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4473 auto *PC = cast<OMPFirstprivateClause>(Cl);
4474 I = PC->private_copies().begin();
4475 It = PC->varlist_begin();
4476 Et = PC->varlist_end();
4477 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4478 auto *PC = cast<OMPLastprivateClause>(Cl);
4479 I = PC->private_copies().begin();
4480 It = PC->varlist_begin();
4481 Et = PC->varlist_end();
4482 } else if (Cl->getClauseKind() == OMPC_linear) {
4483 auto *PC = cast<OMPLinearClause>(Cl);
4484 I = PC->privates().begin();
4485 It = PC->varlist_begin();
4486 Et = PC->varlist_end();
4487 } else if (Cl->getClauseKind() == OMPC_reduction) {
4488 auto *PC = cast<OMPReductionClause>(Cl);
4489 I = PC->privates().begin();
4490 It = PC->varlist_begin();
4491 Et = PC->varlist_end();
4492 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4493 auto *PC = cast<OMPTaskReductionClause>(Cl);
4494 I = PC->privates().begin();
4495 It = PC->varlist_begin();
4496 Et = PC->varlist_end();
4497 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4498 auto *PC = cast<OMPInReductionClause>(Cl);
4499 I = PC->privates().begin();
4500 It = PC->varlist_begin();
4501 Et = PC->varlist_end();
4502 } else {
4503 llvm_unreachable("Expected private clause.");
4504 }
4505 for (Expr *E : llvm::make_range(It, Et)) {
4506 if (!*I) {
4507 ++I;
4508 continue;
4509 }
4510 SourceLocation ELoc;
4511 SourceRange ERange;
4512 Expr *SimpleRefExpr = E;
4513 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4514 /*AllowArraySection=*/true);
4515 DeclToCopy.try_emplace(Res.first,
4516 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4517 ++I;
4518 }
4519 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004520 for (OMPClause *C : AllocateRange) {
4521 auto *AC = cast<OMPAllocateClause>(C);
4522 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4523 getAllocatorKind(S, Stack, AC->getAllocator());
4524 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4525 // For task, taskloop or target directives, allocation requests to memory
4526 // allocators with the trait access set to thread result in unspecified
4527 // behavior.
4528 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4529 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4530 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4531 S.Diag(AC->getAllocator()->getExprLoc(),
4532 diag::warn_omp_allocate_thread_on_task_target_directive)
4533 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004534 }
4535 for (Expr *E : AC->varlists()) {
4536 SourceLocation ELoc;
4537 SourceRange ERange;
4538 Expr *SimpleRefExpr = E;
4539 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4540 ValueDecl *VD = Res.first;
4541 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4542 if (!isOpenMPPrivate(Data.CKind)) {
4543 S.Diag(E->getExprLoc(),
4544 diag::err_omp_expected_private_copy_for_allocate);
4545 continue;
4546 }
4547 VarDecl *PrivateVD = DeclToCopy[VD];
4548 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4549 AllocatorKind, AC->getAllocator()))
4550 continue;
4551 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4552 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004553 }
4554 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004555}
4556
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004557StmtResult Sema::ActOnOpenMPExecutableDirective(
4558 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4559 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4560 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004561 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004562 // First check CancelRegion which is then used in checkNestingOfRegions.
4563 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4564 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004565 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004566 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004567
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004568 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004569 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004570 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004571 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004572 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004573 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4574
4575 // Check default data sharing attributes for referenced variables.
4576 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004577 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4578 Stmt *S = AStmt;
4579 while (--ThisCaptureLevel >= 0)
4580 S = cast<CapturedStmt>(S)->getCapturedStmt();
4581 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004582 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4583 !isOpenMPTaskingDirective(Kind)) {
4584 // Visit subcaptures to generate implicit clauses for captured vars.
4585 auto *CS = cast<CapturedStmt>(AStmt);
4586 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4587 getOpenMPCaptureRegions(CaptureRegions, Kind);
4588 // Ignore outer tasking regions for target directives.
4589 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4590 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4591 DSAChecker.visitSubCaptures(CS);
4592 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004593 if (DSAChecker.isErrorFound())
4594 return StmtError();
4595 // Generate list of implicitly defined firstprivate variables.
4596 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004597
Alexey Bataev88202be2017-07-27 13:20:36 +00004598 SmallVector<Expr *, 4> ImplicitFirstprivates(
4599 DSAChecker.getImplicitFirstprivate().begin(),
4600 DSAChecker.getImplicitFirstprivate().end());
cchene06f3e02019-11-15 13:02:06 -05004601 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4602 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4603 ArrayRef<Expr *> ImplicitMap =
4604 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4605 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4606 }
Alexey Bataev88202be2017-07-27 13:20:36 +00004607 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004608 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004609 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004610 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004611 if (E)
4612 ImplicitFirstprivates.emplace_back(E);
4613 }
4614 }
4615 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004616 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004617 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4618 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004619 ClausesWithImplicit.push_back(Implicit);
4620 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004621 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004622 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004623 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004624 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004625 }
cchene06f3e02019-11-15 13:02:06 -05004626 int ClauseKindCnt = -1;
4627 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4628 ++ClauseKindCnt;
4629 if (ImplicitMap.empty())
4630 continue;
Michael Kruse4304e9d2019-02-19 16:38:20 +00004631 CXXScopeSpec MapperIdScopeSpec;
4632 DeclarationNameInfo MapperId;
cchene06f3e02019-11-15 13:02:06 -05004633 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004634 if (OMPClause *Implicit = ActOnOpenMPMapClause(
cchene06f3e02019-11-15 13:02:06 -05004635 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4636 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4637 ImplicitMap, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004638 ClausesWithImplicit.emplace_back(Implicit);
4639 ErrorFound |=
cchene06f3e02019-11-15 13:02:06 -05004640 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004641 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004642 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004643 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004644 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004645 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004646
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004647 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004648 switch (Kind) {
4649 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004650 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4651 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004652 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004653 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004654 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004655 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4656 VarsWithInheritedDSA);
Alexey Bataevd08c0562019-11-19 12:07:54 -05004657 if (LangOpts.OpenMP >= 50)
4658 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004659 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004660 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004661 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4662 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004663 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004664 case OMPD_for_simd:
4665 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4666 EndLoc, VarsWithInheritedDSA);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05004667 if (LangOpts.OpenMP >= 50)
4668 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004669 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004670 case OMPD_sections:
4671 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4672 EndLoc);
4673 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004674 case OMPD_section:
4675 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004676 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004677 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4678 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004679 case OMPD_single:
4680 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4681 EndLoc);
4682 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004683 case OMPD_master:
4684 assert(ClausesWithImplicit.empty() &&
4685 "No clauses are allowed for 'omp master' directive");
4686 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4687 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004688 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004689 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4690 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004691 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004692 case OMPD_parallel_for:
4693 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4694 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004695 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004696 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004697 case OMPD_parallel_for_simd:
4698 Res = ActOnOpenMPParallelForSimdDirective(
4699 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004700 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevf59614d2019-11-21 10:00:56 -05004701 if (LangOpts.OpenMP >= 50)
4702 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004703 break;
cchen47d60942019-12-05 13:43:48 -05004704 case OMPD_parallel_master:
4705 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
4706 StartLoc, EndLoc);
4707 AllowedNameModifiers.push_back(OMPD_parallel);
4708 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004709 case OMPD_parallel_sections:
4710 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4711 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004712 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004713 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004714 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004715 Res =
4716 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004717 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004718 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004719 case OMPD_taskyield:
4720 assert(ClausesWithImplicit.empty() &&
4721 "No clauses are allowed for 'omp taskyield' directive");
4722 assert(AStmt == nullptr &&
4723 "No associated statement allowed for 'omp taskyield' directive");
4724 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4725 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004726 case OMPD_barrier:
4727 assert(ClausesWithImplicit.empty() &&
4728 "No clauses are allowed for 'omp barrier' directive");
4729 assert(AStmt == nullptr &&
4730 "No associated statement allowed for 'omp barrier' directive");
4731 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4732 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004733 case OMPD_taskwait:
4734 assert(ClausesWithImplicit.empty() &&
4735 "No clauses are allowed for 'omp taskwait' directive");
4736 assert(AStmt == nullptr &&
4737 "No associated statement allowed for 'omp taskwait' directive");
4738 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4739 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004740 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004741 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4742 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004743 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004744 case OMPD_flush:
4745 assert(AStmt == nullptr &&
4746 "No associated statement allowed for 'omp flush' directive");
4747 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4748 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004749 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004750 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4751 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004752 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004753 case OMPD_atomic:
4754 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4755 EndLoc);
4756 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004757 case OMPD_teams:
4758 Res =
4759 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4760 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004761 case OMPD_target:
4762 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4763 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004764 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004765 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004766 case OMPD_target_parallel:
4767 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4768 StartLoc, EndLoc);
4769 AllowedNameModifiers.push_back(OMPD_target);
4770 AllowedNameModifiers.push_back(OMPD_parallel);
4771 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004772 case OMPD_target_parallel_for:
4773 Res = ActOnOpenMPTargetParallelForDirective(
4774 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4775 AllowedNameModifiers.push_back(OMPD_target);
4776 AllowedNameModifiers.push_back(OMPD_parallel);
4777 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004778 case OMPD_cancellation_point:
4779 assert(ClausesWithImplicit.empty() &&
4780 "No clauses are allowed for 'omp cancellation point' directive");
4781 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4782 "cancellation point' directive");
4783 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4784 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004785 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004786 assert(AStmt == nullptr &&
4787 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004788 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4789 CancelRegion);
4790 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004791 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004792 case OMPD_target_data:
4793 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4794 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004795 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004796 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004797 case OMPD_target_enter_data:
4798 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004799 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004800 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4801 break;
Samuel Antao72590762016-01-19 20:04:50 +00004802 case OMPD_target_exit_data:
4803 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004804 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004805 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4806 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004807 case OMPD_taskloop:
4808 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4809 EndLoc, VarsWithInheritedDSA);
4810 AllowedNameModifiers.push_back(OMPD_taskloop);
4811 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004812 case OMPD_taskloop_simd:
4813 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4814 EndLoc, VarsWithInheritedDSA);
4815 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev61205822019-12-04 09:50:21 -05004816 if (LangOpts.OpenMP >= 50)
4817 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004818 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004819 case OMPD_master_taskloop:
4820 Res = ActOnOpenMPMasterTaskLoopDirective(
4821 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4822 AllowedNameModifiers.push_back(OMPD_taskloop);
4823 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004824 case OMPD_master_taskloop_simd:
4825 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4826 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4827 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev853961f2019-12-05 09:50:18 -05004828 if (LangOpts.OpenMP >= 50)
4829 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004830 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004831 case OMPD_parallel_master_taskloop:
4832 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4833 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4834 AllowedNameModifiers.push_back(OMPD_taskloop);
4835 AllowedNameModifiers.push_back(OMPD_parallel);
4836 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004837 case OMPD_parallel_master_taskloop_simd:
4838 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4839 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4840 AllowedNameModifiers.push_back(OMPD_taskloop);
4841 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5c517a62019-12-05 11:31:45 -05004842 if (LangOpts.OpenMP >= 50)
4843 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev14a388f2019-10-25 10:27:13 -04004844 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004845 case OMPD_distribute:
4846 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4847 EndLoc, VarsWithInheritedDSA);
4848 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004849 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004850 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4851 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004852 AllowedNameModifiers.push_back(OMPD_target_update);
4853 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004854 case OMPD_distribute_parallel_for:
4855 Res = ActOnOpenMPDistributeParallelForDirective(
4856 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4857 AllowedNameModifiers.push_back(OMPD_parallel);
4858 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004859 case OMPD_distribute_parallel_for_simd:
4860 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4861 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4862 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev52812f22019-12-05 13:22:15 -05004863 if (LangOpts.OpenMP >= 50)
4864 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4a39add2016-07-05 05:00:15 +00004865 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004866 case OMPD_distribute_simd:
4867 Res = ActOnOpenMPDistributeSimdDirective(
4868 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev779a1802019-12-06 12:21:31 -05004869 if (LangOpts.OpenMP >= 50)
4870 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li787f3fc2016-07-06 04:45:38 +00004871 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004872 case OMPD_target_parallel_for_simd:
4873 Res = ActOnOpenMPTargetParallelForSimdDirective(
4874 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4875 AllowedNameModifiers.push_back(OMPD_target);
4876 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevda17a532019-12-10 11:37:03 -05004877 if (LangOpts.OpenMP >= 50)
4878 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lia579b912016-07-14 02:54:56 +00004879 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004880 case OMPD_target_simd:
4881 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4882 EndLoc, VarsWithInheritedDSA);
4883 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataevef94cd12019-12-10 12:44:45 -05004884 if (LangOpts.OpenMP >= 50)
4885 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li986330c2016-07-20 22:57:10 +00004886 break;
Kelvin Li02532872016-08-05 14:37:37 +00004887 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004888 Res = ActOnOpenMPTeamsDistributeDirective(
4889 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004890 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004891 case OMPD_teams_distribute_simd:
4892 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4893 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev7b774b72019-12-11 11:20:47 -05004894 if (LangOpts.OpenMP >= 50)
4895 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4e325f72016-10-25 12:50:55 +00004896 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004897 case OMPD_teams_distribute_parallel_for_simd:
4898 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4899 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4900 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev0b978942019-12-11 15:26:38 -05004901 if (LangOpts.OpenMP >= 50)
4902 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li579e41c2016-11-30 23:51:03 +00004903 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004904 case OMPD_teams_distribute_parallel_for:
4905 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4906 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4907 AllowedNameModifiers.push_back(OMPD_parallel);
4908 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004909 case OMPD_target_teams:
4910 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4911 EndLoc);
4912 AllowedNameModifiers.push_back(OMPD_target);
4913 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004914 case OMPD_target_teams_distribute:
4915 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4916 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4917 AllowedNameModifiers.push_back(OMPD_target);
4918 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004919 case OMPD_target_teams_distribute_parallel_for:
4920 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4921 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4922 AllowedNameModifiers.push_back(OMPD_target);
4923 AllowedNameModifiers.push_back(OMPD_parallel);
4924 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004925 case OMPD_target_teams_distribute_parallel_for_simd:
4926 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4927 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4928 AllowedNameModifiers.push_back(OMPD_target);
4929 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevfd0c91b2019-12-16 10:27:39 -05004930 if (LangOpts.OpenMP >= 50)
4931 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li1851df52017-01-03 05:23:48 +00004932 break;
Kelvin Lida681182017-01-10 18:08:18 +00004933 case OMPD_target_teams_distribute_simd:
4934 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4935 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4936 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev411e81a2019-12-16 11:16:46 -05004937 if (LangOpts.OpenMP >= 50)
4938 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lida681182017-01-10 18:08:18 +00004939 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004940 case OMPD_declare_target:
4941 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004942 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004943 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004944 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004945 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004946 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004947 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004948 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004949 llvm_unreachable("OpenMP Directive is not allowed");
4950 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004951 llvm_unreachable("Unknown OpenMP directive");
4952 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004953
Roman Lebedevb5700602019-03-20 16:32:36 +00004954 ErrorFound = Res.isInvalid() || ErrorFound;
4955
Alexey Bataev412254a2019-05-09 18:44:53 +00004956 // Check variables in the clauses if default(none) was specified.
4957 if (DSAStack->getDefaultDSA() == DSA_none) {
4958 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4959 for (OMPClause *C : Clauses) {
4960 switch (C->getClauseKind()) {
4961 case OMPC_num_threads:
4962 case OMPC_dist_schedule:
4963 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004964 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004965 break;
4966 continue;
4967 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004968 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004969 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4970 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004971 if (isOpenMPParallelDirective(Kind) &&
4972 isOpenMPTaskLoopDirective(Kind) &&
4973 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4974 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004975 continue;
4976 case OMPC_schedule:
4977 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004978 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004979 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004980 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004981 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004982 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004983 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004984 break;
4985 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004986 case OMPC_ordered:
4987 case OMPC_device:
4988 case OMPC_num_teams:
4989 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004990 case OMPC_hint:
4991 case OMPC_collapse:
4992 case OMPC_safelen:
4993 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004994 case OMPC_default:
4995 case OMPC_proc_bind:
4996 case OMPC_private:
4997 case OMPC_firstprivate:
4998 case OMPC_lastprivate:
4999 case OMPC_shared:
5000 case OMPC_reduction:
5001 case OMPC_task_reduction:
5002 case OMPC_in_reduction:
5003 case OMPC_linear:
5004 case OMPC_aligned:
5005 case OMPC_copyin:
5006 case OMPC_copyprivate:
5007 case OMPC_nowait:
5008 case OMPC_untied:
5009 case OMPC_mergeable:
5010 case OMPC_allocate:
5011 case OMPC_read:
5012 case OMPC_write:
5013 case OMPC_update:
5014 case OMPC_capture:
5015 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -05005016 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -05005017 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -05005018 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -05005019 case OMPC_relaxed:
Alexey Bataev412254a2019-05-09 18:44:53 +00005020 case OMPC_depend:
5021 case OMPC_threads:
5022 case OMPC_simd:
5023 case OMPC_map:
5024 case OMPC_nogroup:
5025 case OMPC_defaultmap:
5026 case OMPC_to:
5027 case OMPC_from:
5028 case OMPC_use_device_ptr:
5029 case OMPC_is_device_ptr:
Alexey Bataevb6e70842019-12-16 15:54:17 -05005030 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -05005031 case OMPC_order:
Alexey Bataev412254a2019-05-09 18:44:53 +00005032 continue;
5033 case OMPC_allocator:
5034 case OMPC_flush:
5035 case OMPC_threadprivate:
5036 case OMPC_uniform:
5037 case OMPC_unknown:
5038 case OMPC_unified_address:
5039 case OMPC_unified_shared_memory:
5040 case OMPC_reverse_offload:
5041 case OMPC_dynamic_allocators:
5042 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00005043 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00005044 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00005045 llvm_unreachable("Unexpected clause");
5046 }
5047 for (Stmt *CC : C->children()) {
5048 if (CC)
5049 DSAChecker.Visit(CC);
5050 }
5051 }
Alexey Bataevcb8e6912020-01-31 16:09:26 -05005052 for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
Alexey Bataev412254a2019-05-09 18:44:53 +00005053 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
5054 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005055 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00005056 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
5057 continue;
5058 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05005059 if (DSAStack->getDefaultDSA() == DSA_none) {
5060 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
5061 << P.first << P.second->getSourceRange();
5062 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
5063 } else if (getLangOpts().OpenMP >= 50) {
5064 Diag(P.second->getExprLoc(),
5065 diag::err_omp_defaultmap_no_attr_for_variable)
5066 << P.first << P.second->getSourceRange();
5067 Diag(DSAStack->getDefaultDSALocation(),
5068 diag::note_omp_defaultmap_attr_none);
5069 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00005070 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005071
5072 if (!AllowedNameModifiers.empty())
5073 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
5074 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00005075
Alexey Bataeved09d242014-05-28 05:53:51 +00005076 if (ErrorFound)
5077 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00005078
5079 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
5080 Res.getAs<OMPExecutableDirective>()
5081 ->getStructuredBlock()
5082 ->setIsOMPStructuredBlock(true);
5083 }
5084
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00005085 if (!CurContext->isDependentContext() &&
5086 isOpenMPTargetExecutionDirective(Kind) &&
5087 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
5088 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
5089 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
5090 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
5091 // Register target to DSA Stack.
5092 DSAStack->addTargetDirLocation(StartLoc);
5093 }
5094
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005095 return Res;
5096}
5097
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005098Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
5099 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00005100 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00005101 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
5102 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005103 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00005104 assert(Linears.size() == LinModifiers.size());
5105 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00005106 if (!DG || DG.get().isNull())
5107 return DeclGroupPtrTy();
5108
Alexey Bataevd158cf62019-09-13 20:18:17 +00005109 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005110 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005111 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5112 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005113 return DG;
5114 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005115 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00005116 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5117 ADecl = FTD->getTemplatedDecl();
5118
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005119 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5120 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005121 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005122 return DeclGroupPtrTy();
5123 }
5124
Alexey Bataev2af33e32016-04-07 12:45:37 +00005125 // OpenMP [2.8.2, declare simd construct, Description]
5126 // The parameter of the simdlen clause must be a constant positive integer
5127 // expression.
5128 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005129 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00005130 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005131 // OpenMP [2.8.2, declare simd construct, Description]
5132 // The special this pointer can be used as if was one of the arguments to the
5133 // function in any of the linear, aligned, or uniform clauses.
5134 // The uniform clause declares one or more arguments to have an invariant
5135 // value for all concurrent invocations of the function in the execution of a
5136 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00005137 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5138 const Expr *UniformedLinearThis = nullptr;
5139 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005140 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005141 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5142 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005143 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5144 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00005145 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00005146 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005147 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005148 }
5149 if (isa<CXXThisExpr>(E)) {
5150 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005151 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005152 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005153 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5154 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00005155 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00005156 // OpenMP [2.8.2, declare simd construct, Description]
5157 // The aligned clause declares that the object to which each list item points
5158 // is aligned to the number of bytes expressed in the optional parameter of
5159 // the aligned clause.
5160 // The special this pointer can be used as if was one of the arguments to the
5161 // function in any of the linear, aligned, or uniform clauses.
5162 // The type of list items appearing in the aligned clause must be array,
5163 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00005164 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5165 const Expr *AlignedThis = nullptr;
5166 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005167 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005168 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5169 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5170 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005171 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5172 FD->getParamDecl(PVD->getFunctionScopeIndex())
5173 ->getCanonicalDecl() == CanonPVD) {
5174 // OpenMP [2.8.1, simd construct, Restrictions]
5175 // A list-item cannot appear in more than one aligned clause.
5176 if (AlignedArgs.count(CanonPVD) > 0) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005177 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5178 << 1 << getOpenMPClauseName(OMPC_aligned)
5179 << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005180 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5181 diag::note_omp_explicit_dsa)
5182 << getOpenMPClauseName(OMPC_aligned);
5183 continue;
5184 }
5185 AlignedArgs[CanonPVD] = E;
5186 QualType QTy = PVD->getType()
5187 .getNonReferenceType()
5188 .getUnqualifiedType()
5189 .getCanonicalType();
5190 const Type *Ty = QTy.getTypePtrOrNull();
5191 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5192 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5193 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5194 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5195 }
5196 continue;
5197 }
5198 }
5199 if (isa<CXXThisExpr>(E)) {
5200 if (AlignedThis) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005201 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5202 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005203 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5204 << getOpenMPClauseName(OMPC_aligned);
5205 }
5206 AlignedThis = E;
5207 continue;
5208 }
5209 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5210 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5211 }
5212 // The optional parameter of the aligned clause, alignment, must be a constant
5213 // positive integer expression. If no optional parameter is specified,
5214 // implementation-defined default alignments for SIMD instructions on the
5215 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005216 SmallVector<const Expr *, 4> NewAligns;
5217 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005218 ExprResult Align;
5219 if (E)
5220 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5221 NewAligns.push_back(Align.get());
5222 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005223 // OpenMP [2.8.2, declare simd construct, Description]
5224 // The linear clause declares one or more list items to be private to a SIMD
5225 // lane and to have a linear relationship with respect to the iteration space
5226 // of a loop.
5227 // The special this pointer can be used as if was one of the arguments to the
5228 // function in any of the linear, aligned, or uniform clauses.
5229 // When a linear-step expression is specified in a linear clause it must be
5230 // either a constant integer expression or an integer-typed parameter that is
5231 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005232 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005233 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5234 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005235 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005236 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5237 ++MI;
5238 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005239 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5240 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5241 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005242 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5243 FD->getParamDecl(PVD->getFunctionScopeIndex())
5244 ->getCanonicalDecl() == CanonPVD) {
5245 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5246 // A list-item cannot appear in more than one linear clause.
5247 if (LinearArgs.count(CanonPVD) > 0) {
5248 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5249 << getOpenMPClauseName(OMPC_linear)
5250 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5251 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5252 diag::note_omp_explicit_dsa)
5253 << getOpenMPClauseName(OMPC_linear);
5254 continue;
5255 }
5256 // Each argument can appear in at most one uniform or linear clause.
5257 if (UniformedArgs.count(CanonPVD) > 0) {
5258 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5259 << getOpenMPClauseName(OMPC_linear)
5260 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5261 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5262 diag::note_omp_explicit_dsa)
5263 << getOpenMPClauseName(OMPC_uniform);
5264 continue;
5265 }
5266 LinearArgs[CanonPVD] = E;
5267 if (E->isValueDependent() || E->isTypeDependent() ||
5268 E->isInstantiationDependent() ||
5269 E->containsUnexpandedParameterPack())
5270 continue;
5271 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5272 PVD->getOriginalType());
5273 continue;
5274 }
5275 }
5276 if (isa<CXXThisExpr>(E)) {
5277 if (UniformedLinearThis) {
5278 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5279 << getOpenMPClauseName(OMPC_linear)
5280 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5281 << E->getSourceRange();
5282 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5283 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5284 : OMPC_linear);
5285 continue;
5286 }
5287 UniformedLinearThis = E;
5288 if (E->isValueDependent() || E->isTypeDependent() ||
5289 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5290 continue;
5291 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5292 E->getType());
5293 continue;
5294 }
5295 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5296 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5297 }
5298 Expr *Step = nullptr;
5299 Expr *NewStep = nullptr;
5300 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005301 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005302 // Skip the same step expression, it was checked already.
5303 if (Step == E || !E) {
5304 NewSteps.push_back(E ? NewStep : nullptr);
5305 continue;
5306 }
5307 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005308 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5309 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5310 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005311 if (UniformedArgs.count(CanonPVD) == 0) {
5312 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5313 << Step->getSourceRange();
5314 } else if (E->isValueDependent() || E->isTypeDependent() ||
5315 E->isInstantiationDependent() ||
5316 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005317 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005318 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005319 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005320 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5321 << Step->getSourceRange();
5322 }
5323 continue;
5324 }
5325 NewStep = Step;
5326 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5327 !Step->isInstantiationDependent() &&
5328 !Step->containsUnexpandedParameterPack()) {
5329 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5330 .get();
5331 if (NewStep)
5332 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5333 }
5334 NewSteps.push_back(NewStep);
5335 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005336 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5337 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005338 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005339 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5340 const_cast<Expr **>(Linears.data()), Linears.size(),
5341 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5342 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005343 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005344 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005345}
5346
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005347static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5348 QualType NewType) {
5349 assert(NewType->isFunctionProtoType() &&
5350 "Expected function type with prototype.");
5351 assert(FD->getType()->isFunctionNoProtoType() &&
5352 "Expected function with type with no prototype.");
5353 assert(FDWithProto->getType()->isFunctionProtoType() &&
5354 "Expected function with prototype.");
5355 // Synthesize parameters with the same types.
5356 FD->setType(NewType);
5357 SmallVector<ParmVarDecl *, 16> Params;
5358 for (const ParmVarDecl *P : FDWithProto->parameters()) {
5359 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5360 SourceLocation(), nullptr, P->getType(),
5361 /*TInfo=*/nullptr, SC_None, nullptr);
5362 Param->setScopeInfo(0, Params.size());
5363 Param->setImplicit();
5364 Params.push_back(Param);
5365 }
5366
5367 FD->setParams(Params);
5368}
5369
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005370Optional<std::pair<FunctionDecl *, Expr *>>
5371Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
Johannes Doerfert1228d422019-12-19 20:42:12 -06005372 Expr *VariantRef, OMPTraitInfo &TI,
5373 SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005374 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005375 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005376
5377 const int VariantId = 1;
5378 // Must be applied only to single decl.
5379 if (!DG.get().isSingleDecl()) {
5380 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5381 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005382 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005383 }
5384 Decl *ADecl = DG.get().getSingleDecl();
5385 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5386 ADecl = FTD->getTemplatedDecl();
5387
5388 // Decl must be a function.
5389 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5390 if (!FD) {
5391 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5392 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005393 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005394 }
5395
5396 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5397 return FD->hasAttrs() &&
5398 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5399 FD->hasAttr<TargetAttr>());
5400 };
5401 // OpenMP is not compatible with CPU-specific attributes.
5402 if (HasMultiVersionAttributes(FD)) {
5403 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5404 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005405 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005406 }
5407
5408 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005409 if (FD->isUsed(false))
5410 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005411 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005412
5413 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005414 const FunctionDecl *Definition;
5415 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5416 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005417 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5418 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005419
5420 // The VariantRef must point to function.
5421 if (!VariantRef) {
5422 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005423 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005424 }
5425
Johannes Doerfert1228d422019-12-19 20:42:12 -06005426 auto ShouldDelayChecks = [](Expr *&E, bool) {
5427 return E && (E->isTypeDependent() || E->isValueDependent() ||
5428 E->containsUnexpandedParameterPack() ||
5429 E->isInstantiationDependent());
5430 };
Alexey Bataevd158cf62019-09-13 20:18:17 +00005431 // Do not check templates, wait until instantiation.
Johannes Doerfert1228d422019-12-19 20:42:12 -06005432 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
5433 TI.anyScoreOrCondition(ShouldDelayChecks))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005434 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005435
Johannes Doerfert1228d422019-12-19 20:42:12 -06005436 // Deal with non-constant score and user condition expressions.
5437 auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
5438 bool IsScore) -> bool {
5439 llvm::APSInt Result;
5440 if (!E || E->isIntegerConstantExpr(Result, Context))
5441 return false;
5442
5443 if (IsScore) {
5444 // We warn on non-constant scores and pretend they were not present.
5445 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
5446 << E;
5447 E = nullptr;
5448 } else {
5449 // We could replace a non-constant user condition with "false" but we
5450 // will soon need to handle these anyway for the dynamic version of
5451 // OpenMP context selectors.
5452 Diag(E->getExprLoc(),
5453 diag::err_omp_declare_variant_user_condition_not_constant)
5454 << E;
5455 }
5456 return true;
5457 };
5458 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
5459 return None;
5460
Alexey Bataevd158cf62019-09-13 20:18:17 +00005461 // Convert VariantRef expression to the type of the original function to
5462 // resolve possible conflicts.
5463 ExprResult VariantRefCast;
5464 if (LangOpts.CPlusPlus) {
5465 QualType FnPtrType;
5466 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5467 if (Method && !Method->isStatic()) {
5468 const Type *ClassType =
5469 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5470 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5471 ExprResult ER;
5472 {
5473 // Build adrr_of unary op to correctly handle type checks for member
5474 // functions.
5475 Sema::TentativeAnalysisScope Trap(*this);
5476 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5477 VariantRef);
5478 }
5479 if (!ER.isUsable()) {
5480 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5481 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005482 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005483 }
5484 VariantRef = ER.get();
5485 } else {
5486 FnPtrType = Context.getPointerType(FD->getType());
5487 }
5488 ImplicitConversionSequence ICS =
5489 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5490 /*SuppressUserConversions=*/false,
Richard Smithd28763c2020-01-29 12:07:14 -08005491 AllowedExplicit::None,
Alexey Bataevd158cf62019-09-13 20:18:17 +00005492 /*InOverloadResolution=*/false,
5493 /*CStyle=*/false,
5494 /*AllowObjCWritebackConversion=*/false);
5495 if (ICS.isFailure()) {
5496 Diag(VariantRef->getExprLoc(),
5497 diag::err_omp_declare_variant_incompat_types)
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005498 << VariantRef->getType()
5499 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
5500 << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005501 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005502 }
5503 VariantRefCast = PerformImplicitConversion(
5504 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5505 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005506 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005507 // Drop previously built artificial addr_of unary op for member functions.
5508 if (Method && !Method->isStatic()) {
5509 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5510 if (auto *UO = dyn_cast<UnaryOperator>(
5511 PossibleAddrOfVariantRef->IgnoreImplicit()))
5512 VariantRefCast = UO->getSubExpr();
5513 }
5514 } else {
5515 VariantRefCast = VariantRef;
5516 }
5517
5518 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5519 if (!ER.isUsable() ||
5520 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5521 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5522 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005523 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005524 }
5525
5526 // The VariantRef must point to function.
5527 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5528 if (!DRE) {
5529 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5530 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005531 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005532 }
5533 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5534 if (!NewFD) {
5535 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5536 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005537 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005538 }
5539
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005540 // Check if function types are compatible in C.
5541 if (!LangOpts.CPlusPlus) {
5542 QualType NewType =
5543 Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
5544 if (NewType.isNull()) {
5545 Diag(VariantRef->getExprLoc(),
5546 diag::err_omp_declare_variant_incompat_types)
5547 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
5548 return None;
5549 }
5550 if (NewType->isFunctionProtoType()) {
5551 if (FD->getType()->isFunctionNoProtoType())
5552 setPrototype(*this, FD, NewFD, NewType);
5553 else if (NewFD->getType()->isFunctionNoProtoType())
5554 setPrototype(*this, NewFD, FD, NewType);
5555 }
5556 }
5557
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005558 // Check if variant function is not marked with declare variant directive.
5559 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5560 Diag(VariantRef->getExprLoc(),
5561 diag::warn_omp_declare_variant_marked_as_declare_variant)
5562 << VariantRef->getSourceRange();
5563 SourceRange SR =
5564 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5565 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005566 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005567 }
5568
Alexey Bataevd158cf62019-09-13 20:18:17 +00005569 enum DoesntSupport {
5570 VirtFuncs = 1,
5571 Constructors = 3,
5572 Destructors = 4,
5573 DeletedFuncs = 5,
5574 DefaultedFuncs = 6,
5575 ConstexprFuncs = 7,
5576 ConstevalFuncs = 8,
5577 };
5578 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5579 if (CXXFD->isVirtual()) {
5580 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5581 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005582 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005583 }
5584
5585 if (isa<CXXConstructorDecl>(FD)) {
5586 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5587 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005588 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005589 }
5590
5591 if (isa<CXXDestructorDecl>(FD)) {
5592 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5593 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005594 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005595 }
5596 }
5597
5598 if (FD->isDeleted()) {
5599 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5600 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005601 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005602 }
5603
5604 if (FD->isDefaulted()) {
5605 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5606 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005607 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005608 }
5609
5610 if (FD->isConstexpr()) {
5611 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5612 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005613 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005614 }
5615
5616 // Check general compatibility.
5617 if (areMultiversionVariantFunctionsCompatible(
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005618 FD, NewFD, PartialDiagnostic::NullDiagnostic(),
5619 PartialDiagnosticAt(SourceLocation(),
5620 PartialDiagnostic::NullDiagnostic()),
Alexey Bataevd158cf62019-09-13 20:18:17 +00005621 PartialDiagnosticAt(
5622 VariantRef->getExprLoc(),
5623 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5624 PartialDiagnosticAt(VariantRef->getExprLoc(),
5625 PDiag(diag::err_omp_declare_variant_diff)
5626 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005627 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5628 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005629 return None;
5630 return std::make_pair(FD, cast<Expr>(DRE));
5631}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005632
Johannes Doerfert1228d422019-12-19 20:42:12 -06005633void Sema::ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD,
5634 Expr *VariantRef,
5635 OMPTraitInfo *TI,
5636 SourceRange SR) {
5637 auto *NewAttr =
5638 OMPDeclareVariantAttr::CreateImplicit(Context, VariantRef, TI, SR);
5639 FD->addAttr(NewAttr);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005640}
5641
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005642void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5643 FunctionDecl *Func,
5644 bool MightBeOdrUse) {
5645 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5646
5647 if (!Func->isDependentContext() && Func->hasAttrs()) {
5648 for (OMPDeclareVariantAttr *A :
5649 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5650 // TODO: add checks for active OpenMP context where possible.
5651 Expr *VariantRef = A->getVariantFuncRef();
Alexey Bataevf17a1d82019-12-02 14:15:38 -05005652 auto *DRE = cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005653 auto *F = cast<FunctionDecl>(DRE->getDecl());
5654 if (!F->isDefined() && F->isTemplateInstantiation())
5655 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5656 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5657 }
5658 }
5659}
5660
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005661StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5662 Stmt *AStmt,
5663 SourceLocation StartLoc,
5664 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005665 if (!AStmt)
5666 return StmtError();
5667
Alexey Bataeve3727102018-04-18 15:57:46 +00005668 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005669 // 1.2.2 OpenMP Language Terminology
5670 // Structured block - An executable statement with a single entry at the
5671 // top and a single exit at the bottom.
5672 // The point of exit cannot be a branch out of the structured block.
5673 // longjmp() and throw() must not violate the entry/exit criteria.
5674 CS->getCapturedDecl()->setNothrow();
5675
Reid Kleckner87a31802018-03-12 21:43:02 +00005676 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005677
Alexey Bataev25e5b442015-09-15 12:52:43 +00005678 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5679 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005680}
5681
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005682namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005683/// Iteration space of a single for loop.
5684struct LoopIterationSpace final {
5685 /// True if the condition operator is the strict compare operator (<, > or
5686 /// !=).
5687 bool IsStrictCompare = false;
5688 /// Condition of the loop.
5689 Expr *PreCond = nullptr;
5690 /// This expression calculates the number of iterations in the loop.
5691 /// It is always possible to calculate it before starting the loop.
5692 Expr *NumIterations = nullptr;
5693 /// The loop counter variable.
5694 Expr *CounterVar = nullptr;
5695 /// Private loop counter variable.
5696 Expr *PrivateCounterVar = nullptr;
5697 /// This is initializer for the initial value of #CounterVar.
5698 Expr *CounterInit = nullptr;
5699 /// This is step for the #CounterVar used to generate its update:
5700 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5701 Expr *CounterStep = nullptr;
5702 /// Should step be subtracted?
5703 bool Subtract = false;
5704 /// Source range of the loop init.
5705 SourceRange InitSrcRange;
5706 /// Source range of the loop condition.
5707 SourceRange CondSrcRange;
5708 /// Source range of the loop increment.
5709 SourceRange IncSrcRange;
5710 /// Minimum value that can have the loop control variable. Used to support
5711 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5712 /// since only such variables can be used in non-loop invariant expressions.
5713 Expr *MinValue = nullptr;
5714 /// Maximum value that can have the loop control variable. Used to support
5715 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5716 /// since only such variables can be used in non-loop invariant expressions.
5717 Expr *MaxValue = nullptr;
5718 /// true, if the lower bound depends on the outer loop control var.
5719 bool IsNonRectangularLB = false;
5720 /// true, if the upper bound depends on the outer loop control var.
5721 bool IsNonRectangularUB = false;
5722 /// Index of the loop this loop depends on and forms non-rectangular loop
5723 /// nest.
5724 unsigned LoopDependentIdx = 0;
5725 /// Final condition for the non-rectangular loop nest support. It is used to
5726 /// check that the number of iterations for this particular counter must be
5727 /// finished.
5728 Expr *FinalCondition = nullptr;
5729};
5730
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005731/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005732/// extracting iteration space of each loop in the loop nest, that will be used
5733/// for IR generation.
5734class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005735 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005736 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005737 /// Data-sharing stack.
5738 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005739 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005740 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005741 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005742 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005743 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005744 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005745 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005746 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005747 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005748 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005749 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005750 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005751 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005752 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005753 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005754 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005755 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005756 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005757 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005758 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005759 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005760 /// Var < UB
5761 /// Var <= UB
5762 /// UB > Var
5763 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005764 /// This will have no value when the condition is !=
5765 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005766 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005767 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005768 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005769 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005770 /// The outer loop counter this loop depends on (if any).
5771 const ValueDecl *DepDecl = nullptr;
5772 /// Contains number of loop (starts from 1) on which loop counter init
5773 /// expression of this loop depends on.
5774 Optional<unsigned> InitDependOnLC;
5775 /// Contains number of loop (starts from 1) on which loop counter condition
5776 /// expression of this loop depends on.
5777 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005778 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005779 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005780 /// Original condition required for checking of the exit condition for
5781 /// non-rectangular loop.
5782 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005783
5784public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005785 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5786 SourceLocation DefaultLoc)
5787 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5788 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005789 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005790 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005791 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005792 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005793 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005794 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005795 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005796 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005797 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005798 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005799 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005800 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005801 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005802 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005803 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005804 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005805 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005806 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005807 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005808 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005809 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005810 /// True, if the compare operator is strict (<, > or !=).
5811 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005812 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005813 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005814 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005815 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005816 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005817 Expr *
5818 buildPreCond(Scope *S, Expr *Cond,
5819 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005820 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005821 DeclRefExpr *
5822 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5823 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005824 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005825 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005826 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005827 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005828 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005829 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005830 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005831 /// Build loop data with counter value for depend clauses in ordered
5832 /// directives.
5833 Expr *
5834 buildOrderedLoopData(Scope *S, Expr *Counter,
5835 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5836 SourceLocation Loc, Expr *Inc = nullptr,
5837 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005838 /// Builds the minimum value for the loop counter.
5839 std::pair<Expr *, Expr *> buildMinMaxValues(
5840 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5841 /// Builds final condition for the non-rectangular loops.
5842 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005843 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005844 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005845 /// Returns true if the initializer forms non-rectangular loop.
5846 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5847 /// Returns true if the condition forms non-rectangular loop.
5848 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5849 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5850 unsigned getLoopDependentIdx() const {
5851 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5852 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005853
5854private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005855 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005856 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005857 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005858 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005859 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5860 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005861 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005862 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5863 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005864 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005865 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005866};
5867
Alexey Bataeve3727102018-04-18 15:57:46 +00005868bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005869 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005870 assert(!LB && !UB && !Step);
5871 return false;
5872 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005873 return LCDecl->getType()->isDependentType() ||
5874 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5875 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005876}
5877
Alexey Bataeve3727102018-04-18 15:57:46 +00005878bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005879 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005880 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005881 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005882 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005883 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005884 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005885 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005886 LCDecl = getCanonicalDecl(NewLCDecl);
5887 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005888 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5889 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005890 if ((Ctor->isCopyOrMoveConstructor() ||
5891 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5892 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005893 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005894 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005895 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005896 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005897 return false;
5898}
5899
Alexey Bataev316ccf62019-01-29 18:51:58 +00005900bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5901 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005902 bool StrictOp, SourceRange SR,
5903 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005904 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005905 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5906 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005907 if (!NewUB)
5908 return true;
5909 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005910 if (LessOp)
5911 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005912 TestIsStrictOp = StrictOp;
5913 ConditionSrcRange = SR;
5914 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005915 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005916 return false;
5917}
5918
Alexey Bataeve3727102018-04-18 15:57:46 +00005919bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005920 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005921 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005922 if (!NewStep)
5923 return true;
5924 if (!NewStep->isValueDependent()) {
5925 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005926 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005927 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5928 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005929 if (Val.isInvalid())
5930 return true;
5931 NewStep = Val.get();
5932
5933 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5934 // If test-expr is of form var relational-op b and relational-op is < or
5935 // <= then incr-expr must cause var to increase on each iteration of the
5936 // loop. If test-expr is of form var relational-op b and relational-op is
5937 // > or >= then incr-expr must cause var to decrease on each iteration of
5938 // the loop.
5939 // If test-expr is of form b relational-op var and relational-op is < or
5940 // <= then incr-expr must cause var to decrease on each iteration of the
5941 // loop. If test-expr is of form b relational-op var and relational-op is
5942 // > or >= then incr-expr must cause var to increase on each iteration of
5943 // the loop.
5944 llvm::APSInt Result;
5945 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5946 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5947 bool IsConstNeg =
5948 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005949 bool IsConstPos =
5950 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005951 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005952
5953 // != with increment is treated as <; != with decrement is treated as >
5954 if (!TestIsLessOp.hasValue())
5955 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005956 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005957 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005958 (IsConstNeg || (IsUnsigned && Subtract)) :
5959 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005960 SemaRef.Diag(NewStep->getExprLoc(),
5961 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005962 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005963 SemaRef.Diag(ConditionLoc,
5964 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005965 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005966 return true;
5967 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005968 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005969 NewStep =
5970 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5971 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005972 Subtract = !Subtract;
5973 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005974 }
5975
5976 Step = NewStep;
5977 SubtractStep = Subtract;
5978 return false;
5979}
5980
Alexey Bataev622af1d2019-04-24 19:58:30 +00005981namespace {
5982/// Checker for the non-rectangular loops. Checks if the initializer or
5983/// condition expression references loop counter variable.
5984class LoopCounterRefChecker final
5985 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5986 Sema &SemaRef;
5987 DSAStackTy &Stack;
5988 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005989 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005990 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005991 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005992 unsigned BaseLoopId = 0;
5993 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5994 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5995 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5996 << (IsInitializer ? 0 : 1);
5997 return false;
5998 }
5999 const auto &&Data = Stack.isLoopControlVariable(VD);
6000 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
6001 // The type of the loop iterator on which we depend may not have a random
6002 // access iterator type.
6003 if (Data.first && VD->getType()->isRecordType()) {
6004 SmallString<128> Name;
6005 llvm::raw_svector_ostream OS(Name);
6006 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6007 /*Qualified=*/true);
6008 SemaRef.Diag(E->getExprLoc(),
6009 diag::err_omp_wrong_dependency_iterator_type)
6010 << OS.str();
6011 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
6012 return false;
6013 }
6014 if (Data.first &&
6015 (DepDecl || (PrevDepDecl &&
6016 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
6017 if (!DepDecl && PrevDepDecl)
6018 DepDecl = PrevDepDecl;
6019 SmallString<128> Name;
6020 llvm::raw_svector_ostream OS(Name);
6021 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6022 /*Qualified=*/true);
6023 SemaRef.Diag(E->getExprLoc(),
6024 diag::err_omp_invariant_or_linear_dependency)
6025 << OS.str();
6026 return false;
6027 }
6028 if (Data.first) {
6029 DepDecl = VD;
6030 BaseLoopId = Data.first;
6031 }
6032 return Data.first;
6033 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00006034
6035public:
6036 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6037 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006038 if (isa<VarDecl>(VD))
6039 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00006040 return false;
6041 }
6042 bool VisitMemberExpr(const MemberExpr *E) {
6043 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
6044 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00006045 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
6046 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00006047 }
6048 return false;
6049 }
6050 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006051 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006052 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00006053 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006054 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006055 }
6056 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006057 const ValueDecl *CurLCDecl, bool IsInitializer,
6058 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00006059 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006060 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
6061 unsigned getBaseLoopId() const {
6062 assert(CurLCDecl && "Expected loop dependency.");
6063 return BaseLoopId;
6064 }
6065 const ValueDecl *getDepDecl() const {
6066 assert(CurLCDecl && "Expected loop dependency.");
6067 return DepDecl;
6068 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00006069};
6070} // namespace
6071
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006072Optional<unsigned>
6073OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6074 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00006075 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006076 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6077 DepDecl);
6078 if (LoopStmtChecker.Visit(S)) {
6079 DepDecl = LoopStmtChecker.getDepDecl();
6080 return LoopStmtChecker.getBaseLoopId();
6081 }
6082 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006083}
6084
Alexey Bataeve3727102018-04-18 15:57:46 +00006085bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006086 // Check init-expr for canonical loop form and save loop counter
6087 // variable - #Var and its initialization value - #LB.
6088 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6089 // var = lb
6090 // integer-type var = lb
6091 // random-access-iterator-type var = lb
6092 // pointer-type var = lb
6093 //
6094 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00006095 if (EmitDiags) {
6096 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6097 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006098 return true;
6099 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006100 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6101 if (!ExprTemp->cleanupsHaveSideEffects())
6102 S = ExprTemp->getSubExpr();
6103
Alexander Musmana5f070a2014-10-01 06:03:56 +00006104 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006105 if (Expr *E = dyn_cast<Expr>(S))
6106 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006107 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006108 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006109 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006110 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6111 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6112 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006113 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6114 EmitDiags);
6115 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006116 }
6117 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6118 if (ME->isArrow() &&
6119 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006120 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6121 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006122 }
6123 }
David Majnemer9d168222016-08-05 17:44:54 +00006124 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006125 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00006126 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00006127 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006128 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00006129 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006130 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006131 diag::ext_omp_loop_not_canonical_init)
6132 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00006133 return setLCDeclAndLB(
6134 Var,
6135 buildDeclRefExpr(SemaRef, Var,
6136 Var->getType().getNonReferenceType(),
6137 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00006138 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006139 }
6140 }
6141 }
David Majnemer9d168222016-08-05 17:44:54 +00006142 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006143 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006144 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00006145 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006146 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6147 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006148 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6149 EmitDiags);
6150 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006151 }
6152 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6153 if (ME->isArrow() &&
6154 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006155 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6156 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006157 }
6158 }
6159 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006160
Alexey Bataeve3727102018-04-18 15:57:46 +00006161 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006162 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00006163 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006164 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00006165 << S->getSourceRange();
6166 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006167 return true;
6168}
6169
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006170/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006171/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00006172static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006173 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00006174 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006175 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00006176 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006177 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00006178 if ((Ctor->isCopyOrMoveConstructor() ||
6179 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6180 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006181 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00006182 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6183 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006184 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006185 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006186 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006187 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6188 return getCanonicalDecl(ME->getMemberDecl());
6189 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006190}
6191
Alexey Bataeve3727102018-04-18 15:57:46 +00006192bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006193 // Check test-expr for canonical form, save upper-bound UB, flags for
6194 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00006195 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006196 // var relational-op b
6197 // b relational-op var
6198 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006199 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006200 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006201 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6202 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006203 return true;
6204 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006205 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006206 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006207 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006208 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006209 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006210 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6211 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006212 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6213 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6214 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006215 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6216 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006217 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6218 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6219 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006220 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6221 return setUB(
6222 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6223 /*LessOp=*/llvm::None,
6224 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006225 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006226 if (CE->getNumArgs() == 2) {
6227 auto Op = CE->getOperator();
6228 switch (Op) {
6229 case OO_Greater:
6230 case OO_GreaterEqual:
6231 case OO_Less:
6232 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006233 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6234 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006235 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6236 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006237 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6238 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006239 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6240 CE->getOperatorLoc());
6241 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006242 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006243 if (IneqCondIsCanonical)
6244 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6245 : CE->getArg(0),
6246 /*LessOp=*/llvm::None,
6247 /*StrictOp=*/true, CE->getSourceRange(),
6248 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006249 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006250 default:
6251 break;
6252 }
6253 }
6254 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006255 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006256 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006257 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006258 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006259 return true;
6260}
6261
Alexey Bataeve3727102018-04-18 15:57:46 +00006262bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006263 // RHS of canonical loop form increment can be:
6264 // var + incr
6265 // incr + var
6266 // var - incr
6267 //
6268 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006269 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006270 if (BO->isAdditiveOp()) {
6271 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006272 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6273 return setStep(BO->getRHS(), !IsAdd);
6274 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6275 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006276 }
David Majnemer9d168222016-08-05 17:44:54 +00006277 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006278 bool IsAdd = CE->getOperator() == OO_Plus;
6279 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006280 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6281 return setStep(CE->getArg(1), !IsAdd);
6282 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6283 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006284 }
6285 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006286 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006287 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006288 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006289 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006290 return true;
6291}
6292
Alexey Bataeve3727102018-04-18 15:57:46 +00006293bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006294 // Check incr-expr for canonical loop form and return true if it
6295 // does not conform.
6296 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6297 // ++var
6298 // var++
6299 // --var
6300 // var--
6301 // var += incr
6302 // var -= incr
6303 // var = var + incr
6304 // var = incr + var
6305 // var = var - incr
6306 //
6307 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006308 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006309 return true;
6310 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006311 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6312 if (!ExprTemp->cleanupsHaveSideEffects())
6313 S = ExprTemp->getSubExpr();
6314
Alexander Musmana5f070a2014-10-01 06:03:56 +00006315 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006316 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006317 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006318 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006319 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6320 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006321 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006322 (UO->isDecrementOp() ? -1 : 1))
6323 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006324 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006325 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006326 switch (BO->getOpcode()) {
6327 case BO_AddAssign:
6328 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006329 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6330 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006331 break;
6332 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006333 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6334 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006335 break;
6336 default:
6337 break;
6338 }
David Majnemer9d168222016-08-05 17:44:54 +00006339 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006340 switch (CE->getOperator()) {
6341 case OO_PlusPlus:
6342 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006343 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6344 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006345 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006346 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006347 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6348 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006349 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006350 break;
6351 case OO_PlusEqual:
6352 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006353 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6354 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006355 break;
6356 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006357 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6358 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006359 break;
6360 default:
6361 break;
6362 }
6363 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006364 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006365 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006366 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006367 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006368 return true;
6369}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006370
Alexey Bataev5a3af132016-03-29 08:58:54 +00006371static ExprResult
6372tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006373 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006374 if (SemaRef.CurContext->isDependentContext())
6375 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006376 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6377 return SemaRef.PerformImplicitConversion(
6378 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6379 /*AllowExplicit=*/true);
6380 auto I = Captures.find(Capture);
6381 if (I != Captures.end())
6382 return buildCapture(SemaRef, Capture, I->second);
6383 DeclRefExpr *Ref = nullptr;
6384 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6385 Captures[Capture] = Ref;
6386 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006387}
6388
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006389/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006390Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006391 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006392 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006393 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006394 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006395 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006396 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006397 Expr *LBVal = LB;
6398 Expr *UBVal = UB;
6399 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6400 // max(LB(MinVal), LB(MaxVal))
6401 if (InitDependOnLC) {
6402 const LoopIterationSpace &IS =
6403 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6404 InitDependOnLC.getValueOr(
6405 CondDependOnLC.getValueOr(0))];
6406 if (!IS.MinValue || !IS.MaxValue)
6407 return nullptr;
6408 // OuterVar = Min
6409 ExprResult MinValue =
6410 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6411 if (!MinValue.isUsable())
6412 return nullptr;
6413
6414 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6415 IS.CounterVar, MinValue.get());
6416 if (!LBMinVal.isUsable())
6417 return nullptr;
6418 // OuterVar = Min, LBVal
6419 LBMinVal =
6420 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6421 if (!LBMinVal.isUsable())
6422 return nullptr;
6423 // (OuterVar = Min, LBVal)
6424 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6425 if (!LBMinVal.isUsable())
6426 return nullptr;
6427
6428 // OuterVar = Max
6429 ExprResult MaxValue =
6430 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6431 if (!MaxValue.isUsable())
6432 return nullptr;
6433
6434 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6435 IS.CounterVar, MaxValue.get());
6436 if (!LBMaxVal.isUsable())
6437 return nullptr;
6438 // OuterVar = Max, LBVal
6439 LBMaxVal =
6440 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6441 if (!LBMaxVal.isUsable())
6442 return nullptr;
6443 // (OuterVar = Max, LBVal)
6444 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6445 if (!LBMaxVal.isUsable())
6446 return nullptr;
6447
6448 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6449 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6450 if (!LBMin || !LBMax)
6451 return nullptr;
6452 // LB(MinVal) < LB(MaxVal)
6453 ExprResult MinLessMaxRes =
6454 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6455 if (!MinLessMaxRes.isUsable())
6456 return nullptr;
6457 Expr *MinLessMax =
6458 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6459 if (!MinLessMax)
6460 return nullptr;
6461 if (TestIsLessOp.getValue()) {
6462 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6463 // LB(MaxVal))
6464 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6465 MinLessMax, LBMin, LBMax);
6466 if (!MinLB.isUsable())
6467 return nullptr;
6468 LBVal = MinLB.get();
6469 } else {
6470 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6471 // LB(MaxVal))
6472 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6473 MinLessMax, LBMax, LBMin);
6474 if (!MaxLB.isUsable())
6475 return nullptr;
6476 LBVal = MaxLB.get();
6477 }
6478 }
6479 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6480 // min(UB(MinVal), UB(MaxVal))
6481 if (CondDependOnLC) {
6482 const LoopIterationSpace &IS =
6483 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6484 InitDependOnLC.getValueOr(
6485 CondDependOnLC.getValueOr(0))];
6486 if (!IS.MinValue || !IS.MaxValue)
6487 return nullptr;
6488 // OuterVar = Min
6489 ExprResult MinValue =
6490 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6491 if (!MinValue.isUsable())
6492 return nullptr;
6493
6494 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6495 IS.CounterVar, MinValue.get());
6496 if (!UBMinVal.isUsable())
6497 return nullptr;
6498 // OuterVar = Min, UBVal
6499 UBMinVal =
6500 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6501 if (!UBMinVal.isUsable())
6502 return nullptr;
6503 // (OuterVar = Min, UBVal)
6504 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6505 if (!UBMinVal.isUsable())
6506 return nullptr;
6507
6508 // OuterVar = Max
6509 ExprResult MaxValue =
6510 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6511 if (!MaxValue.isUsable())
6512 return nullptr;
6513
6514 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6515 IS.CounterVar, MaxValue.get());
6516 if (!UBMaxVal.isUsable())
6517 return nullptr;
6518 // OuterVar = Max, UBVal
6519 UBMaxVal =
6520 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6521 if (!UBMaxVal.isUsable())
6522 return nullptr;
6523 // (OuterVar = Max, UBVal)
6524 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6525 if (!UBMaxVal.isUsable())
6526 return nullptr;
6527
6528 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6529 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6530 if (!UBMin || !UBMax)
6531 return nullptr;
6532 // UB(MinVal) > UB(MaxVal)
6533 ExprResult MinGreaterMaxRes =
6534 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6535 if (!MinGreaterMaxRes.isUsable())
6536 return nullptr;
6537 Expr *MinGreaterMax =
6538 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6539 if (!MinGreaterMax)
6540 return nullptr;
6541 if (TestIsLessOp.getValue()) {
6542 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6543 // UB(MaxVal))
6544 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6545 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6546 if (!MaxUB.isUsable())
6547 return nullptr;
6548 UBVal = MaxUB.get();
6549 } else {
6550 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6551 // UB(MaxVal))
6552 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6553 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6554 if (!MinUB.isUsable())
6555 return nullptr;
6556 UBVal = MinUB.get();
6557 }
6558 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006559 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006560 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6561 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006562 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6563 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006564 if (!Upper || !Lower)
6565 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006566
6567 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6568
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006569 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006570 // BuildBinOp already emitted error, this one is to point user to upper
6571 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006572 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006573 << Upper->getSourceRange() << Lower->getSourceRange();
6574 return nullptr;
6575 }
6576 }
6577
6578 if (!Diff.isUsable())
6579 return nullptr;
6580
6581 // Upper - Lower [- 1]
6582 if (TestIsStrictOp)
6583 Diff = SemaRef.BuildBinOp(
6584 S, DefaultLoc, BO_Sub, Diff.get(),
6585 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6586 if (!Diff.isUsable())
6587 return nullptr;
6588
6589 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006590 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006591 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006592 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006593 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006594 if (!Diff.isUsable())
6595 return nullptr;
6596
6597 // Parentheses (for dumping/debugging purposes only).
6598 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6599 if (!Diff.isUsable())
6600 return nullptr;
6601
6602 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006603 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006604 if (!Diff.isUsable())
6605 return nullptr;
6606
Alexander Musman174b3ca2014-10-06 11:16:29 +00006607 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006608 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006609 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006610 bool UseVarType = VarType->hasIntegerRepresentation() &&
6611 C.getTypeSize(Type) > C.getTypeSize(VarType);
6612 if (!Type->isIntegerType() || UseVarType) {
6613 unsigned NewSize =
6614 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6615 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6616 : Type->hasSignedIntegerRepresentation();
6617 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006618 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6619 Diff = SemaRef.PerformImplicitConversion(
6620 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6621 if (!Diff.isUsable())
6622 return nullptr;
6623 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006624 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006625 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006626 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6627 if (NewSize != C.getTypeSize(Type)) {
6628 if (NewSize < C.getTypeSize(Type)) {
6629 assert(NewSize == 64 && "incorrect loop var size");
6630 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6631 << InitSrcRange << ConditionSrcRange;
6632 }
6633 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006634 NewSize, Type->hasSignedIntegerRepresentation() ||
6635 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006636 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6637 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6638 Sema::AA_Converting, true);
6639 if (!Diff.isUsable())
6640 return nullptr;
6641 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006642 }
6643 }
6644
Alexander Musmana5f070a2014-10-01 06:03:56 +00006645 return Diff.get();
6646}
6647
Alexey Bataevf8be4762019-08-14 19:30:06 +00006648std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6649 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6650 // Do not build for iterators, they cannot be used in non-rectangular loop
6651 // nests.
6652 if (LCDecl->getType()->isRecordType())
6653 return std::make_pair(nullptr, nullptr);
6654 // If we subtract, the min is in the condition, otherwise the min is in the
6655 // init value.
6656 Expr *MinExpr = nullptr;
6657 Expr *MaxExpr = nullptr;
6658 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6659 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6660 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6661 : CondDependOnLC.hasValue();
6662 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6663 : InitDependOnLC.hasValue();
6664 Expr *Lower =
6665 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6666 Expr *Upper =
6667 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6668 if (!Upper || !Lower)
6669 return std::make_pair(nullptr, nullptr);
6670
6671 if (TestIsLessOp.getValue())
6672 MinExpr = Lower;
6673 else
6674 MaxExpr = Upper;
6675
6676 // Build minimum/maximum value based on number of iterations.
6677 ExprResult Diff;
6678 QualType VarType = LCDecl->getType().getNonReferenceType();
6679
6680 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6681 if (!Diff.isUsable())
6682 return std::make_pair(nullptr, nullptr);
6683
6684 // Upper - Lower [- 1]
6685 if (TestIsStrictOp)
6686 Diff = SemaRef.BuildBinOp(
6687 S, DefaultLoc, BO_Sub, Diff.get(),
6688 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6689 if (!Diff.isUsable())
6690 return std::make_pair(nullptr, nullptr);
6691
6692 // Upper - Lower [- 1] + Step
6693 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6694 if (!NewStep.isUsable())
6695 return std::make_pair(nullptr, nullptr);
6696
6697 // Parentheses (for dumping/debugging purposes only).
6698 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6699 if (!Diff.isUsable())
6700 return std::make_pair(nullptr, nullptr);
6701
6702 // (Upper - Lower [- 1]) / Step
6703 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6704 if (!Diff.isUsable())
6705 return std::make_pair(nullptr, nullptr);
6706
6707 // ((Upper - Lower [- 1]) / Step) * Step
6708 // Parentheses (for dumping/debugging purposes only).
6709 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6710 if (!Diff.isUsable())
6711 return std::make_pair(nullptr, nullptr);
6712
6713 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6714 if (!Diff.isUsable())
6715 return std::make_pair(nullptr, nullptr);
6716
6717 // Convert to the original type or ptrdiff_t, if original type is pointer.
6718 if (!VarType->isAnyPointerType() &&
6719 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6720 Diff = SemaRef.PerformImplicitConversion(
6721 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6722 } else if (VarType->isAnyPointerType() &&
6723 !SemaRef.Context.hasSameType(
6724 Diff.get()->getType(),
6725 SemaRef.Context.getUnsignedPointerDiffType())) {
6726 Diff = SemaRef.PerformImplicitConversion(
6727 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6728 Sema::AA_Converting, /*AllowExplicit=*/true);
6729 }
6730 if (!Diff.isUsable())
6731 return std::make_pair(nullptr, nullptr);
6732
6733 // Parentheses (for dumping/debugging purposes only).
6734 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6735 if (!Diff.isUsable())
6736 return std::make_pair(nullptr, nullptr);
6737
6738 if (TestIsLessOp.getValue()) {
6739 // MinExpr = Lower;
6740 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6741 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6742 if (!Diff.isUsable())
6743 return std::make_pair(nullptr, nullptr);
6744 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6745 if (!Diff.isUsable())
6746 return std::make_pair(nullptr, nullptr);
6747 MaxExpr = Diff.get();
6748 } else {
6749 // MaxExpr = Upper;
6750 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6751 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6752 if (!Diff.isUsable())
6753 return std::make_pair(nullptr, nullptr);
6754 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6755 if (!Diff.isUsable())
6756 return std::make_pair(nullptr, nullptr);
6757 MinExpr = Diff.get();
6758 }
6759
6760 return std::make_pair(MinExpr, MaxExpr);
6761}
6762
6763Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6764 if (InitDependOnLC || CondDependOnLC)
6765 return Condition;
6766 return nullptr;
6767}
6768
Alexey Bataeve3727102018-04-18 15:57:46 +00006769Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006770 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006771 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006772 // Do not build a precondition when the condition/initialization is dependent
6773 // to prevent pessimistic early loop exit.
6774 // TODO: this can be improved by calculating min/max values but not sure that
6775 // it will be very effective.
6776 if (CondDependOnLC || InitDependOnLC)
6777 return SemaRef.PerformImplicitConversion(
6778 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6779 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6780 /*AllowExplicit=*/true).get();
6781
Alexey Bataev62dbb972015-04-22 11:59:37 +00006782 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006783 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006784
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006785 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6786 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006787 if (!NewLB.isUsable() || !NewUB.isUsable())
6788 return nullptr;
6789
Alexey Bataeve3727102018-04-18 15:57:46 +00006790 ExprResult CondExpr =
6791 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006792 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006793 (TestIsStrictOp ? BO_LT : BO_LE) :
6794 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006795 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006796 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006797 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6798 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006799 CondExpr = SemaRef.PerformImplicitConversion(
6800 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6801 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006802 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006803
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006804 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006805 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6806}
6807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006808/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006809DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006810 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6811 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006812 auto *VD = dyn_cast<VarDecl>(LCDecl);
6813 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006814 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6815 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006816 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006817 const DSAStackTy::DSAVarData Data =
6818 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006819 // If the loop control decl is explicitly marked as private, do not mark it
6820 // as captured again.
6821 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6822 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006823 return Ref;
6824 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006825 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006826}
6827
Alexey Bataeve3727102018-04-18 15:57:46 +00006828Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006829 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006830 QualType Type = LCDecl->getType().getNonReferenceType();
6831 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006832 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6833 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6834 isa<VarDecl>(LCDecl)
6835 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6836 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006837 if (PrivateVar->isInvalidDecl())
6838 return nullptr;
6839 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6840 }
6841 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006842}
6843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006844/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006845Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006846
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006847/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006848Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006849
Alexey Bataevf138fda2018-08-13 19:04:24 +00006850Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6851 Scope *S, Expr *Counter,
6852 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6853 Expr *Inc, OverloadedOperatorKind OOK) {
6854 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6855 if (!Cnt)
6856 return nullptr;
6857 if (Inc) {
6858 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6859 "Expected only + or - operations for depend clauses.");
6860 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6861 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6862 if (!Cnt)
6863 return nullptr;
6864 }
6865 ExprResult Diff;
6866 QualType VarType = LCDecl->getType().getNonReferenceType();
6867 if (VarType->isIntegerType() || VarType->isPointerType() ||
6868 SemaRef.getLangOpts().CPlusPlus) {
6869 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006870 Expr *Upper = TestIsLessOp.getValue()
6871 ? Cnt
6872 : tryBuildCapture(SemaRef, UB, Captures).get();
6873 Expr *Lower = TestIsLessOp.getValue()
6874 ? tryBuildCapture(SemaRef, LB, Captures).get()
6875 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006876 if (!Upper || !Lower)
6877 return nullptr;
6878
6879 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6880
6881 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6882 // BuildBinOp already emitted error, this one is to point user to upper
6883 // and lower bound, and to tell what is passed to 'operator-'.
6884 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6885 << Upper->getSourceRange() << Lower->getSourceRange();
6886 return nullptr;
6887 }
6888 }
6889
6890 if (!Diff.isUsable())
6891 return nullptr;
6892
6893 // Parentheses (for dumping/debugging purposes only).
6894 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6895 if (!Diff.isUsable())
6896 return nullptr;
6897
6898 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6899 if (!NewStep.isUsable())
6900 return nullptr;
6901 // (Upper - Lower) / Step
6902 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6903 if (!Diff.isUsable())
6904 return nullptr;
6905
6906 return Diff.get();
6907}
Alexey Bataev23b69422014-06-18 07:08:49 +00006908} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006909
Alexey Bataev9c821032015-04-30 04:23:23 +00006910void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6911 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6912 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006913 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6914 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006915 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006916 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006917 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006918 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6919 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006920 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006921 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006922 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006923 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006924 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006925 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006926 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6927 /*WithInit=*/false);
6928 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006929 }
6930 }
6931 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006932 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6933 if (LD != D->getCanonicalDecl()) {
6934 DSAStack->resetPossibleLoopCounter();
6935 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6936 MarkDeclarationsReferencedInExpr(
6937 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6938 Var->getType().getNonLValueExprType(Context),
6939 ForLoc, /*RefersToCapture=*/true));
6940 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006941 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6942 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6943 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6944 // associated for-loop of a simd construct with just one associated
6945 // for-loop may be listed in a linear clause with a constant-linear-step
6946 // that is the increment of the associated for-loop. The loop iteration
6947 // variable(s) in the associated for-loop(s) of a for or parallel for
6948 // construct may be listed in a private or lastprivate clause.
6949 DSAStackTy::DSAVarData DVar =
6950 DSAStack->getTopDSA(D, /*FromParent=*/false);
6951 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6952 // is declared in the loop and it is predetermined as a private.
6953 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6954 OpenMPClauseKind PredeterminedCKind =
6955 isOpenMPSimdDirective(DKind)
6956 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6957 : OMPC_private;
6958 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6959 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6960 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6961 DVar.CKind != OMPC_private))) ||
6962 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006963 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006964 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006965 isOpenMPDistributeDirective(DKind)) &&
6966 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6967 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6968 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6969 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6970 << getOpenMPClauseName(DVar.CKind)
6971 << getOpenMPDirectiveName(DKind)
6972 << getOpenMPClauseName(PredeterminedCKind);
6973 if (DVar.RefExpr == nullptr)
6974 DVar.CKind = PredeterminedCKind;
6975 reportOriginalDsa(*this, DSAStack, D, DVar,
6976 /*IsLoopIterVar=*/true);
6977 } else if (LoopDeclRefExpr) {
6978 // Make the loop iteration variable private (for worksharing
6979 // constructs), linear (for simd directives with the only one
6980 // associated loop) or lastprivate (for simd directives with several
6981 // collapsed or ordered loops).
6982 if (DVar.CKind == OMPC_unknown)
6983 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6984 PrivateRef);
6985 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006986 }
6987 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006988 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006989 }
6990}
6991
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006992/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006993/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006994static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006995 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6996 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006997 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6998 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006999 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007000 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00007001 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00007002 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007003 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00007004 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00007005 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00007006 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
7007 // Ranged for is supported only in OpenMP 5.0.
7008 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007009 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007010 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00007011 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00007012 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00007013 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007014 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
7015 SemaRef.Diag(DSA.getConstructLoc(),
7016 diag::note_omp_collapse_ordered_expr)
7017 << 2 << CollapseLoopCountExpr->getSourceRange()
7018 << OrderedLoopCountExpr->getSourceRange();
7019 else if (CollapseLoopCountExpr)
7020 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7021 diag::note_omp_collapse_ordered_expr)
7022 << 0 << CollapseLoopCountExpr->getSourceRange();
7023 else
7024 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7025 diag::note_omp_collapse_ordered_expr)
7026 << 1 << OrderedLoopCountExpr->getSourceRange();
7027 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007028 return true;
7029 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00007030 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
7031 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007032
Alexey Bataevbef93a92019-10-07 18:54:57 +00007033 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
7034 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007035
7036 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007037 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00007038 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007039 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007040
7041 bool HasErrors = false;
7042
7043 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00007044 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007045 // OpenMP [2.6, Canonical Loop Form]
7046 // Var is one of the following:
7047 // A variable of signed or unsigned integer type.
7048 // For C++, a variable of a random access iterator type.
7049 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00007050 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007051 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
7052 !VarType->isPointerType() &&
7053 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007054 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007055 << SemaRef.getLangOpts().CPlusPlus;
7056 HasErrors = true;
7057 }
7058
7059 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
7060 // a Construct
7061 // The loop iteration variable(s) in the associated for-loop(s) of a for or
7062 // parallel for construct is (are) private.
7063 // The loop iteration variable in the associated for-loop of a simd
7064 // construct with just one associated for-loop is linear with a
7065 // constant-linear-step that is the increment of the associated for-loop.
7066 // Exclude loop var from the list of variables with implicitly defined data
7067 // sharing attributes.
7068 VarsWithImplicitDSA.erase(LCDecl);
7069
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007070 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
7071
7072 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007073 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007074
7075 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007076 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007077 }
7078
Alexey Bataeve3727102018-04-18 15:57:46 +00007079 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007080 return HasErrors;
7081
Alexander Musmana5f070a2014-10-01 06:03:56 +00007082 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007083 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
7084 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007085 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
7086 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
7087 (isOpenMPWorksharingDirective(DKind) ||
7088 isOpenMPTaskLoopDirective(DKind) ||
7089 isOpenMPDistributeDirective(DKind)),
7090 Captures);
7091 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
7092 ISC.buildCounterVar(Captures, DSA);
7093 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
7094 ISC.buildPrivateCounterVar();
7095 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
7096 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
7097 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
7098 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
7099 ISC.getConditionSrcRange();
7100 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
7101 ISC.getIncrementSrcRange();
7102 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
7103 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
7104 ISC.isStrictTestOp();
7105 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
7106 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
7107 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
7108 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
7109 ISC.buildFinalCondition(DSA.getCurScope());
7110 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
7111 ISC.doesInitDependOnLC();
7112 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
7113 ISC.doesCondDependOnLC();
7114 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
7115 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007116
Alexey Bataevf8be4762019-08-14 19:30:06 +00007117 HasErrors |=
7118 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
7119 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
7120 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
7121 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
7122 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
7123 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007124 if (!HasErrors && DSA.isOrderedRegion()) {
7125 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7126 if (CurrentNestedLoopCount <
7127 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7128 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007129 CurrentNestedLoopCount,
7130 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007131 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007132 CurrentNestedLoopCount,
7133 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007134 }
7135 }
7136 for (auto &Pair : DSA.getDoacrossDependClauses()) {
7137 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7138 // Erroneous case - clause has some problems.
7139 continue;
7140 }
7141 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7142 Pair.second.size() <= CurrentNestedLoopCount) {
7143 // Erroneous case - clause has some problems.
7144 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7145 continue;
7146 }
7147 Expr *CntValue;
7148 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7149 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007150 DSA.getCurScope(),
7151 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007152 Pair.first->getDependencyLoc());
7153 else
7154 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007155 DSA.getCurScope(),
7156 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007157 Pair.first->getDependencyLoc(),
7158 Pair.second[CurrentNestedLoopCount].first,
7159 Pair.second[CurrentNestedLoopCount].second);
7160 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7161 }
7162 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007163
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007164 return HasErrors;
7165}
7166
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007167/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00007168static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00007169buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007170 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007171 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007172 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007173 ExprResult NewStart = IsNonRectangularLB
7174 ? Start.get()
7175 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00007176 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007177 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00007178 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00007179 VarRef.get()->getType())) {
7180 NewStart = SemaRef.PerformImplicitConversion(
7181 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7182 /*AllowExplicit=*/true);
7183 if (!NewStart.isUsable())
7184 return ExprError();
7185 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007186
Alexey Bataeve3727102018-04-18 15:57:46 +00007187 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007188 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7189 return Init;
7190}
7191
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007192/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00007193static ExprResult buildCounterUpdate(
7194 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7195 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007196 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007197 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007198 // Add parentheses (for debugging purposes only).
7199 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7200 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7201 !Step.isUsable())
7202 return ExprError();
7203
Alexey Bataev5a3af132016-03-29 08:58:54 +00007204 ExprResult NewStep = Step;
7205 if (Captures)
7206 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007207 if (NewStep.isInvalid())
7208 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007209 ExprResult Update =
7210 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007211 if (!Update.isUsable())
7212 return ExprError();
7213
Alexey Bataevc0214e02016-02-16 12:13:49 +00007214 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7215 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007216 if (!Start.isUsable())
7217 return ExprError();
7218 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7219 if (!NewStart.isUsable())
7220 return ExprError();
7221 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007222 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007223 if (NewStart.isInvalid())
7224 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007225
Alexey Bataevc0214e02016-02-16 12:13:49 +00007226 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7227 ExprResult SavedUpdate = Update;
7228 ExprResult UpdateVal;
7229 if (VarRef.get()->getType()->isOverloadableType() ||
7230 NewStart.get()->getType()->isOverloadableType() ||
7231 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007232 Sema::TentativeAnalysisScope Trap(SemaRef);
7233
Alexey Bataevc0214e02016-02-16 12:13:49 +00007234 Update =
7235 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7236 if (Update.isUsable()) {
7237 UpdateVal =
7238 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7239 VarRef.get(), SavedUpdate.get());
7240 if (UpdateVal.isUsable()) {
7241 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7242 UpdateVal.get());
7243 }
7244 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007245 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007246
Alexey Bataevc0214e02016-02-16 12:13:49 +00007247 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7248 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7249 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7250 NewStart.get(), SavedUpdate.get());
7251 if (!Update.isUsable())
7252 return ExprError();
7253
Alexey Bataev11481f52016-02-17 10:29:05 +00007254 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7255 VarRef.get()->getType())) {
7256 Update = SemaRef.PerformImplicitConversion(
7257 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7258 if (!Update.isUsable())
7259 return ExprError();
7260 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007261
7262 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7263 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007264 return Update;
7265}
7266
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007267/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007268/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007269static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007270 if (E == nullptr)
7271 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007272 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007273 QualType OldType = E->getType();
7274 unsigned HasBits = C.getTypeSize(OldType);
7275 if (HasBits >= Bits)
7276 return ExprResult(E);
7277 // OK to convert to signed, because new type has more bits than old.
7278 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7279 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7280 true);
7281}
7282
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007283/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007284/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007285static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007286 if (E == nullptr)
7287 return false;
7288 llvm::APSInt Result;
7289 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7290 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7291 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007292}
7293
Alexey Bataev5a3af132016-03-29 08:58:54 +00007294/// Build preinits statement for the given declarations.
7295static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007296 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007297 if (!PreInits.empty()) {
7298 return new (Context) DeclStmt(
7299 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7300 SourceLocation(), SourceLocation());
7301 }
7302 return nullptr;
7303}
7304
7305/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007306static Stmt *
7307buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007308 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007309 if (!Captures.empty()) {
7310 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007311 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007312 PreInits.push_back(Pair.second->getDecl());
7313 return buildPreInits(Context, PreInits);
7314 }
7315 return nullptr;
7316}
7317
7318/// Build postupdate expression for the given list of postupdates expressions.
7319static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7320 Expr *PostUpdate = nullptr;
7321 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007322 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007323 Expr *ConvE = S.BuildCStyleCastExpr(
7324 E->getExprLoc(),
7325 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7326 E->getExprLoc(), E)
7327 .get();
7328 PostUpdate = PostUpdate
7329 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7330 PostUpdate, ConvE)
7331 .get()
7332 : ConvE;
7333 }
7334 }
7335 return PostUpdate;
7336}
7337
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007338/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007339/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7340/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007341static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007342checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007343 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7344 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007345 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007346 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007347 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007348 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007349 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007350 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007351 if (!CollapseLoopCountExpr->isValueDependent() &&
7352 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007353 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007354 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007355 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007356 return 1;
7357 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007358 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007359 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007360 if (OrderedLoopCountExpr) {
7361 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007362 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007363 if (!OrderedLoopCountExpr->isValueDependent() &&
7364 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7365 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007366 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007367 if (Result.getLimitedValue() < NestedLoopCount) {
7368 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7369 diag::err_omp_wrong_ordered_loop_count)
7370 << OrderedLoopCountExpr->getSourceRange();
7371 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7372 diag::note_collapse_loop_count)
7373 << CollapseLoopCountExpr->getSourceRange();
7374 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007375 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007376 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007377 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007378 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007379 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007380 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007381 // This is helper routine for loop directives (e.g., 'for', 'simd',
7382 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007383 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007384 SmallVector<LoopIterationSpace, 4> IterSpaces(
7385 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007386 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007387 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007388 if (checkOpenMPIterationSpace(
7389 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7390 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007391 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007392 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007393 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007394 // OpenMP [2.8.1, simd construct, Restrictions]
7395 // All loops associated with the construct must be perfectly nested; that
7396 // is, there must be no intervening code nor any OpenMP directive between
7397 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007398 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7399 CurStmt = For->getBody();
7400 } else {
7401 assert(isa<CXXForRangeStmt>(CurStmt) &&
7402 "Expected canonical for or range-based for loops.");
7403 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7404 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007405 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7406 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007407 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007408 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7409 if (checkOpenMPIterationSpace(
7410 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7411 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007412 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007413 return 0;
7414 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7415 // Handle initialization of captured loop iterator variables.
7416 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7417 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7418 Captures[DRE] = DRE;
7419 }
7420 }
7421 // Move on to the next nested for loop, or to the loop body.
7422 // OpenMP [2.8.1, simd construct, Restrictions]
7423 // All loops associated with the construct must be perfectly nested; that
7424 // is, there must be no intervening code nor any OpenMP directive between
7425 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007426 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7427 CurStmt = For->getBody();
7428 } else {
7429 assert(isa<CXXForRangeStmt>(CurStmt) &&
7430 "Expected canonical for or range-based for loops.");
7431 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7432 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007433 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7434 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007435 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007436
Alexander Musmana5f070a2014-10-01 06:03:56 +00007437 Built.clear(/* size */ NestedLoopCount);
7438
7439 if (SemaRef.CurContext->isDependentContext())
7440 return NestedLoopCount;
7441
7442 // An example of what is generated for the following code:
7443 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007444 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007445 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007446 // for (k = 0; k < NK; ++k)
7447 // for (j = J0; j < NJ; j+=2) {
7448 // <loop body>
7449 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007450 //
7451 // We generate the code below.
7452 // Note: the loop body may be outlined in CodeGen.
7453 // Note: some counters may be C++ classes, operator- is used to find number of
7454 // iterations and operator+= to calculate counter value.
7455 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7456 // or i64 is currently supported).
7457 //
7458 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7459 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7460 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7461 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7462 // // similar updates for vars in clauses (e.g. 'linear')
7463 // <loop body (using local i and j)>
7464 // }
7465 // i = NI; // assign final values of counters
7466 // j = NJ;
7467 //
7468
7469 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7470 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007471 // Precondition tests if there is at least one iteration (all conditions are
7472 // true).
7473 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007474 Expr *N0 = IterSpaces[0].NumIterations;
7475 ExprResult LastIteration32 =
7476 widenIterationCount(/*Bits=*/32,
7477 SemaRef
7478 .PerformImplicitConversion(
7479 N0->IgnoreImpCasts(), N0->getType(),
7480 Sema::AA_Converting, /*AllowExplicit=*/true)
7481 .get(),
7482 SemaRef);
7483 ExprResult LastIteration64 = widenIterationCount(
7484 /*Bits=*/64,
7485 SemaRef
7486 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7487 Sema::AA_Converting,
7488 /*AllowExplicit=*/true)
7489 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007490 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007491
7492 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7493 return NestedLoopCount;
7494
Alexey Bataeve3727102018-04-18 15:57:46 +00007495 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007496 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7497
7498 Scope *CurScope = DSA.getCurScope();
7499 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007500 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007501 PreCond =
7502 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7503 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007504 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007505 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007506 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007507 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7508 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007509 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007510 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007511 SemaRef
7512 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7513 Sema::AA_Converting,
7514 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007515 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007516 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007517 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007518 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007519 SemaRef
7520 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7521 Sema::AA_Converting,
7522 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007523 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007524 }
7525
7526 // Choose either the 32-bit or 64-bit version.
7527 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007528 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7529 (LastIteration32.isUsable() &&
7530 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7531 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7532 fitsInto(
7533 /*Bits=*/32,
7534 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7535 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007536 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007537 QualType VType = LastIteration.get()->getType();
7538 QualType RealVType = VType;
7539 QualType StrideVType = VType;
7540 if (isOpenMPTaskLoopDirective(DKind)) {
7541 VType =
7542 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7543 StrideVType =
7544 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7545 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007546
7547 if (!LastIteration.isUsable())
7548 return 0;
7549
7550 // Save the number of iterations.
7551 ExprResult NumIterations = LastIteration;
7552 {
7553 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007554 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7555 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007556 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7557 if (!LastIteration.isUsable())
7558 return 0;
7559 }
7560
7561 // Calculate the last iteration number beforehand instead of doing this on
7562 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7563 llvm::APSInt Result;
7564 bool IsConstant =
7565 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7566 ExprResult CalcLastIteration;
7567 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007568 ExprResult SaveRef =
7569 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007570 LastIteration = SaveRef;
7571
7572 // Prepare SaveRef + 1.
7573 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007574 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007575 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7576 if (!NumIterations.isUsable())
7577 return 0;
7578 }
7579
7580 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7581
David Majnemer9d168222016-08-05 17:44:54 +00007582 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007583 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007584 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7585 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007586 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007587 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7588 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007589 SemaRef.AddInitializerToDecl(LBDecl,
7590 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7591 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007592
7593 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007594 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7595 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007596 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007597 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007598
7599 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7600 // This will be used to implement clause 'lastprivate'.
7601 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007602 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7603 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007604 SemaRef.AddInitializerToDecl(ILDecl,
7605 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7606 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007607
7608 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007609 VarDecl *STDecl =
7610 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7611 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007612 SemaRef.AddInitializerToDecl(STDecl,
7613 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7614 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007615
7616 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007617 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007618 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7619 UB.get(), LastIteration.get());
7620 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007621 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7622 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007623 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7624 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007625 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007626
7627 // If we have a combined directive that combines 'distribute', 'for' or
7628 // 'simd' we need to be able to access the bounds of the schedule of the
7629 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7630 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7631 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007632 // Lower bound variable, initialized with zero.
7633 VarDecl *CombLBDecl =
7634 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7635 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7636 SemaRef.AddInitializerToDecl(
7637 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7638 /*DirectInit*/ false);
7639
7640 // Upper bound variable, initialized with last iteration number.
7641 VarDecl *CombUBDecl =
7642 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7643 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7644 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7645 /*DirectInit*/ false);
7646
7647 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7648 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7649 ExprResult CombCondOp =
7650 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7651 LastIteration.get(), CombUB.get());
7652 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7653 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007654 CombEUB =
7655 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007656
Alexey Bataeve3727102018-04-18 15:57:46 +00007657 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007658 // We expect to have at least 2 more parameters than the 'parallel'
7659 // directive does - the lower and upper bounds of the previous schedule.
7660 assert(CD->getNumParams() >= 4 &&
7661 "Unexpected number of parameters in loop combined directive");
7662
7663 // Set the proper type for the bounds given what we learned from the
7664 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007665 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7666 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007667
7668 // Previous lower and upper bounds are obtained from the region
7669 // parameters.
7670 PrevLB =
7671 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7672 PrevUB =
7673 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7674 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007675 }
7676
7677 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007678 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007679 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007680 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007681 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7682 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007683 Expr *RHS =
7684 (isOpenMPWorksharingDirective(DKind) ||
7685 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7686 ? LB.get()
7687 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007688 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007689 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007690
7691 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7692 Expr *CombRHS =
7693 (isOpenMPWorksharingDirective(DKind) ||
7694 isOpenMPTaskLoopDirective(DKind) ||
7695 isOpenMPDistributeDirective(DKind))
7696 ? CombLB.get()
7697 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7698 CombInit =
7699 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007700 CombInit =
7701 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007702 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007703 }
7704
Alexey Bataev316ccf62019-01-29 18:51:58 +00007705 bool UseStrictCompare =
7706 RealVType->hasUnsignedIntegerRepresentation() &&
7707 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7708 return LIS.IsStrictCompare;
7709 });
7710 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7711 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007712 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007713 Expr *BoundUB = UB.get();
7714 if (UseStrictCompare) {
7715 BoundUB =
7716 SemaRef
7717 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7718 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7719 .get();
7720 BoundUB =
7721 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7722 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007723 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007724 (isOpenMPWorksharingDirective(DKind) ||
7725 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007726 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7727 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7728 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007729 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7730 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007731 ExprResult CombDistCond;
7732 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007733 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7734 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007735 }
7736
Carlo Bertolliffafe102017-04-20 00:39:39 +00007737 ExprResult CombCond;
7738 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007739 Expr *BoundCombUB = CombUB.get();
7740 if (UseStrictCompare) {
7741 BoundCombUB =
7742 SemaRef
7743 .BuildBinOp(
7744 CurScope, CondLoc, BO_Add, BoundCombUB,
7745 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7746 .get();
7747 BoundCombUB =
7748 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7749 .get();
7750 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007751 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007752 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7753 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007754 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007755 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007756 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007757 ExprResult Inc =
7758 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7759 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7760 if (!Inc.isUsable())
7761 return 0;
7762 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007763 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007764 if (!Inc.isUsable())
7765 return 0;
7766
7767 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7768 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007769 // In combined construct, add combined version that use CombLB and CombUB
7770 // base variables for the update
7771 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007772 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7773 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007774 // LB + ST
7775 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7776 if (!NextLB.isUsable())
7777 return 0;
7778 // LB = LB + ST
7779 NextLB =
7780 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007781 NextLB =
7782 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007783 if (!NextLB.isUsable())
7784 return 0;
7785 // UB + ST
7786 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7787 if (!NextUB.isUsable())
7788 return 0;
7789 // UB = UB + ST
7790 NextUB =
7791 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007792 NextUB =
7793 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007794 if (!NextUB.isUsable())
7795 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007796 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7797 CombNextLB =
7798 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7799 if (!NextLB.isUsable())
7800 return 0;
7801 // LB = LB + ST
7802 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7803 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007804 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7805 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007806 if (!CombNextLB.isUsable())
7807 return 0;
7808 // UB + ST
7809 CombNextUB =
7810 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7811 if (!CombNextUB.isUsable())
7812 return 0;
7813 // UB = UB + ST
7814 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7815 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007816 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7817 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007818 if (!CombNextUB.isUsable())
7819 return 0;
7820 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007821 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007822
Carlo Bertolliffafe102017-04-20 00:39:39 +00007823 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007824 // directive with for as IV = IV + ST; ensure upper bound expression based
7825 // on PrevUB instead of NumIterations - used to implement 'for' when found
7826 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007827 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007828 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007829 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007830 DistCond = SemaRef.BuildBinOp(
7831 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007832 assert(DistCond.isUsable() && "distribute cond expr was not built");
7833
7834 DistInc =
7835 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7836 assert(DistInc.isUsable() && "distribute inc expr was not built");
7837 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7838 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007839 DistInc =
7840 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007841 assert(DistInc.isUsable() && "distribute inc expr was not built");
7842
7843 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7844 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007845 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007846 ExprResult IsUBGreater =
7847 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7848 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7849 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7850 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7851 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007852 PrevEUB =
7853 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007854
Alexey Bataev316ccf62019-01-29 18:51:58 +00007855 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7856 // parallel for is in combination with a distribute directive with
7857 // schedule(static, 1)
7858 Expr *BoundPrevUB = PrevUB.get();
7859 if (UseStrictCompare) {
7860 BoundPrevUB =
7861 SemaRef
7862 .BuildBinOp(
7863 CurScope, CondLoc, BO_Add, BoundPrevUB,
7864 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7865 .get();
7866 BoundPrevUB =
7867 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7868 .get();
7869 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007870 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007871 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7872 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007873 }
7874
Alexander Musmana5f070a2014-10-01 06:03:56 +00007875 // Build updates and final values of the loop counters.
7876 bool HasErrors = false;
7877 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007878 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007879 Built.Updates.resize(NestedLoopCount);
7880 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007881 Built.DependentCounters.resize(NestedLoopCount);
7882 Built.DependentInits.resize(NestedLoopCount);
7883 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007884 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007885 // We implement the following algorithm for obtaining the
7886 // original loop iteration variable values based on the
7887 // value of the collapsed loop iteration variable IV.
7888 //
7889 // Let n+1 be the number of collapsed loops in the nest.
7890 // Iteration variables (I0, I1, .... In)
7891 // Iteration counts (N0, N1, ... Nn)
7892 //
7893 // Acc = IV;
7894 //
7895 // To compute Ik for loop k, 0 <= k <= n, generate:
7896 // Prod = N(k+1) * N(k+2) * ... * Nn;
7897 // Ik = Acc / Prod;
7898 // Acc -= Ik * Prod;
7899 //
7900 ExprResult Acc = IV;
7901 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007902 LoopIterationSpace &IS = IterSpaces[Cnt];
7903 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007904 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007905
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007906 // Compute prod
7907 ExprResult Prod =
7908 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7909 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7910 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7911 IterSpaces[K].NumIterations);
7912
7913 // Iter = Acc / Prod
7914 // If there is at least one more inner loop to avoid
7915 // multiplication by 1.
7916 if (Cnt + 1 < NestedLoopCount)
7917 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7918 Acc.get(), Prod.get());
7919 else
7920 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007921 if (!Iter.isUsable()) {
7922 HasErrors = true;
7923 break;
7924 }
7925
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007926 // Update Acc:
7927 // Acc -= Iter * Prod
7928 // Check if there is at least one more inner loop to avoid
7929 // multiplication by 1.
7930 if (Cnt + 1 < NestedLoopCount)
7931 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7932 Iter.get(), Prod.get());
7933 else
7934 Prod = Iter;
7935 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7936 Acc.get(), Prod.get());
7937
Alexey Bataev39f915b82015-05-08 10:41:21 +00007938 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007939 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007940 DeclRefExpr *CounterVar = buildDeclRefExpr(
7941 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7942 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007943 ExprResult Init =
7944 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7945 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007946 if (!Init.isUsable()) {
7947 HasErrors = true;
7948 break;
7949 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007950 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007951 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007952 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007953 if (!Update.isUsable()) {
7954 HasErrors = true;
7955 break;
7956 }
7957
7958 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007959 ExprResult Final =
7960 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7961 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7962 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007963 if (!Final.isUsable()) {
7964 HasErrors = true;
7965 break;
7966 }
7967
Alexander Musmana5f070a2014-10-01 06:03:56 +00007968 if (!Update.isUsable() || !Final.isUsable()) {
7969 HasErrors = true;
7970 break;
7971 }
7972 // Save results
7973 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007974 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007975 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007976 Built.Updates[Cnt] = Update.get();
7977 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007978 Built.DependentCounters[Cnt] = nullptr;
7979 Built.DependentInits[Cnt] = nullptr;
7980 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007981 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007982 Built.DependentCounters[Cnt] =
7983 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7984 Built.DependentInits[Cnt] =
7985 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7986 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7987 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007988 }
7989 }
7990
7991 if (HasErrors)
7992 return 0;
7993
7994 // Save results
7995 Built.IterationVarRef = IV.get();
7996 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007997 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007998 Built.CalcLastIteration = SemaRef
7999 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00008000 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00008001 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008002 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008003 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00008004 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008005 Built.Init = Init.get();
8006 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00008007 Built.LB = LB.get();
8008 Built.UB = UB.get();
8009 Built.IL = IL.get();
8010 Built.ST = ST.get();
8011 Built.EUB = EUB.get();
8012 Built.NLB = NextLB.get();
8013 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00008014 Built.PrevLB = PrevLB.get();
8015 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00008016 Built.DistInc = DistInc.get();
8017 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00008018 Built.DistCombinedFields.LB = CombLB.get();
8019 Built.DistCombinedFields.UB = CombUB.get();
8020 Built.DistCombinedFields.EUB = CombEUB.get();
8021 Built.DistCombinedFields.Init = CombInit.get();
8022 Built.DistCombinedFields.Cond = CombCond.get();
8023 Built.DistCombinedFields.NLB = CombNextLB.get();
8024 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00008025 Built.DistCombinedFields.DistCond = CombDistCond.get();
8026 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008027
Alexey Bataevabfc0692014-06-25 06:52:00 +00008028 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008029}
8030
Alexey Bataev10e775f2015-07-30 11:36:16 +00008031static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00008032 auto CollapseClauses =
8033 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
8034 if (CollapseClauses.begin() != CollapseClauses.end())
8035 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00008036 return nullptr;
8037}
8038
Alexey Bataev10e775f2015-07-30 11:36:16 +00008039static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00008040 auto OrderedClauses =
8041 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
8042 if (OrderedClauses.begin() != OrderedClauses.end())
8043 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00008044 return nullptr;
8045}
8046
Kelvin Lic5609492016-07-15 04:39:07 +00008047static bool checkSimdlenSafelenSpecified(Sema &S,
8048 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008049 const OMPSafelenClause *Safelen = nullptr;
8050 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00008051
Alexey Bataeve3727102018-04-18 15:57:46 +00008052 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00008053 if (Clause->getClauseKind() == OMPC_safelen)
8054 Safelen = cast<OMPSafelenClause>(Clause);
8055 else if (Clause->getClauseKind() == OMPC_simdlen)
8056 Simdlen = cast<OMPSimdlenClause>(Clause);
8057 if (Safelen && Simdlen)
8058 break;
8059 }
8060
8061 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008062 const Expr *SimdlenLength = Simdlen->getSimdlen();
8063 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00008064 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
8065 SimdlenLength->isInstantiationDependent() ||
8066 SimdlenLength->containsUnexpandedParameterPack())
8067 return false;
8068 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
8069 SafelenLength->isInstantiationDependent() ||
8070 SafelenLength->containsUnexpandedParameterPack())
8071 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008072 Expr::EvalResult SimdlenResult, SafelenResult;
8073 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
8074 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
8075 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
8076 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00008077 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
8078 // If both simdlen and safelen clauses are specified, the value of the
8079 // simdlen parameter must be less than or equal to the value of the safelen
8080 // parameter.
8081 if (SimdlenRes > SafelenRes) {
8082 S.Diag(SimdlenLength->getExprLoc(),
8083 diag::err_omp_wrong_simdlen_safelen_values)
8084 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
8085 return true;
8086 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00008087 }
8088 return false;
8089}
8090
Alexey Bataeve3727102018-04-18 15:57:46 +00008091StmtResult
8092Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8093 SourceLocation StartLoc, SourceLocation EndLoc,
8094 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008095 if (!AStmt)
8096 return StmtError();
8097
8098 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008099 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008100 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8101 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008102 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008103 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8104 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008105 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008106 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008107
Alexander Musmana5f070a2014-10-01 06:03:56 +00008108 assert((CurContext->isDependentContext() || B.builtAll()) &&
8109 "omp simd loop exprs were not built");
8110
Alexander Musman3276a272015-03-21 10:12:56 +00008111 if (!CurContext->isDependentContext()) {
8112 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008113 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008114 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00008115 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008116 B.NumIterations, *this, CurScope,
8117 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00008118 return StmtError();
8119 }
8120 }
8121
Kelvin Lic5609492016-07-15 04:39:07 +00008122 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008123 return StmtError();
8124
Reid Kleckner87a31802018-03-12 21:43:02 +00008125 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008126 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8127 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008128}
8129
Alexey Bataeve3727102018-04-18 15:57:46 +00008130StmtResult
8131Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8132 SourceLocation StartLoc, SourceLocation EndLoc,
8133 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008134 if (!AStmt)
8135 return StmtError();
8136
8137 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008138 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008139 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8140 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008141 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008142 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8143 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008144 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00008145 return StmtError();
8146
Alexander Musmana5f070a2014-10-01 06:03:56 +00008147 assert((CurContext->isDependentContext() || B.builtAll()) &&
8148 "omp for loop exprs were not built");
8149
Alexey Bataev54acd402015-08-04 11:18:19 +00008150 if (!CurContext->isDependentContext()) {
8151 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008152 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008153 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008154 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008155 B.NumIterations, *this, CurScope,
8156 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008157 return StmtError();
8158 }
8159 }
8160
Reid Kleckner87a31802018-03-12 21:43:02 +00008161 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008162 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008163 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00008164}
8165
Alexander Musmanf82886e2014-09-18 05:12:34 +00008166StmtResult Sema::ActOnOpenMPForSimdDirective(
8167 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008168 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008169 if (!AStmt)
8170 return StmtError();
8171
8172 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008173 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008174 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8175 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00008176 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008177 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008178 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8179 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008180 if (NestedLoopCount == 0)
8181 return StmtError();
8182
Alexander Musmanc6388682014-12-15 07:07:06 +00008183 assert((CurContext->isDependentContext() || B.builtAll()) &&
8184 "omp for simd loop exprs were not built");
8185
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008186 if (!CurContext->isDependentContext()) {
8187 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008188 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008189 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008190 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008191 B.NumIterations, *this, CurScope,
8192 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008193 return StmtError();
8194 }
8195 }
8196
Kelvin Lic5609492016-07-15 04:39:07 +00008197 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008198 return StmtError();
8199
Reid Kleckner87a31802018-03-12 21:43:02 +00008200 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008201 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8202 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008203}
8204
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008205StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8206 Stmt *AStmt,
8207 SourceLocation StartLoc,
8208 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008209 if (!AStmt)
8210 return StmtError();
8211
8212 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008213 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008214 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008215 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008216 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008217 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008218 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008219 return StmtError();
8220 // All associated statements must be '#pragma omp section' except for
8221 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008222 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008223 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8224 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008225 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008226 diag::err_omp_sections_substmt_not_section);
8227 return StmtError();
8228 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008229 cast<OMPSectionDirective>(SectionStmt)
8230 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008231 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008232 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008233 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008234 return StmtError();
8235 }
8236
Reid Kleckner87a31802018-03-12 21:43:02 +00008237 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008238
Alexey Bataev25e5b442015-09-15 12:52:43 +00008239 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8240 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008241}
8242
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008243StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8244 SourceLocation StartLoc,
8245 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008246 if (!AStmt)
8247 return StmtError();
8248
8249 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008250
Reid Kleckner87a31802018-03-12 21:43:02 +00008251 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008252 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008253
Alexey Bataev25e5b442015-09-15 12:52:43 +00008254 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8255 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008256}
8257
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008258StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8259 Stmt *AStmt,
8260 SourceLocation StartLoc,
8261 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008262 if (!AStmt)
8263 return StmtError();
8264
8265 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008266
Reid Kleckner87a31802018-03-12 21:43:02 +00008267 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008268
Alexey Bataev3255bf32015-01-19 05:20:46 +00008269 // OpenMP [2.7.3, single Construct, Restrictions]
8270 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008271 const OMPClause *Nowait = nullptr;
8272 const OMPClause *Copyprivate = nullptr;
8273 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008274 if (Clause->getClauseKind() == OMPC_nowait)
8275 Nowait = Clause;
8276 else if (Clause->getClauseKind() == OMPC_copyprivate)
8277 Copyprivate = Clause;
8278 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008279 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008280 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008281 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008282 return StmtError();
8283 }
8284 }
8285
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008286 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8287}
8288
Alexander Musman80c22892014-07-17 08:54:58 +00008289StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8290 SourceLocation StartLoc,
8291 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008292 if (!AStmt)
8293 return StmtError();
8294
8295 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008296
Reid Kleckner87a31802018-03-12 21:43:02 +00008297 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008298
8299 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8300}
8301
Alexey Bataev28c75412015-12-15 08:19:24 +00008302StmtResult Sema::ActOnOpenMPCriticalDirective(
8303 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8304 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008305 if (!AStmt)
8306 return StmtError();
8307
8308 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008309
Alexey Bataev28c75412015-12-15 08:19:24 +00008310 bool ErrorFound = false;
8311 llvm::APSInt Hint;
8312 SourceLocation HintLoc;
8313 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008314 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008315 if (C->getClauseKind() == OMPC_hint) {
8316 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008317 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008318 ErrorFound = true;
8319 }
8320 Expr *E = cast<OMPHintClause>(C)->getHint();
8321 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008322 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008323 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008324 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008325 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008326 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008327 }
8328 }
8329 }
8330 if (ErrorFound)
8331 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008332 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008333 if (Pair.first && DirName.getName() && !DependentHint) {
8334 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8335 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008336 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008337 Diag(HintLoc, diag::note_omp_critical_hint_here)
8338 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008339 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008340 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008341 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008342 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008343 << 1
8344 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8345 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008346 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008347 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008348 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008349 }
8350 }
8351
Reid Kleckner87a31802018-03-12 21:43:02 +00008352 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008353
Alexey Bataev28c75412015-12-15 08:19:24 +00008354 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8355 Clauses, AStmt);
8356 if (!Pair.first && DirName.getName() && !DependentHint)
8357 DSAStack->addCriticalWithHint(Dir, Hint);
8358 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008359}
8360
Alexey Bataev4acb8592014-07-07 13:01:15 +00008361StmtResult Sema::ActOnOpenMPParallelForDirective(
8362 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008363 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008364 if (!AStmt)
8365 return StmtError();
8366
Alexey Bataeve3727102018-04-18 15:57:46 +00008367 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008368 // 1.2.2 OpenMP Language Terminology
8369 // Structured block - An executable statement with a single entry at the
8370 // top and a single exit at the bottom.
8371 // The point of exit cannot be a branch out of the structured block.
8372 // longjmp() and throw() must not violate the entry/exit criteria.
8373 CS->getCapturedDecl()->setNothrow();
8374
Alexander Musmanc6388682014-12-15 07:07:06 +00008375 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008376 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8377 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008378 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008379 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008380 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8381 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008382 if (NestedLoopCount == 0)
8383 return StmtError();
8384
Alexander Musmana5f070a2014-10-01 06:03:56 +00008385 assert((CurContext->isDependentContext() || B.builtAll()) &&
8386 "omp parallel for loop exprs were not built");
8387
Alexey Bataev54acd402015-08-04 11:18:19 +00008388 if (!CurContext->isDependentContext()) {
8389 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008390 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008391 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008392 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008393 B.NumIterations, *this, CurScope,
8394 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008395 return StmtError();
8396 }
8397 }
8398
Reid Kleckner87a31802018-03-12 21:43:02 +00008399 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008400 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008401 NestedLoopCount, Clauses, AStmt, B,
8402 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008403}
8404
Alexander Musmane4e893b2014-09-23 09:33:00 +00008405StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8406 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008407 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008408 if (!AStmt)
8409 return StmtError();
8410
Alexey Bataeve3727102018-04-18 15:57:46 +00008411 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008412 // 1.2.2 OpenMP Language Terminology
8413 // Structured block - An executable statement with a single entry at the
8414 // top and a single exit at the bottom.
8415 // The point of exit cannot be a branch out of the structured block.
8416 // longjmp() and throw() must not violate the entry/exit criteria.
8417 CS->getCapturedDecl()->setNothrow();
8418
Alexander Musmanc6388682014-12-15 07:07:06 +00008419 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008420 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8421 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008422 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008423 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008424 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8425 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008426 if (NestedLoopCount == 0)
8427 return StmtError();
8428
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008429 if (!CurContext->isDependentContext()) {
8430 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008431 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008432 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008433 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008434 B.NumIterations, *this, CurScope,
8435 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008436 return StmtError();
8437 }
8438 }
8439
Kelvin Lic5609492016-07-15 04:39:07 +00008440 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008441 return StmtError();
8442
Reid Kleckner87a31802018-03-12 21:43:02 +00008443 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008444 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008445 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008446}
8447
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008448StmtResult
cchen47d60942019-12-05 13:43:48 -05008449Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
8450 Stmt *AStmt, SourceLocation StartLoc,
8451 SourceLocation EndLoc) {
8452 if (!AStmt)
8453 return StmtError();
8454
8455 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8456 auto *CS = cast<CapturedStmt>(AStmt);
8457 // 1.2.2 OpenMP Language Terminology
8458 // Structured block - An executable statement with a single entry at the
8459 // top and a single exit at the bottom.
8460 // The point of exit cannot be a branch out of the structured block.
8461 // longjmp() and throw() must not violate the entry/exit criteria.
8462 CS->getCapturedDecl()->setNothrow();
8463
8464 setFunctionHasBranchProtectedScope();
8465
8466 return OMPParallelMasterDirective::Create(Context, StartLoc, EndLoc, Clauses,
8467 AStmt);
8468}
8469
8470StmtResult
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008471Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8472 Stmt *AStmt, SourceLocation StartLoc,
8473 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008474 if (!AStmt)
8475 return StmtError();
8476
8477 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008478 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008479 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008480 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008481 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008482 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008483 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008484 return StmtError();
8485 // All associated statements must be '#pragma omp section' except for
8486 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008487 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008488 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8489 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008490 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008491 diag::err_omp_parallel_sections_substmt_not_section);
8492 return StmtError();
8493 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008494 cast<OMPSectionDirective>(SectionStmt)
8495 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008496 }
8497 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008498 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008499 diag::err_omp_parallel_sections_not_compound_stmt);
8500 return StmtError();
8501 }
8502
Reid Kleckner87a31802018-03-12 21:43:02 +00008503 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008504
Alexey Bataev25e5b442015-09-15 12:52:43 +00008505 return OMPParallelSectionsDirective::Create(
8506 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008507}
8508
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008509StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8510 Stmt *AStmt, SourceLocation StartLoc,
8511 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008512 if (!AStmt)
8513 return StmtError();
8514
David Majnemer9d168222016-08-05 17:44:54 +00008515 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008516 // 1.2.2 OpenMP Language Terminology
8517 // Structured block - An executable statement with a single entry at the
8518 // top and a single exit at the bottom.
8519 // The point of exit cannot be a branch out of the structured block.
8520 // longjmp() and throw() must not violate the entry/exit criteria.
8521 CS->getCapturedDecl()->setNothrow();
8522
Reid Kleckner87a31802018-03-12 21:43:02 +00008523 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008524
Alexey Bataev25e5b442015-09-15 12:52:43 +00008525 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8526 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008527}
8528
Alexey Bataev68446b72014-07-18 07:47:19 +00008529StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8530 SourceLocation EndLoc) {
8531 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8532}
8533
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008534StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8535 SourceLocation EndLoc) {
8536 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8537}
8538
Alexey Bataev2df347a2014-07-18 10:17:07 +00008539StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8540 SourceLocation EndLoc) {
8541 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8542}
8543
Alexey Bataev169d96a2017-07-18 20:17:46 +00008544StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8545 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008546 SourceLocation StartLoc,
8547 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008548 if (!AStmt)
8549 return StmtError();
8550
8551 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008552
Reid Kleckner87a31802018-03-12 21:43:02 +00008553 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008554
Alexey Bataev169d96a2017-07-18 20:17:46 +00008555 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008556 AStmt,
8557 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008558}
8559
Alexey Bataev6125da92014-07-21 11:26:11 +00008560StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8561 SourceLocation StartLoc,
8562 SourceLocation EndLoc) {
Alexey Bataevea9166b2020-02-06 16:30:23 -05008563 OMPFlushClause *FC = nullptr;
8564 OMPClause *OrderClause = nullptr;
8565 for (OMPClause *C : Clauses) {
8566 if (C->getClauseKind() == OMPC_flush)
8567 FC = cast<OMPFlushClause>(C);
8568 else
8569 OrderClause = C;
8570 }
Alexey Bataev04a830f2020-02-10 14:30:39 -05008571 OpenMPClauseKind MemOrderKind = OMPC_unknown;
8572 SourceLocation MemOrderLoc;
8573 for (const OMPClause *C : Clauses) {
Alexey Bataev95598342020-02-10 15:49:05 -05008574 if (C->getClauseKind() == OMPC_acq_rel ||
8575 C->getClauseKind() == OMPC_acquire ||
8576 C->getClauseKind() == OMPC_release) {
Alexey Bataev04a830f2020-02-10 14:30:39 -05008577 if (MemOrderKind != OMPC_unknown) {
8578 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
8579 << getOpenMPDirectiveName(OMPD_flush) << 1
8580 << SourceRange(C->getBeginLoc(), C->getEndLoc());
8581 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
8582 << getOpenMPClauseName(MemOrderKind);
8583 } else {
8584 MemOrderKind = C->getClauseKind();
8585 MemOrderLoc = C->getBeginLoc();
8586 }
8587 }
8588 }
Alexey Bataevea9166b2020-02-06 16:30:23 -05008589 if (FC && OrderClause) {
8590 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
8591 << getOpenMPClauseName(OrderClause->getClauseKind());
8592 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
8593 << getOpenMPClauseName(OrderClause->getClauseKind());
8594 return StmtError();
8595 }
Alexey Bataev6125da92014-07-21 11:26:11 +00008596 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8597}
8598
Alexey Bataev346265e2015-09-25 10:37:12 +00008599StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8600 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008601 SourceLocation StartLoc,
8602 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008603 const OMPClause *DependFound = nullptr;
8604 const OMPClause *DependSourceClause = nullptr;
8605 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008606 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008607 const OMPThreadsClause *TC = nullptr;
8608 const OMPSIMDClause *SC = nullptr;
8609 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008610 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8611 DependFound = C;
8612 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8613 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008614 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008615 << getOpenMPDirectiveName(OMPD_ordered)
8616 << getOpenMPClauseName(OMPC_depend) << 2;
8617 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008618 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008619 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008620 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008621 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008622 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008623 << 0;
8624 ErrorFound = true;
8625 }
8626 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8627 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008628 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008629 << 1;
8630 ErrorFound = true;
8631 }
8632 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008633 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008634 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008635 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008636 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008637 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008638 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008639 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008640 if (!ErrorFound && !SC &&
8641 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008642 // OpenMP [2.8.1,simd Construct, Restrictions]
8643 // An ordered construct with the simd clause is the only OpenMP construct
8644 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008645 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8646 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008647 ErrorFound = true;
8648 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008649 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008650 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8651 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008652 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008653 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008654 diag::err_omp_ordered_directive_without_param);
8655 ErrorFound = true;
8656 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008657 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008658 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008659 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8660 << (TC != nullptr);
Alexey Bataevcb8e6912020-01-31 16:09:26 -05008661 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
Alexey Bataeveb482352015-12-18 05:05:56 +00008662 ErrorFound = true;
8663 }
8664 }
8665 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008666 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008667
8668 if (AStmt) {
8669 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8670
Reid Kleckner87a31802018-03-12 21:43:02 +00008671 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008672 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008673
8674 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008675}
8676
Alexey Bataev1d160b12015-03-13 12:27:31 +00008677namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008678/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008679/// construct.
8680class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008681 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008682 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008683 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008684 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008685 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008686 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008687 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008688 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008689 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008690 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008691 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008692 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008693 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008694 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008695 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008696 /// expression.
8697 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008698 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008699 /// part.
8700 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008701 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008702 NoError
8703 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008704 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008705 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008706 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008707 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008708 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008709 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008710 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008711 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008712 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008713 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8714 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8715 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008716 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008717 /// important for non-associative operations.
8718 bool IsXLHSInRHSPart;
8719 BinaryOperatorKind Op;
8720 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008721 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008722 /// if it is a prefix unary operation.
8723 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008724
8725public:
8726 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008727 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008728 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008729 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008730 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008731 /// expression. If DiagId and NoteId == 0, then only check is performed
8732 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008733 /// \param DiagId Diagnostic which should be emitted if error is found.
8734 /// \param NoteId Diagnostic note for the main error message.
8735 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008736 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008737 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008738 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008739 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008740 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008741 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008742 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8743 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8744 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008745 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008746 /// false otherwise.
8747 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8748
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008749 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008750 /// if it is a prefix unary operation.
8751 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8752
Alexey Bataev1d160b12015-03-13 12:27:31 +00008753private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008754 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8755 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008756};
8757} // namespace
8758
8759bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8760 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8761 ExprAnalysisErrorCode ErrorFound = NoError;
8762 SourceLocation ErrorLoc, NoteLoc;
8763 SourceRange ErrorRange, NoteRange;
8764 // Allowed constructs are:
8765 // x = x binop expr;
8766 // x = expr binop x;
8767 if (AtomicBinOp->getOpcode() == BO_Assign) {
8768 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008769 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008770 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8771 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8772 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8773 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008774 Op = AtomicInnerBinOp->getOpcode();
8775 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008776 Expr *LHS = AtomicInnerBinOp->getLHS();
8777 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008778 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8779 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8780 /*Canonical=*/true);
8781 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8782 /*Canonical=*/true);
8783 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8784 /*Canonical=*/true);
8785 if (XId == LHSId) {
8786 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008787 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008788 } else if (XId == RHSId) {
8789 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008790 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008791 } else {
8792 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8793 ErrorRange = AtomicInnerBinOp->getSourceRange();
8794 NoteLoc = X->getExprLoc();
8795 NoteRange = X->getSourceRange();
8796 ErrorFound = NotAnUpdateExpression;
8797 }
8798 } else {
8799 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8800 ErrorRange = AtomicInnerBinOp->getSourceRange();
8801 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8802 NoteRange = SourceRange(NoteLoc, NoteLoc);
8803 ErrorFound = NotABinaryOperator;
8804 }
8805 } else {
8806 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8807 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8808 ErrorFound = NotABinaryExpression;
8809 }
8810 } else {
8811 ErrorLoc = AtomicBinOp->getExprLoc();
8812 ErrorRange = AtomicBinOp->getSourceRange();
8813 NoteLoc = AtomicBinOp->getOperatorLoc();
8814 NoteRange = SourceRange(NoteLoc, NoteLoc);
8815 ErrorFound = NotAnAssignmentOp;
8816 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008817 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008818 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8819 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8820 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008821 }
8822 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008823 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008824 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008825}
8826
8827bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8828 unsigned NoteId) {
8829 ExprAnalysisErrorCode ErrorFound = NoError;
8830 SourceLocation ErrorLoc, NoteLoc;
8831 SourceRange ErrorRange, NoteRange;
8832 // Allowed constructs are:
8833 // x++;
8834 // x--;
8835 // ++x;
8836 // --x;
8837 // x binop= expr;
8838 // x = x binop expr;
8839 // x = expr binop x;
8840 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8841 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8842 if (AtomicBody->getType()->isScalarType() ||
8843 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008844 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008845 AtomicBody->IgnoreParenImpCasts())) {
8846 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008847 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008848 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008849 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008850 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008851 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008852 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008853 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8854 AtomicBody->IgnoreParenImpCasts())) {
8855 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008856 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008857 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008858 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008859 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008860 // Check for Unary Operation
8861 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008862 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008863 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8864 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008865 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008866 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8867 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008868 } else {
8869 ErrorFound = NotAnUnaryIncDecExpression;
8870 ErrorLoc = AtomicUnaryOp->getExprLoc();
8871 ErrorRange = AtomicUnaryOp->getSourceRange();
8872 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8873 NoteRange = SourceRange(NoteLoc, NoteLoc);
8874 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008875 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008876 ErrorFound = NotABinaryOrUnaryExpression;
8877 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8878 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8879 }
8880 } else {
8881 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008882 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008883 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8884 }
8885 } else {
8886 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008887 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008888 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8889 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008890 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008891 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8892 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8893 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008894 }
8895 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008896 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008897 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008898 // Build an update expression of form 'OpaqueValueExpr(x) binop
8899 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8900 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8901 auto *OVEX = new (SemaRef.getASTContext())
8902 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8903 auto *OVEExpr = new (SemaRef.getASTContext())
8904 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008905 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008906 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8907 IsXLHSInRHSPart ? OVEExpr : OVEX);
8908 if (Update.isInvalid())
8909 return true;
8910 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8911 Sema::AA_Casting);
8912 if (Update.isInvalid())
8913 return true;
8914 UpdateExpr = Update.get();
8915 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008916 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008917}
8918
Alexey Bataev0162e452014-07-22 10:10:35 +00008919StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8920 Stmt *AStmt,
8921 SourceLocation StartLoc,
8922 SourceLocation EndLoc) {
Alexey Bataev2d4f80f2020-02-11 15:15:21 -05008923 // Register location of the first atomic directive.
8924 DSAStack->addAtomicDirectiveLoc(StartLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008925 if (!AStmt)
8926 return StmtError();
8927
David Majnemer9d168222016-08-05 17:44:54 +00008928 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008929 // 1.2.2 OpenMP Language Terminology
8930 // Structured block - An executable statement with a single entry at the
8931 // top and a single exit at the bottom.
8932 // The point of exit cannot be a branch out of the structured block.
8933 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008934 OpenMPClauseKind AtomicKind = OMPC_unknown;
8935 SourceLocation AtomicKindLoc;
Alexey Bataevea9166b2020-02-06 16:30:23 -05008936 OpenMPClauseKind MemOrderKind = OMPC_unknown;
8937 SourceLocation MemOrderLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008938 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008939 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008940 C->getClauseKind() == OMPC_update ||
8941 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008942 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008943 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008944 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataev04a830f2020-02-10 14:30:39 -05008945 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
Alexey Bataevdea47612014-07-23 07:46:59 +00008946 << getOpenMPClauseName(AtomicKind);
8947 } else {
8948 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008949 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008950 }
8951 }
Alexey Bataevea9166b2020-02-06 16:30:23 -05008952 if (C->getClauseKind() == OMPC_seq_cst ||
Alexey Bataev04a830f2020-02-10 14:30:39 -05008953 C->getClauseKind() == OMPC_acq_rel ||
Alexey Bataev95598342020-02-10 15:49:05 -05008954 C->getClauseKind() == OMPC_acquire ||
Alexey Bataev9a8defc2020-02-11 11:10:43 -05008955 C->getClauseKind() == OMPC_release ||
8956 C->getClauseKind() == OMPC_relaxed) {
Alexey Bataevea9166b2020-02-06 16:30:23 -05008957 if (MemOrderKind != OMPC_unknown) {
Alexey Bataev04a830f2020-02-10 14:30:39 -05008958 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
8959 << getOpenMPDirectiveName(OMPD_atomic) << 0
Alexey Bataevea9166b2020-02-06 16:30:23 -05008960 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataev04a830f2020-02-10 14:30:39 -05008961 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
Alexey Bataevea9166b2020-02-06 16:30:23 -05008962 << getOpenMPClauseName(MemOrderKind);
8963 } else {
8964 MemOrderKind = C->getClauseKind();
8965 MemOrderLoc = C->getBeginLoc();
8966 }
8967 }
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008968 }
Alexey Bataev9a3740c2020-02-11 09:35:52 -05008969 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
8970 // If atomic-clause is read then memory-order-clause must not be acq_rel or
8971 // release.
8972 // If atomic-clause is write then memory-order-clause must not be acq_rel or
8973 // acquire.
8974 // If atomic-clause is update or not present then memory-order-clause must not
8975 // be acq_rel or acquire.
8976 if ((AtomicKind == OMPC_read &&
8977 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
8978 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
8979 AtomicKind == OMPC_unknown) &&
8980 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
8981 SourceLocation Loc = AtomicKindLoc;
8982 if (AtomicKind == OMPC_unknown)
8983 Loc = StartLoc;
8984 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
8985 << getOpenMPClauseName(AtomicKind)
8986 << (AtomicKind == OMPC_unknown ? 1 : 0)
8987 << getOpenMPClauseName(MemOrderKind);
8988 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
8989 << getOpenMPClauseName(MemOrderKind);
8990 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008991
Alexey Bataeve3727102018-04-18 15:57:46 +00008992 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008993 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8994 Body = EWC->getSubExpr();
8995
Alexey Bataev62cec442014-11-18 10:14:22 +00008996 Expr *X = nullptr;
8997 Expr *V = nullptr;
8998 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008999 Expr *UE = nullptr;
9000 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009001 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00009002 // OpenMP [2.12.6, atomic Construct]
9003 // In the next expressions:
9004 // * x and v (as applicable) are both l-value expressions with scalar type.
9005 // * During the execution of an atomic region, multiple syntactic
9006 // occurrences of x must designate the same storage location.
9007 // * Neither of v and expr (as applicable) may access the storage location
9008 // designated by x.
9009 // * Neither of x and expr (as applicable) may access the storage location
9010 // designated by v.
9011 // * expr is an expression with scalar type.
9012 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
9013 // * binop, binop=, ++, and -- are not overloaded operators.
9014 // * The expression x binop expr must be numerically equivalent to x binop
9015 // (expr). This requirement is satisfied if the operators in expr have
9016 // precedence greater than binop, or by using parentheses around expr or
9017 // subexpressions of expr.
9018 // * The expression expr binop x must be numerically equivalent to (expr)
9019 // binop x. This requirement is satisfied if the operators in expr have
9020 // precedence equal to or greater than binop, or by using parentheses around
9021 // expr or subexpressions of expr.
9022 // * For forms that allow multiple occurrences of x, the number of times
9023 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00009024 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009025 enum {
9026 NotAnExpression,
9027 NotAnAssignmentOp,
9028 NotAScalarType,
9029 NotAnLValue,
9030 NoError
9031 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00009032 SourceLocation ErrorLoc, NoteLoc;
9033 SourceRange ErrorRange, NoteRange;
9034 // If clause is read:
9035 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00009036 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9037 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00009038 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9039 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9040 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9041 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
9042 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9043 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
9044 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009045 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00009046 ErrorFound = NotAnLValue;
9047 ErrorLoc = AtomicBinOp->getExprLoc();
9048 ErrorRange = AtomicBinOp->getSourceRange();
9049 NoteLoc = NotLValueExpr->getExprLoc();
9050 NoteRange = NotLValueExpr->getSourceRange();
9051 }
9052 } else if (!X->isInstantiationDependent() ||
9053 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009054 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00009055 (X->isInstantiationDependent() || X->getType()->isScalarType())
9056 ? V
9057 : X;
9058 ErrorFound = NotAScalarType;
9059 ErrorLoc = AtomicBinOp->getExprLoc();
9060 ErrorRange = AtomicBinOp->getSourceRange();
9061 NoteLoc = NotScalarExpr->getExprLoc();
9062 NoteRange = NotScalarExpr->getSourceRange();
9063 }
Alexey Bataev5a195472015-09-04 12:55:50 +00009064 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00009065 ErrorFound = NotAnAssignmentOp;
9066 ErrorLoc = AtomicBody->getExprLoc();
9067 ErrorRange = AtomicBody->getSourceRange();
9068 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9069 : AtomicBody->getExprLoc();
9070 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9071 : AtomicBody->getSourceRange();
9072 }
9073 } else {
9074 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009075 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00009076 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00009077 }
Alexey Bataev62cec442014-11-18 10:14:22 +00009078 if (ErrorFound != NoError) {
9079 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
9080 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00009081 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9082 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00009083 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00009084 }
9085 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00009086 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00009087 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009088 enum {
9089 NotAnExpression,
9090 NotAnAssignmentOp,
9091 NotAScalarType,
9092 NotAnLValue,
9093 NoError
9094 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00009095 SourceLocation ErrorLoc, NoteLoc;
9096 SourceRange ErrorRange, NoteRange;
9097 // If clause is write:
9098 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009099 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9100 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00009101 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9102 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00009103 X = AtomicBinOp->getLHS();
9104 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00009105 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9106 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
9107 if (!X->isLValue()) {
9108 ErrorFound = NotAnLValue;
9109 ErrorLoc = AtomicBinOp->getExprLoc();
9110 ErrorRange = AtomicBinOp->getSourceRange();
9111 NoteLoc = X->getExprLoc();
9112 NoteRange = X->getSourceRange();
9113 }
9114 } else if (!X->isInstantiationDependent() ||
9115 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009116 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00009117 (X->isInstantiationDependent() || X->getType()->isScalarType())
9118 ? E
9119 : X;
9120 ErrorFound = NotAScalarType;
9121 ErrorLoc = AtomicBinOp->getExprLoc();
9122 ErrorRange = AtomicBinOp->getSourceRange();
9123 NoteLoc = NotScalarExpr->getExprLoc();
9124 NoteRange = NotScalarExpr->getSourceRange();
9125 }
Alexey Bataev5a195472015-09-04 12:55:50 +00009126 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00009127 ErrorFound = NotAnAssignmentOp;
9128 ErrorLoc = AtomicBody->getExprLoc();
9129 ErrorRange = AtomicBody->getSourceRange();
9130 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9131 : AtomicBody->getExprLoc();
9132 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9133 : AtomicBody->getSourceRange();
9134 }
9135 } else {
9136 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009137 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00009138 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00009139 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00009140 if (ErrorFound != NoError) {
9141 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
9142 << ErrorRange;
9143 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9144 << NoteRange;
9145 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00009146 }
9147 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00009148 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009149 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00009150 // If clause is update:
9151 // x++;
9152 // x--;
9153 // ++x;
9154 // --x;
9155 // x binop= expr;
9156 // x = x binop expr;
9157 // x = expr binop x;
9158 OpenMPAtomicUpdateChecker Checker(*this);
9159 if (Checker.checkStatement(
9160 Body, (AtomicKind == OMPC_update)
9161 ? diag::err_omp_atomic_update_not_expression_statement
9162 : diag::err_omp_atomic_not_expression_statement,
9163 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00009164 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00009165 if (!CurContext->isDependentContext()) {
9166 E = Checker.getExpr();
9167 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00009168 UE = Checker.getUpdateExpr();
9169 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00009170 }
Alexey Bataev459dec02014-07-24 06:46:57 +00009171 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009172 enum {
9173 NotAnAssignmentOp,
9174 NotACompoundStatement,
9175 NotTwoSubstatements,
9176 NotASpecificExpression,
9177 NoError
9178 } ErrorFound = NoError;
9179 SourceLocation ErrorLoc, NoteLoc;
9180 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009181 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009182 // If clause is a capture:
9183 // v = x++;
9184 // v = x--;
9185 // v = ++x;
9186 // v = --x;
9187 // v = x binop= expr;
9188 // v = x = x binop expr;
9189 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00009190 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00009191 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9192 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9193 V = AtomicBinOp->getLHS();
9194 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9195 OpenMPAtomicUpdateChecker Checker(*this);
9196 if (Checker.checkStatement(
9197 Body, diag::err_omp_atomic_capture_not_expression_statement,
9198 diag::note_omp_atomic_update))
9199 return StmtError();
9200 E = Checker.getExpr();
9201 X = Checker.getX();
9202 UE = Checker.getUpdateExpr();
9203 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9204 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00009205 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009206 ErrorLoc = AtomicBody->getExprLoc();
9207 ErrorRange = AtomicBody->getSourceRange();
9208 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9209 : AtomicBody->getExprLoc();
9210 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9211 : AtomicBody->getSourceRange();
9212 ErrorFound = NotAnAssignmentOp;
9213 }
9214 if (ErrorFound != NoError) {
9215 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9216 << ErrorRange;
9217 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9218 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009219 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009220 if (CurContext->isDependentContext())
9221 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009222 } else {
9223 // If clause is a capture:
9224 // { v = x; x = expr; }
9225 // { v = x; x++; }
9226 // { v = x; x--; }
9227 // { v = x; ++x; }
9228 // { v = x; --x; }
9229 // { v = x; x binop= expr; }
9230 // { v = x; x = x binop expr; }
9231 // { v = x; x = expr binop x; }
9232 // { x++; v = x; }
9233 // { x--; v = x; }
9234 // { ++x; v = x; }
9235 // { --x; v = x; }
9236 // { x binop= expr; v = x; }
9237 // { x = x binop expr; v = x; }
9238 // { x = expr binop x; v = x; }
9239 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9240 // Check that this is { expr1; expr2; }
9241 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009242 Stmt *First = CS->body_front();
9243 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009244 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9245 First = EWC->getSubExpr()->IgnoreParenImpCasts();
9246 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9247 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9248 // Need to find what subexpression is 'v' and what is 'x'.
9249 OpenMPAtomicUpdateChecker Checker(*this);
9250 bool IsUpdateExprFound = !Checker.checkStatement(Second);
9251 BinaryOperator *BinOp = nullptr;
9252 if (IsUpdateExprFound) {
9253 BinOp = dyn_cast<BinaryOperator>(First);
9254 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9255 }
9256 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9257 // { v = x; x++; }
9258 // { v = x; x--; }
9259 // { v = x; ++x; }
9260 // { v = x; --x; }
9261 // { v = x; x binop= expr; }
9262 // { v = x; x = x binop expr; }
9263 // { v = x; x = expr binop x; }
9264 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009265 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009266 llvm::FoldingSetNodeID XId, PossibleXId;
9267 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9268 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9269 IsUpdateExprFound = XId == PossibleXId;
9270 if (IsUpdateExprFound) {
9271 V = BinOp->getLHS();
9272 X = Checker.getX();
9273 E = Checker.getExpr();
9274 UE = Checker.getUpdateExpr();
9275 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009276 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009277 }
9278 }
9279 if (!IsUpdateExprFound) {
9280 IsUpdateExprFound = !Checker.checkStatement(First);
9281 BinOp = nullptr;
9282 if (IsUpdateExprFound) {
9283 BinOp = dyn_cast<BinaryOperator>(Second);
9284 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9285 }
9286 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9287 // { x++; v = x; }
9288 // { x--; v = x; }
9289 // { ++x; v = x; }
9290 // { --x; v = x; }
9291 // { x binop= expr; v = x; }
9292 // { x = x binop expr; v = x; }
9293 // { x = expr binop x; v = x; }
9294 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009295 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009296 llvm::FoldingSetNodeID XId, PossibleXId;
9297 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9298 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9299 IsUpdateExprFound = XId == PossibleXId;
9300 if (IsUpdateExprFound) {
9301 V = BinOp->getLHS();
9302 X = Checker.getX();
9303 E = Checker.getExpr();
9304 UE = Checker.getUpdateExpr();
9305 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009306 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009307 }
9308 }
9309 }
9310 if (!IsUpdateExprFound) {
9311 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009312 auto *FirstExpr = dyn_cast<Expr>(First);
9313 auto *SecondExpr = dyn_cast<Expr>(Second);
9314 if (!FirstExpr || !SecondExpr ||
9315 !(FirstExpr->isInstantiationDependent() ||
9316 SecondExpr->isInstantiationDependent())) {
9317 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9318 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009319 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009320 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009321 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009322 NoteRange = ErrorRange = FirstBinOp
9323 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009324 : SourceRange(ErrorLoc, ErrorLoc);
9325 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009326 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9327 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9328 ErrorFound = NotAnAssignmentOp;
9329 NoteLoc = ErrorLoc = SecondBinOp
9330 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009331 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009332 NoteRange = ErrorRange =
9333 SecondBinOp ? SecondBinOp->getSourceRange()
9334 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009335 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009336 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009337 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009338 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009339 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9340 llvm::FoldingSetNodeID X1Id, X2Id;
9341 PossibleXRHSInFirst->Profile(X1Id, Context,
9342 /*Canonical=*/true);
9343 PossibleXLHSInSecond->Profile(X2Id, Context,
9344 /*Canonical=*/true);
9345 IsUpdateExprFound = X1Id == X2Id;
9346 if (IsUpdateExprFound) {
9347 V = FirstBinOp->getLHS();
9348 X = SecondBinOp->getLHS();
9349 E = SecondBinOp->getRHS();
9350 UE = nullptr;
9351 IsXLHSInRHSPart = false;
9352 IsPostfixUpdate = true;
9353 } else {
9354 ErrorFound = NotASpecificExpression;
9355 ErrorLoc = FirstBinOp->getExprLoc();
9356 ErrorRange = FirstBinOp->getSourceRange();
9357 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9358 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9359 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009360 }
9361 }
9362 }
9363 }
9364 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009365 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009366 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009367 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009368 ErrorFound = NotTwoSubstatements;
9369 }
9370 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009371 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009372 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009373 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009374 ErrorFound = NotACompoundStatement;
9375 }
9376 if (ErrorFound != NoError) {
9377 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9378 << ErrorRange;
9379 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9380 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009381 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009382 if (CurContext->isDependentContext())
9383 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009384 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009385 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009386
Reid Kleckner87a31802018-03-12 21:43:02 +00009387 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009388
Alexey Bataev62cec442014-11-18 10:14:22 +00009389 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009390 X, V, E, UE, IsXLHSInRHSPart,
9391 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009392}
9393
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009394StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9395 Stmt *AStmt,
9396 SourceLocation StartLoc,
9397 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009398 if (!AStmt)
9399 return StmtError();
9400
Alexey Bataeve3727102018-04-18 15:57:46 +00009401 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009402 // 1.2.2 OpenMP Language Terminology
9403 // Structured block - An executable statement with a single entry at the
9404 // top and a single exit at the bottom.
9405 // The point of exit cannot be a branch out of the structured block.
9406 // longjmp() and throw() must not violate the entry/exit criteria.
9407 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009408 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9409 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9410 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9411 // 1.2.2 OpenMP Language Terminology
9412 // Structured block - An executable statement with a single entry at the
9413 // top and a single exit at the bottom.
9414 // The point of exit cannot be a branch out of the structured block.
9415 // longjmp() and throw() must not violate the entry/exit criteria.
9416 CS->getCapturedDecl()->setNothrow();
9417 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009418
Alexey Bataev13314bf2014-10-09 04:18:56 +00009419 // OpenMP [2.16, Nesting of Regions]
9420 // If specified, a teams construct must be contained within a target
9421 // construct. That target construct must contain no statements or directives
9422 // outside of the teams construct.
9423 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009424 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009425 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009426 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009427 auto I = CS->body_begin();
9428 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009429 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009430 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9431 OMPTeamsFound) {
9432
Alexey Bataev13314bf2014-10-09 04:18:56 +00009433 OMPTeamsFound = false;
9434 break;
9435 }
9436 ++I;
9437 }
9438 assert(I != CS->body_end() && "Not found statement");
9439 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009440 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009441 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009442 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009443 }
9444 if (!OMPTeamsFound) {
9445 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9446 Diag(DSAStack->getInnerTeamsRegionLoc(),
9447 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009448 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009449 << isa<OMPExecutableDirective>(S);
9450 return StmtError();
9451 }
9452 }
9453
Reid Kleckner87a31802018-03-12 21:43:02 +00009454 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009455
9456 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9457}
9458
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009459StmtResult
9460Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9461 Stmt *AStmt, SourceLocation StartLoc,
9462 SourceLocation EndLoc) {
9463 if (!AStmt)
9464 return StmtError();
9465
Alexey Bataeve3727102018-04-18 15:57:46 +00009466 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009467 // 1.2.2 OpenMP Language Terminology
9468 // Structured block - An executable statement with a single entry at the
9469 // top and a single exit at the bottom.
9470 // The point of exit cannot be a branch out of the structured block.
9471 // longjmp() and throw() must not violate the entry/exit criteria.
9472 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009473 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9474 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9475 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9476 // 1.2.2 OpenMP Language Terminology
9477 // Structured block - An executable statement with a single entry at the
9478 // top and a single exit at the bottom.
9479 // The point of exit cannot be a branch out of the structured block.
9480 // longjmp() and throw() must not violate the entry/exit criteria.
9481 CS->getCapturedDecl()->setNothrow();
9482 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009483
Reid Kleckner87a31802018-03-12 21:43:02 +00009484 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009485
9486 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9487 AStmt);
9488}
9489
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009490StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9491 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009492 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009493 if (!AStmt)
9494 return StmtError();
9495
Alexey Bataeve3727102018-04-18 15:57:46 +00009496 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009497 // 1.2.2 OpenMP Language Terminology
9498 // Structured block - An executable statement with a single entry at the
9499 // top and a single exit at the bottom.
9500 // The point of exit cannot be a branch out of the structured block.
9501 // longjmp() and throw() must not violate the entry/exit criteria.
9502 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009503 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9504 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9505 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9506 // 1.2.2 OpenMP Language Terminology
9507 // Structured block - An executable statement with a single entry at the
9508 // top and a single exit at the bottom.
9509 // The point of exit cannot be a branch out of the structured block.
9510 // longjmp() and throw() must not violate the entry/exit criteria.
9511 CS->getCapturedDecl()->setNothrow();
9512 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009513
9514 OMPLoopDirective::HelperExprs B;
9515 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9516 // define the nested loops number.
9517 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009518 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009519 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009520 VarsWithImplicitDSA, B);
9521 if (NestedLoopCount == 0)
9522 return StmtError();
9523
9524 assert((CurContext->isDependentContext() || B.builtAll()) &&
9525 "omp target parallel for loop exprs were not built");
9526
9527 if (!CurContext->isDependentContext()) {
9528 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009529 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009530 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009531 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009532 B.NumIterations, *this, CurScope,
9533 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009534 return StmtError();
9535 }
9536 }
9537
Reid Kleckner87a31802018-03-12 21:43:02 +00009538 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009539 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9540 NestedLoopCount, Clauses, AStmt,
9541 B, DSAStack->isCancelRegion());
9542}
9543
Alexey Bataev95b64a92017-05-30 16:00:04 +00009544/// Check for existence of a map clause in the list of clauses.
9545static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9546 const OpenMPClauseKind K) {
9547 return llvm::any_of(
9548 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9549}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009550
Alexey Bataev95b64a92017-05-30 16:00:04 +00009551template <typename... Params>
9552static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9553 const Params... ClauseTypes) {
9554 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009555}
9556
Michael Wong65f367f2015-07-21 13:44:28 +00009557StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9558 Stmt *AStmt,
9559 SourceLocation StartLoc,
9560 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009561 if (!AStmt)
9562 return StmtError();
9563
9564 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9565
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009566 // OpenMP [2.10.1, Restrictions, p. 97]
9567 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009568 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9569 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9570 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009571 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009572 return StmtError();
9573 }
9574
Reid Kleckner87a31802018-03-12 21:43:02 +00009575 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009576
9577 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9578 AStmt);
9579}
9580
Samuel Antaodf67fc42016-01-19 19:15:56 +00009581StmtResult
9582Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9583 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009584 SourceLocation EndLoc, Stmt *AStmt) {
9585 if (!AStmt)
9586 return StmtError();
9587
Alexey Bataeve3727102018-04-18 15:57:46 +00009588 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009589 // 1.2.2 OpenMP Language Terminology
9590 // Structured block - An executable statement with a single entry at the
9591 // top and a single exit at the bottom.
9592 // The point of exit cannot be a branch out of the structured block.
9593 // longjmp() and throw() must not violate the entry/exit criteria.
9594 CS->getCapturedDecl()->setNothrow();
9595 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9596 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9597 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9598 // 1.2.2 OpenMP Language Terminology
9599 // Structured block - An executable statement with a single entry at the
9600 // top and a single exit at the bottom.
9601 // The point of exit cannot be a branch out of the structured block.
9602 // longjmp() and throw() must not violate the entry/exit criteria.
9603 CS->getCapturedDecl()->setNothrow();
9604 }
9605
Samuel Antaodf67fc42016-01-19 19:15:56 +00009606 // OpenMP [2.10.2, Restrictions, p. 99]
9607 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009608 if (!hasClauses(Clauses, OMPC_map)) {
9609 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9610 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009611 return StmtError();
9612 }
9613
Alexey Bataev7828b252017-11-21 17:08:48 +00009614 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9615 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009616}
9617
Samuel Antao72590762016-01-19 20:04:50 +00009618StmtResult
9619Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9620 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009621 SourceLocation EndLoc, Stmt *AStmt) {
9622 if (!AStmt)
9623 return StmtError();
9624
Alexey Bataeve3727102018-04-18 15:57:46 +00009625 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009626 // 1.2.2 OpenMP Language Terminology
9627 // Structured block - An executable statement with a single entry at the
9628 // top and a single exit at the bottom.
9629 // The point of exit cannot be a branch out of the structured block.
9630 // longjmp() and throw() must not violate the entry/exit criteria.
9631 CS->getCapturedDecl()->setNothrow();
9632 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9633 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9634 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9635 // 1.2.2 OpenMP Language Terminology
9636 // Structured block - An executable statement with a single entry at the
9637 // top and a single exit at the bottom.
9638 // The point of exit cannot be a branch out of the structured block.
9639 // longjmp() and throw() must not violate the entry/exit criteria.
9640 CS->getCapturedDecl()->setNothrow();
9641 }
9642
Samuel Antao72590762016-01-19 20:04:50 +00009643 // OpenMP [2.10.3, Restrictions, p. 102]
9644 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009645 if (!hasClauses(Clauses, OMPC_map)) {
9646 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9647 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009648 return StmtError();
9649 }
9650
Alexey Bataev7828b252017-11-21 17:08:48 +00009651 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9652 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009653}
9654
Samuel Antao686c70c2016-05-26 17:30:50 +00009655StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9656 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009657 SourceLocation EndLoc,
9658 Stmt *AStmt) {
9659 if (!AStmt)
9660 return StmtError();
9661
Alexey Bataeve3727102018-04-18 15:57:46 +00009662 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009663 // 1.2.2 OpenMP Language Terminology
9664 // Structured block - An executable statement with a single entry at the
9665 // top and a single exit at the bottom.
9666 // The point of exit cannot be a branch out of the structured block.
9667 // longjmp() and throw() must not violate the entry/exit criteria.
9668 CS->getCapturedDecl()->setNothrow();
9669 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9670 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9671 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9672 // 1.2.2 OpenMP Language Terminology
9673 // Structured block - An executable statement with a single entry at the
9674 // top and a single exit at the bottom.
9675 // The point of exit cannot be a branch out of the structured block.
9676 // longjmp() and throw() must not violate the entry/exit criteria.
9677 CS->getCapturedDecl()->setNothrow();
9678 }
9679
Alexey Bataev95b64a92017-05-30 16:00:04 +00009680 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009681 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9682 return StmtError();
9683 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009684 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9685 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009686}
9687
Alexey Bataev13314bf2014-10-09 04:18:56 +00009688StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9689 Stmt *AStmt, SourceLocation StartLoc,
9690 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009691 if (!AStmt)
9692 return StmtError();
9693
Alexey Bataeve3727102018-04-18 15:57:46 +00009694 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009695 // 1.2.2 OpenMP Language Terminology
9696 // Structured block - An executable statement with a single entry at the
9697 // top and a single exit at the bottom.
9698 // The point of exit cannot be a branch out of the structured block.
9699 // longjmp() and throw() must not violate the entry/exit criteria.
9700 CS->getCapturedDecl()->setNothrow();
9701
Reid Kleckner87a31802018-03-12 21:43:02 +00009702 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009703
Alexey Bataevceabd412017-11-30 18:01:54 +00009704 DSAStack->setParentTeamsRegionLoc(StartLoc);
9705
Alexey Bataev13314bf2014-10-09 04:18:56 +00009706 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9707}
9708
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009709StmtResult
9710Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9711 SourceLocation EndLoc,
9712 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009713 if (DSAStack->isParentNowaitRegion()) {
9714 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9715 return StmtError();
9716 }
9717 if (DSAStack->isParentOrderedRegion()) {
9718 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9719 return StmtError();
9720 }
9721 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9722 CancelRegion);
9723}
9724
Alexey Bataev87933c72015-09-18 08:07:34 +00009725StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9726 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009727 SourceLocation EndLoc,
9728 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009729 if (DSAStack->isParentNowaitRegion()) {
9730 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9731 return StmtError();
9732 }
9733 if (DSAStack->isParentOrderedRegion()) {
9734 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9735 return StmtError();
9736 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009737 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009738 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9739 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009740}
9741
Alexey Bataev382967a2015-12-08 12:06:20 +00009742static bool checkGrainsizeNumTasksClauses(Sema &S,
9743 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009744 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009745 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009746 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009747 if (C->getClauseKind() == OMPC_grainsize ||
9748 C->getClauseKind() == OMPC_num_tasks) {
9749 if (!PrevClause)
9750 PrevClause = C;
9751 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009752 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009753 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9754 << getOpenMPClauseName(C->getClauseKind())
9755 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009756 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009757 diag::note_omp_previous_grainsize_num_tasks)
9758 << getOpenMPClauseName(PrevClause->getClauseKind());
9759 ErrorFound = true;
9760 }
9761 }
9762 }
9763 return ErrorFound;
9764}
9765
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009766static bool checkReductionClauseWithNogroup(Sema &S,
9767 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009768 const OMPClause *ReductionClause = nullptr;
9769 const OMPClause *NogroupClause = nullptr;
9770 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009771 if (C->getClauseKind() == OMPC_reduction) {
9772 ReductionClause = C;
9773 if (NogroupClause)
9774 break;
9775 continue;
9776 }
9777 if (C->getClauseKind() == OMPC_nogroup) {
9778 NogroupClause = C;
9779 if (ReductionClause)
9780 break;
9781 continue;
9782 }
9783 }
9784 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009785 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9786 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009787 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009788 return true;
9789 }
9790 return false;
9791}
9792
Alexey Bataev49f6e782015-12-01 04:18:41 +00009793StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9794 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009795 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009796 if (!AStmt)
9797 return StmtError();
9798
9799 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9800 OMPLoopDirective::HelperExprs B;
9801 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9802 // define the nested loops number.
9803 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009804 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009805 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009806 VarsWithImplicitDSA, B);
9807 if (NestedLoopCount == 0)
9808 return StmtError();
9809
9810 assert((CurContext->isDependentContext() || B.builtAll()) &&
9811 "omp for loop exprs were not built");
9812
Alexey Bataev382967a2015-12-08 12:06:20 +00009813 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9814 // The grainsize clause and num_tasks clause are mutually exclusive and may
9815 // not appear on the same taskloop directive.
9816 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9817 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009818 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9819 // If a reduction clause is present on the taskloop directive, the nogroup
9820 // clause must not be specified.
9821 if (checkReductionClauseWithNogroup(*this, Clauses))
9822 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009823
Reid Kleckner87a31802018-03-12 21:43:02 +00009824 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009825 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataeve0ca4792020-02-12 16:12:53 -05009826 NestedLoopCount, Clauses, AStmt, B,
9827 DSAStack->isCancelRegion());
Alexey Bataev49f6e782015-12-01 04:18:41 +00009828}
9829
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009830StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9831 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009832 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009833 if (!AStmt)
9834 return StmtError();
9835
9836 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9837 OMPLoopDirective::HelperExprs B;
9838 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9839 // define the nested loops number.
9840 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009841 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009842 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9843 VarsWithImplicitDSA, B);
9844 if (NestedLoopCount == 0)
9845 return StmtError();
9846
9847 assert((CurContext->isDependentContext() || B.builtAll()) &&
9848 "omp for loop exprs were not built");
9849
Alexey Bataev5a3af132016-03-29 08:58:54 +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) {
David Majnemer9d168222016-08-05 17:44:54 +00009853 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009854 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009855 B.NumIterations, *this, CurScope,
9856 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009857 return StmtError();
9858 }
9859 }
9860
Alexey Bataev382967a2015-12-08 12:06:20 +00009861 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9862 // The grainsize clause and num_tasks clause are mutually exclusive and may
9863 // not appear on the same taskloop directive.
9864 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9865 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009866 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9867 // If a reduction clause is present on the taskloop directive, the nogroup
9868 // clause must not be specified.
9869 if (checkReductionClauseWithNogroup(*this, Clauses))
9870 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009871 if (checkSimdlenSafelenSpecified(*this, Clauses))
9872 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009873
Reid Kleckner87a31802018-03-12 21:43:02 +00009874 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009875 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9876 NestedLoopCount, Clauses, AStmt, B);
9877}
9878
Alexey Bataev60e51c42019-10-10 20:13:02 +00009879StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9880 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9881 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9882 if (!AStmt)
9883 return StmtError();
9884
9885 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9886 OMPLoopDirective::HelperExprs B;
9887 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9888 // define the nested loops number.
9889 unsigned NestedLoopCount =
9890 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9891 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9892 VarsWithImplicitDSA, B);
9893 if (NestedLoopCount == 0)
9894 return StmtError();
9895
9896 assert((CurContext->isDependentContext() || B.builtAll()) &&
9897 "omp for loop exprs were not built");
9898
9899 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9900 // The grainsize clause and num_tasks clause are mutually exclusive and may
9901 // not appear on the same taskloop directive.
9902 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9903 return StmtError();
9904 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9905 // If a reduction clause is present on the taskloop directive, the nogroup
9906 // clause must not be specified.
9907 if (checkReductionClauseWithNogroup(*this, Clauses))
9908 return StmtError();
9909
9910 setFunctionHasBranchProtectedScope();
9911 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataeve0ca4792020-02-12 16:12:53 -05009912 NestedLoopCount, Clauses, AStmt, B,
9913 DSAStack->isCancelRegion());
Alexey Bataev60e51c42019-10-10 20:13:02 +00009914}
9915
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009916StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9917 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9918 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9919 if (!AStmt)
9920 return StmtError();
9921
9922 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9923 OMPLoopDirective::HelperExprs B;
9924 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9925 // define the nested loops number.
9926 unsigned NestedLoopCount =
9927 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9928 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9929 VarsWithImplicitDSA, B);
9930 if (NestedLoopCount == 0)
9931 return StmtError();
9932
9933 assert((CurContext->isDependentContext() || B.builtAll()) &&
9934 "omp for loop exprs were not built");
9935
9936 if (!CurContext->isDependentContext()) {
9937 // Finalize the clauses that need pre-built expressions for CodeGen.
9938 for (OMPClause *C : Clauses) {
9939 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9940 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9941 B.NumIterations, *this, CurScope,
9942 DSAStack))
9943 return StmtError();
9944 }
9945 }
9946
9947 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9948 // The grainsize clause and num_tasks clause are mutually exclusive and may
9949 // not appear on the same taskloop directive.
9950 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9951 return StmtError();
9952 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9953 // If a reduction clause is present on the taskloop directive, the nogroup
9954 // clause must not be specified.
9955 if (checkReductionClauseWithNogroup(*this, Clauses))
9956 return StmtError();
9957 if (checkSimdlenSafelenSpecified(*this, Clauses))
9958 return StmtError();
9959
9960 setFunctionHasBranchProtectedScope();
9961 return OMPMasterTaskLoopSimdDirective::Create(
9962 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9963}
9964
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009965StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9966 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9967 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9968 if (!AStmt)
9969 return StmtError();
9970
9971 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9972 auto *CS = cast<CapturedStmt>(AStmt);
9973 // 1.2.2 OpenMP Language Terminology
9974 // Structured block - An executable statement with a single entry at the
9975 // top and a single exit at the bottom.
9976 // The point of exit cannot be a branch out of the structured block.
9977 // longjmp() and throw() must not violate the entry/exit criteria.
9978 CS->getCapturedDecl()->setNothrow();
9979 for (int ThisCaptureLevel =
9980 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9981 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9982 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9983 // 1.2.2 OpenMP Language Terminology
9984 // Structured block - An executable statement with a single entry at the
9985 // top and a single exit at the bottom.
9986 // The point of exit cannot be a branch out of the structured block.
9987 // longjmp() and throw() must not violate the entry/exit criteria.
9988 CS->getCapturedDecl()->setNothrow();
9989 }
9990
9991 OMPLoopDirective::HelperExprs B;
9992 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9993 // define the nested loops number.
9994 unsigned NestedLoopCount = checkOpenMPLoop(
9995 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9996 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9997 VarsWithImplicitDSA, B);
9998 if (NestedLoopCount == 0)
9999 return StmtError();
10000
10001 assert((CurContext->isDependentContext() || B.builtAll()) &&
10002 "omp for loop exprs were not built");
10003
10004 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10005 // The grainsize clause and num_tasks clause are mutually exclusive and may
10006 // not appear on the same taskloop directive.
10007 if (checkGrainsizeNumTasksClauses(*this, Clauses))
10008 return StmtError();
10009 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10010 // If a reduction clause is present on the taskloop directive, the nogroup
10011 // clause must not be specified.
10012 if (checkReductionClauseWithNogroup(*this, Clauses))
10013 return StmtError();
10014
10015 setFunctionHasBranchProtectedScope();
10016 return OMPParallelMasterTaskLoopDirective::Create(
Alexey Bataeve0ca4792020-02-12 16:12:53 -050010017 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10018 DSAStack->isCancelRegion());
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010019}
10020
Alexey Bataev14a388f2019-10-25 10:27:13 -040010021StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10022 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10023 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10024 if (!AStmt)
10025 return StmtError();
10026
10027 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10028 auto *CS = cast<CapturedStmt>(AStmt);
10029 // 1.2.2 OpenMP Language Terminology
10030 // Structured block - An executable statement with a single entry at the
10031 // top and a single exit at the bottom.
10032 // The point of exit cannot be a branch out of the structured block.
10033 // longjmp() and throw() must not violate the entry/exit criteria.
10034 CS->getCapturedDecl()->setNothrow();
10035 for (int ThisCaptureLevel =
10036 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
10037 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10038 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10039 // 1.2.2 OpenMP Language Terminology
10040 // Structured block - An executable statement with a single entry at the
10041 // top and a single exit at the bottom.
10042 // The point of exit cannot be a branch out of the structured block.
10043 // longjmp() and throw() must not violate the entry/exit criteria.
10044 CS->getCapturedDecl()->setNothrow();
10045 }
10046
10047 OMPLoopDirective::HelperExprs B;
10048 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10049 // define the nested loops number.
10050 unsigned NestedLoopCount = checkOpenMPLoop(
10051 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
10052 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10053 VarsWithImplicitDSA, B);
10054 if (NestedLoopCount == 0)
10055 return StmtError();
10056
10057 assert((CurContext->isDependentContext() || B.builtAll()) &&
10058 "omp for loop exprs were not built");
10059
10060 if (!CurContext->isDependentContext()) {
10061 // Finalize the clauses that need pre-built expressions for CodeGen.
10062 for (OMPClause *C : Clauses) {
10063 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10064 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10065 B.NumIterations, *this, CurScope,
10066 DSAStack))
10067 return StmtError();
10068 }
10069 }
10070
10071 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10072 // The grainsize clause and num_tasks clause are mutually exclusive and may
10073 // not appear on the same taskloop directive.
10074 if (checkGrainsizeNumTasksClauses(*this, Clauses))
10075 return StmtError();
10076 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10077 // If a reduction clause is present on the taskloop directive, the nogroup
10078 // clause must not be specified.
10079 if (checkReductionClauseWithNogroup(*this, Clauses))
10080 return StmtError();
10081 if (checkSimdlenSafelenSpecified(*this, Clauses))
10082 return StmtError();
10083
10084 setFunctionHasBranchProtectedScope();
10085 return OMPParallelMasterTaskLoopSimdDirective::Create(
10086 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10087}
10088
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010089StmtResult Sema::ActOnOpenMPDistributeDirective(
10090 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010091 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010092 if (!AStmt)
10093 return StmtError();
10094
10095 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10096 OMPLoopDirective::HelperExprs B;
10097 // In presence of clause 'collapse' with number of loops, it will
10098 // define the nested loops number.
10099 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010100 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010101 nullptr /*ordered not a clause on distribute*/, AStmt,
10102 *this, *DSAStack, VarsWithImplicitDSA, B);
10103 if (NestedLoopCount == 0)
10104 return StmtError();
10105
10106 assert((CurContext->isDependentContext() || B.builtAll()) &&
10107 "omp for loop exprs were not built");
10108
Reid Kleckner87a31802018-03-12 21:43:02 +000010109 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010110 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
10111 NestedLoopCount, Clauses, AStmt, B);
10112}
10113
Carlo Bertolli9925f152016-06-27 14:55:37 +000010114StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
10115 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010116 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +000010117 if (!AStmt)
10118 return StmtError();
10119
Alexey Bataeve3727102018-04-18 15:57:46 +000010120 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +000010121 // 1.2.2 OpenMP Language Terminology
10122 // Structured block - An executable statement with a single entry at the
10123 // top and a single exit at the bottom.
10124 // The point of exit cannot be a branch out of the structured block.
10125 // longjmp() and throw() must not violate the entry/exit criteria.
10126 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +000010127 for (int ThisCaptureLevel =
10128 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
10129 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10130 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10131 // 1.2.2 OpenMP Language Terminology
10132 // Structured block - An executable statement with a single entry at the
10133 // top and a single exit at the bottom.
10134 // The point of exit cannot be a branch out of the structured block.
10135 // longjmp() and throw() must not violate the entry/exit criteria.
10136 CS->getCapturedDecl()->setNothrow();
10137 }
Carlo Bertolli9925f152016-06-27 14:55:37 +000010138
10139 OMPLoopDirective::HelperExprs B;
10140 // In presence of clause 'collapse' with number of loops, it will
10141 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010142 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +000010143 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +000010144 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +000010145 VarsWithImplicitDSA, B);
10146 if (NestedLoopCount == 0)
10147 return StmtError();
10148
10149 assert((CurContext->isDependentContext() || B.builtAll()) &&
10150 "omp for loop exprs were not built");
10151
Reid Kleckner87a31802018-03-12 21:43:02 +000010152 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +000010153 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010154 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10155 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +000010156}
10157
Kelvin Li4a39add2016-07-05 05:00:15 +000010158StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
10159 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010160 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +000010161 if (!AStmt)
10162 return StmtError();
10163
Alexey Bataeve3727102018-04-18 15:57:46 +000010164 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +000010165 // 1.2.2 OpenMP Language Terminology
10166 // Structured block - An executable statement with a single entry at the
10167 // top and a single exit at the bottom.
10168 // The point of exit cannot be a branch out of the structured block.
10169 // longjmp() and throw() must not violate the entry/exit criteria.
10170 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +000010171 for (int ThisCaptureLevel =
10172 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
10173 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10174 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10175 // 1.2.2 OpenMP Language Terminology
10176 // Structured block - An executable statement with a single entry at the
10177 // top and a single exit at the bottom.
10178 // The point of exit cannot be a branch out of the structured block.
10179 // longjmp() and throw() must not violate the entry/exit criteria.
10180 CS->getCapturedDecl()->setNothrow();
10181 }
Kelvin Li4a39add2016-07-05 05:00:15 +000010182
10183 OMPLoopDirective::HelperExprs B;
10184 // In presence of clause 'collapse' with number of loops, it will
10185 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010186 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +000010187 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +000010188 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +000010189 VarsWithImplicitDSA, B);
10190 if (NestedLoopCount == 0)
10191 return StmtError();
10192
10193 assert((CurContext->isDependentContext() || B.builtAll()) &&
10194 "omp for loop exprs were not built");
10195
Alexey Bataev438388c2017-11-22 18:34:02 +000010196 if (!CurContext->isDependentContext()) {
10197 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010198 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010199 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10200 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10201 B.NumIterations, *this, CurScope,
10202 DSAStack))
10203 return StmtError();
10204 }
10205 }
10206
Kelvin Lic5609492016-07-15 04:39:07 +000010207 if (checkSimdlenSafelenSpecified(*this, Clauses))
10208 return StmtError();
10209
Reid Kleckner87a31802018-03-12 21:43:02 +000010210 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +000010211 return OMPDistributeParallelForSimdDirective::Create(
10212 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10213}
10214
Kelvin Li787f3fc2016-07-06 04:45:38 +000010215StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10216 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010217 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +000010218 if (!AStmt)
10219 return StmtError();
10220
Alexey Bataeve3727102018-04-18 15:57:46 +000010221 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010222 // 1.2.2 OpenMP Language Terminology
10223 // Structured block - An executable statement with a single entry at the
10224 // top and a single exit at the bottom.
10225 // The point of exit cannot be a branch out of the structured block.
10226 // longjmp() and throw() must not violate the entry/exit criteria.
10227 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +000010228 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10229 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10230 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10231 // 1.2.2 OpenMP Language Terminology
10232 // Structured block - An executable statement with a single entry at the
10233 // top and a single exit at the bottom.
10234 // The point of exit cannot be a branch out of the structured block.
10235 // longjmp() and throw() must not violate the entry/exit criteria.
10236 CS->getCapturedDecl()->setNothrow();
10237 }
Kelvin Li787f3fc2016-07-06 04:45:38 +000010238
10239 OMPLoopDirective::HelperExprs B;
10240 // In presence of clause 'collapse' with number of loops, it will
10241 // define the nested loops number.
10242 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010243 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +000010244 nullptr /*ordered not a clause on distribute*/, CS, *this,
10245 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010246 if (NestedLoopCount == 0)
10247 return StmtError();
10248
10249 assert((CurContext->isDependentContext() || B.builtAll()) &&
10250 "omp for loop exprs were not built");
10251
Alexey Bataev438388c2017-11-22 18:34:02 +000010252 if (!CurContext->isDependentContext()) {
10253 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010254 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010255 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10256 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10257 B.NumIterations, *this, CurScope,
10258 DSAStack))
10259 return StmtError();
10260 }
10261 }
10262
Kelvin Lic5609492016-07-15 04:39:07 +000010263 if (checkSimdlenSafelenSpecified(*this, Clauses))
10264 return StmtError();
10265
Reid Kleckner87a31802018-03-12 21:43:02 +000010266 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +000010267 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
10268 NestedLoopCount, Clauses, AStmt, B);
10269}
10270
Kelvin Lia579b912016-07-14 02:54:56 +000010271StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
10272 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010273 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +000010274 if (!AStmt)
10275 return StmtError();
10276
Alexey Bataeve3727102018-04-18 15:57:46 +000010277 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +000010278 // 1.2.2 OpenMP Language Terminology
10279 // Structured block - An executable statement with a single entry at the
10280 // top and a single exit at the bottom.
10281 // The point of exit cannot be a branch out of the structured block.
10282 // longjmp() and throw() must not violate the entry/exit criteria.
10283 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010284 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10285 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10286 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10287 // 1.2.2 OpenMP Language Terminology
10288 // Structured block - An executable statement with a single entry at the
10289 // top and a single exit at the bottom.
10290 // The point of exit cannot be a branch out of the structured block.
10291 // longjmp() and throw() must not violate the entry/exit criteria.
10292 CS->getCapturedDecl()->setNothrow();
10293 }
Kelvin Lia579b912016-07-14 02:54:56 +000010294
10295 OMPLoopDirective::HelperExprs B;
10296 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10297 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010298 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010299 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010300 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010301 VarsWithImplicitDSA, B);
10302 if (NestedLoopCount == 0)
10303 return StmtError();
10304
10305 assert((CurContext->isDependentContext() || B.builtAll()) &&
10306 "omp target parallel for simd loop exprs were not built");
10307
10308 if (!CurContext->isDependentContext()) {
10309 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010310 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010311 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010312 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10313 B.NumIterations, *this, CurScope,
10314 DSAStack))
10315 return StmtError();
10316 }
10317 }
Kelvin Lic5609492016-07-15 04:39:07 +000010318 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010319 return StmtError();
10320
Reid Kleckner87a31802018-03-12 21:43:02 +000010321 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010322 return OMPTargetParallelForSimdDirective::Create(
10323 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10324}
10325
Kelvin Li986330c2016-07-20 22:57:10 +000010326StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10327 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010328 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010329 if (!AStmt)
10330 return StmtError();
10331
Alexey Bataeve3727102018-04-18 15:57:46 +000010332 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010333 // 1.2.2 OpenMP Language Terminology
10334 // Structured block - An executable statement with a single entry at the
10335 // top and a single exit at the bottom.
10336 // The point of exit cannot be a branch out of the structured block.
10337 // longjmp() and throw() must not violate the entry/exit criteria.
10338 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010339 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10340 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10341 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10342 // 1.2.2 OpenMP Language Terminology
10343 // Structured block - An executable statement with a single entry at the
10344 // top and a single exit at the bottom.
10345 // The point of exit cannot be a branch out of the structured block.
10346 // longjmp() and throw() must not violate the entry/exit criteria.
10347 CS->getCapturedDecl()->setNothrow();
10348 }
10349
Kelvin Li986330c2016-07-20 22:57:10 +000010350 OMPLoopDirective::HelperExprs B;
10351 // In presence of clause 'collapse' with number of loops, it will define the
10352 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010353 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010354 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010355 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010356 VarsWithImplicitDSA, B);
10357 if (NestedLoopCount == 0)
10358 return StmtError();
10359
10360 assert((CurContext->isDependentContext() || B.builtAll()) &&
10361 "omp target simd loop exprs were not built");
10362
10363 if (!CurContext->isDependentContext()) {
10364 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010365 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010366 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010367 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10368 B.NumIterations, *this, CurScope,
10369 DSAStack))
10370 return StmtError();
10371 }
10372 }
10373
10374 if (checkSimdlenSafelenSpecified(*this, Clauses))
10375 return StmtError();
10376
Reid Kleckner87a31802018-03-12 21:43:02 +000010377 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010378 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10379 NestedLoopCount, Clauses, AStmt, B);
10380}
10381
Kelvin Li02532872016-08-05 14:37:37 +000010382StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10383 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010384 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010385 if (!AStmt)
10386 return StmtError();
10387
Alexey Bataeve3727102018-04-18 15:57:46 +000010388 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +000010389 // 1.2.2 OpenMP Language Terminology
10390 // Structured block - An executable statement with a single entry at the
10391 // top and a single exit at the bottom.
10392 // The point of exit cannot be a branch out of the structured block.
10393 // longjmp() and throw() must not violate the entry/exit criteria.
10394 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010395 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10396 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10397 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10398 // 1.2.2 OpenMP Language Terminology
10399 // Structured block - An executable statement with a single entry at the
10400 // top and a single exit at the bottom.
10401 // The point of exit cannot be a branch out of the structured block.
10402 // longjmp() and throw() must not violate the entry/exit criteria.
10403 CS->getCapturedDecl()->setNothrow();
10404 }
Kelvin Li02532872016-08-05 14:37:37 +000010405
10406 OMPLoopDirective::HelperExprs B;
10407 // In presence of clause 'collapse' with number of loops, it will
10408 // define the nested loops number.
10409 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010410 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010411 nullptr /*ordered not a clause on distribute*/, CS, *this,
10412 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010413 if (NestedLoopCount == 0)
10414 return StmtError();
10415
10416 assert((CurContext->isDependentContext() || B.builtAll()) &&
10417 "omp teams distribute loop exprs were not built");
10418
Reid Kleckner87a31802018-03-12 21:43:02 +000010419 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010420
10421 DSAStack->setParentTeamsRegionLoc(StartLoc);
10422
David Majnemer9d168222016-08-05 17:44:54 +000010423 return OMPTeamsDistributeDirective::Create(
10424 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010425}
10426
Kelvin Li4e325f72016-10-25 12:50:55 +000010427StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10428 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010429 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010430 if (!AStmt)
10431 return StmtError();
10432
Alexey Bataeve3727102018-04-18 15:57:46 +000010433 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010434 // 1.2.2 OpenMP Language Terminology
10435 // Structured block - An executable statement with a single entry at the
10436 // top and a single exit at the bottom.
10437 // The point of exit cannot be a branch out of the structured block.
10438 // longjmp() and throw() must not violate the entry/exit criteria.
10439 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010440 for (int ThisCaptureLevel =
10441 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10442 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10443 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10444 // 1.2.2 OpenMP Language Terminology
10445 // Structured block - An executable statement with a single entry at the
10446 // top and a single exit at the bottom.
10447 // The point of exit cannot be a branch out of the structured block.
10448 // longjmp() and throw() must not violate the entry/exit criteria.
10449 CS->getCapturedDecl()->setNothrow();
10450 }
10451
Kelvin Li4e325f72016-10-25 12:50:55 +000010452 OMPLoopDirective::HelperExprs B;
10453 // In presence of clause 'collapse' with number of loops, it will
10454 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010455 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010456 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010457 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010458 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010459
10460 if (NestedLoopCount == 0)
10461 return StmtError();
10462
10463 assert((CurContext->isDependentContext() || B.builtAll()) &&
10464 "omp teams distribute simd loop exprs were not built");
10465
10466 if (!CurContext->isDependentContext()) {
10467 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010468 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010469 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10470 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10471 B.NumIterations, *this, CurScope,
10472 DSAStack))
10473 return StmtError();
10474 }
10475 }
10476
10477 if (checkSimdlenSafelenSpecified(*this, Clauses))
10478 return StmtError();
10479
Reid Kleckner87a31802018-03-12 21:43:02 +000010480 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010481
10482 DSAStack->setParentTeamsRegionLoc(StartLoc);
10483
Kelvin Li4e325f72016-10-25 12:50:55 +000010484 return OMPTeamsDistributeSimdDirective::Create(
10485 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10486}
10487
Kelvin Li579e41c2016-11-30 23:51:03 +000010488StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10489 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010490 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010491 if (!AStmt)
10492 return StmtError();
10493
Alexey Bataeve3727102018-04-18 15:57:46 +000010494 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010495 // 1.2.2 OpenMP Language Terminology
10496 // Structured block - An executable statement with a single entry at the
10497 // top and a single exit at the bottom.
10498 // The point of exit cannot be a branch out of the structured block.
10499 // longjmp() and throw() must not violate the entry/exit criteria.
10500 CS->getCapturedDecl()->setNothrow();
10501
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010502 for (int ThisCaptureLevel =
10503 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10504 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10505 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10506 // 1.2.2 OpenMP Language Terminology
10507 // Structured block - An executable statement with a single entry at the
10508 // top and a single exit at the bottom.
10509 // The point of exit cannot be a branch out of the structured block.
10510 // longjmp() and throw() must not violate the entry/exit criteria.
10511 CS->getCapturedDecl()->setNothrow();
10512 }
10513
Kelvin Li579e41c2016-11-30 23:51:03 +000010514 OMPLoopDirective::HelperExprs B;
10515 // In presence of clause 'collapse' with number of loops, it will
10516 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010517 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010518 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010519 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010520 VarsWithImplicitDSA, B);
10521
10522 if (NestedLoopCount == 0)
10523 return StmtError();
10524
10525 assert((CurContext->isDependentContext() || B.builtAll()) &&
10526 "omp for loop exprs were not built");
10527
10528 if (!CurContext->isDependentContext()) {
10529 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010530 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010531 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10532 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10533 B.NumIterations, *this, CurScope,
10534 DSAStack))
10535 return StmtError();
10536 }
10537 }
10538
10539 if (checkSimdlenSafelenSpecified(*this, Clauses))
10540 return StmtError();
10541
Reid Kleckner87a31802018-03-12 21:43:02 +000010542 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010543
10544 DSAStack->setParentTeamsRegionLoc(StartLoc);
10545
Kelvin Li579e41c2016-11-30 23:51:03 +000010546 return OMPTeamsDistributeParallelForSimdDirective::Create(
10547 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10548}
10549
Kelvin Li7ade93f2016-12-09 03:24:30 +000010550StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10551 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010552 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010553 if (!AStmt)
10554 return StmtError();
10555
Alexey Bataeve3727102018-04-18 15:57:46 +000010556 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010557 // 1.2.2 OpenMP Language Terminology
10558 // Structured block - An executable statement with a single entry at the
10559 // top and a single exit at the bottom.
10560 // The point of exit cannot be a branch out of the structured block.
10561 // longjmp() and throw() must not violate the entry/exit criteria.
10562 CS->getCapturedDecl()->setNothrow();
10563
Carlo Bertolli62fae152017-11-20 20:46:39 +000010564 for (int ThisCaptureLevel =
10565 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10566 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10567 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10568 // 1.2.2 OpenMP Language Terminology
10569 // Structured block - An executable statement with a single entry at the
10570 // top and a single exit at the bottom.
10571 // The point of exit cannot be a branch out of the structured block.
10572 // longjmp() and throw() must not violate the entry/exit criteria.
10573 CS->getCapturedDecl()->setNothrow();
10574 }
10575
Kelvin Li7ade93f2016-12-09 03:24:30 +000010576 OMPLoopDirective::HelperExprs B;
10577 // In presence of clause 'collapse' with number of loops, it will
10578 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010579 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010580 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010581 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010582 VarsWithImplicitDSA, B);
10583
10584 if (NestedLoopCount == 0)
10585 return StmtError();
10586
10587 assert((CurContext->isDependentContext() || B.builtAll()) &&
10588 "omp for loop exprs were not built");
10589
Reid Kleckner87a31802018-03-12 21:43:02 +000010590 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010591
10592 DSAStack->setParentTeamsRegionLoc(StartLoc);
10593
Kelvin Li7ade93f2016-12-09 03:24:30 +000010594 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010595 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10596 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010597}
10598
Kelvin Libf594a52016-12-17 05:48:59 +000010599StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10600 Stmt *AStmt,
10601 SourceLocation StartLoc,
10602 SourceLocation EndLoc) {
10603 if (!AStmt)
10604 return StmtError();
10605
Alexey Bataeve3727102018-04-18 15:57:46 +000010606 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010607 // 1.2.2 OpenMP Language Terminology
10608 // Structured block - An executable statement with a single entry at the
10609 // top and a single exit at the bottom.
10610 // The point of exit cannot be a branch out of the structured block.
10611 // longjmp() and throw() must not violate the entry/exit criteria.
10612 CS->getCapturedDecl()->setNothrow();
10613
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010614 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10615 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10616 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10617 // 1.2.2 OpenMP Language Terminology
10618 // Structured block - An executable statement with a single entry at the
10619 // top and a single exit at the bottom.
10620 // The point of exit cannot be a branch out of the structured block.
10621 // longjmp() and throw() must not violate the entry/exit criteria.
10622 CS->getCapturedDecl()->setNothrow();
10623 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010624 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010625
10626 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10627 AStmt);
10628}
10629
Kelvin Li83c451e2016-12-25 04:52:54 +000010630StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10631 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010632 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010633 if (!AStmt)
10634 return StmtError();
10635
Alexey Bataeve3727102018-04-18 15:57:46 +000010636 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010637 // 1.2.2 OpenMP Language Terminology
10638 // Structured block - An executable statement with a single entry at the
10639 // top and a single exit at the bottom.
10640 // The point of exit cannot be a branch out of the structured block.
10641 // longjmp() and throw() must not violate the entry/exit criteria.
10642 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010643 for (int ThisCaptureLevel =
10644 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10645 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10646 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10647 // 1.2.2 OpenMP Language Terminology
10648 // Structured block - An executable statement with a single entry at the
10649 // top and a single exit at the bottom.
10650 // The point of exit cannot be a branch out of the structured block.
10651 // longjmp() and throw() must not violate the entry/exit criteria.
10652 CS->getCapturedDecl()->setNothrow();
10653 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010654
10655 OMPLoopDirective::HelperExprs B;
10656 // In presence of clause 'collapse' with number of loops, it will
10657 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010658 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010659 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10660 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010661 VarsWithImplicitDSA, B);
10662 if (NestedLoopCount == 0)
10663 return StmtError();
10664
10665 assert((CurContext->isDependentContext() || B.builtAll()) &&
10666 "omp target teams distribute loop exprs were not built");
10667
Reid Kleckner87a31802018-03-12 21:43:02 +000010668 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010669 return OMPTargetTeamsDistributeDirective::Create(
10670 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10671}
10672
Kelvin Li80e8f562016-12-29 22:16:30 +000010673StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10674 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010675 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010676 if (!AStmt)
10677 return StmtError();
10678
Alexey Bataeve3727102018-04-18 15:57:46 +000010679 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010680 // 1.2.2 OpenMP Language Terminology
10681 // Structured block - An executable statement with a single entry at the
10682 // top and a single exit at the bottom.
10683 // The point of exit cannot be a branch out of the structured block.
10684 // longjmp() and throw() must not violate the entry/exit criteria.
10685 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010686 for (int ThisCaptureLevel =
10687 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10688 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10689 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10690 // 1.2.2 OpenMP Language Terminology
10691 // Structured block - An executable statement with a single entry at the
10692 // top and a single exit at the bottom.
10693 // The point of exit cannot be a branch out of the structured block.
10694 // longjmp() and throw() must not violate the entry/exit criteria.
10695 CS->getCapturedDecl()->setNothrow();
10696 }
10697
Kelvin Li80e8f562016-12-29 22:16:30 +000010698 OMPLoopDirective::HelperExprs B;
10699 // In presence of clause 'collapse' with number of loops, it will
10700 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010701 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010702 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10703 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010704 VarsWithImplicitDSA, B);
10705 if (NestedLoopCount == 0)
10706 return StmtError();
10707
10708 assert((CurContext->isDependentContext() || B.builtAll()) &&
10709 "omp target teams distribute parallel for loop exprs were not built");
10710
Alexey Bataev647dd842018-01-15 20:59:40 +000010711 if (!CurContext->isDependentContext()) {
10712 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010713 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010714 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10715 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10716 B.NumIterations, *this, CurScope,
10717 DSAStack))
10718 return StmtError();
10719 }
10720 }
10721
Reid Kleckner87a31802018-03-12 21:43:02 +000010722 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010723 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010724 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10725 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010726}
10727
Kelvin Li1851df52017-01-03 05:23:48 +000010728StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10729 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010730 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010731 if (!AStmt)
10732 return StmtError();
10733
Alexey Bataeve3727102018-04-18 15:57:46 +000010734 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010735 // 1.2.2 OpenMP Language Terminology
10736 // Structured block - An executable statement with a single entry at the
10737 // top and a single exit at the bottom.
10738 // The point of exit cannot be a branch out of the structured block.
10739 // longjmp() and throw() must not violate the entry/exit criteria.
10740 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010741 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10742 OMPD_target_teams_distribute_parallel_for_simd);
10743 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10744 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10745 // 1.2.2 OpenMP Language Terminology
10746 // Structured block - An executable statement with a single entry at the
10747 // top and a single exit at the bottom.
10748 // The point of exit cannot be a branch out of the structured block.
10749 // longjmp() and throw() must not violate the entry/exit criteria.
10750 CS->getCapturedDecl()->setNothrow();
10751 }
Kelvin Li1851df52017-01-03 05:23:48 +000010752
10753 OMPLoopDirective::HelperExprs B;
10754 // In presence of clause 'collapse' with number of loops, it will
10755 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010756 unsigned NestedLoopCount =
10757 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010758 getCollapseNumberExpr(Clauses),
10759 nullptr /*ordered not a clause on distribute*/, CS, *this,
10760 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010761 if (NestedLoopCount == 0)
10762 return StmtError();
10763
10764 assert((CurContext->isDependentContext() || B.builtAll()) &&
10765 "omp target teams distribute parallel for simd loop exprs were not "
10766 "built");
10767
10768 if (!CurContext->isDependentContext()) {
10769 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010770 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010771 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10772 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10773 B.NumIterations, *this, CurScope,
10774 DSAStack))
10775 return StmtError();
10776 }
10777 }
10778
Alexey Bataev438388c2017-11-22 18:34:02 +000010779 if (checkSimdlenSafelenSpecified(*this, Clauses))
10780 return StmtError();
10781
Reid Kleckner87a31802018-03-12 21:43:02 +000010782 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010783 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10784 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10785}
10786
Kelvin Lida681182017-01-10 18:08:18 +000010787StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10788 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010789 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010790 if (!AStmt)
10791 return StmtError();
10792
10793 auto *CS = cast<CapturedStmt>(AStmt);
10794 // 1.2.2 OpenMP Language Terminology
10795 // Structured block - An executable statement with a single entry at the
10796 // top and a single exit at the bottom.
10797 // The point of exit cannot be a branch out of the structured block.
10798 // longjmp() and throw() must not violate the entry/exit criteria.
10799 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010800 for (int ThisCaptureLevel =
10801 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10802 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10803 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10804 // 1.2.2 OpenMP Language Terminology
10805 // Structured block - An executable statement with a single entry at the
10806 // top and a single exit at the bottom.
10807 // The point of exit cannot be a branch out of the structured block.
10808 // longjmp() and throw() must not violate the entry/exit criteria.
10809 CS->getCapturedDecl()->setNothrow();
10810 }
Kelvin Lida681182017-01-10 18:08:18 +000010811
10812 OMPLoopDirective::HelperExprs B;
10813 // In presence of clause 'collapse' with number of loops, it will
10814 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010815 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010816 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010817 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010818 VarsWithImplicitDSA, B);
10819 if (NestedLoopCount == 0)
10820 return StmtError();
10821
10822 assert((CurContext->isDependentContext() || B.builtAll()) &&
10823 "omp target teams distribute simd loop exprs were not built");
10824
Alexey Bataev438388c2017-11-22 18:34:02 +000010825 if (!CurContext->isDependentContext()) {
10826 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010827 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010828 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10829 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10830 B.NumIterations, *this, CurScope,
10831 DSAStack))
10832 return StmtError();
10833 }
10834 }
10835
10836 if (checkSimdlenSafelenSpecified(*this, Clauses))
10837 return StmtError();
10838
Reid Kleckner87a31802018-03-12 21:43:02 +000010839 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010840 return OMPTargetTeamsDistributeSimdDirective::Create(
10841 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10842}
10843
Alexey Bataeved09d242014-05-28 05:53:51 +000010844OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010845 SourceLocation StartLoc,
10846 SourceLocation LParenLoc,
10847 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010848 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010849 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010850 case OMPC_final:
10851 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10852 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010853 case OMPC_num_threads:
10854 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10855 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010856 case OMPC_safelen:
10857 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10858 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010859 case OMPC_simdlen:
10860 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10861 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010862 case OMPC_allocator:
10863 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10864 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010865 case OMPC_collapse:
10866 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10867 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010868 case OMPC_ordered:
10869 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10870 break;
Michael Wonge710d542015-08-07 16:16:36 +000010871 case OMPC_device:
10872 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10873 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010874 case OMPC_num_teams:
10875 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10876 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010877 case OMPC_thread_limit:
10878 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10879 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010880 case OMPC_priority:
10881 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10882 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010883 case OMPC_grainsize:
10884 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10885 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010886 case OMPC_num_tasks:
10887 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10888 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010889 case OMPC_hint:
10890 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10891 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010892 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010893 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010894 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010895 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010896 case OMPC_private:
10897 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010898 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010899 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010900 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010901 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010902 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010903 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010904 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010905 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010906 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010907 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010908 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010909 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010910 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010911 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010912 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010913 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010914 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010915 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010916 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010917 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050010918 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050010919 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050010920 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050010921 case OMPC_relaxed:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010922 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010923 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010924 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010925 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010926 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010927 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010928 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010929 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010930 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010931 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010932 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010933 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010934 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010935 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010936 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010937 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010938 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010939 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010940 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010941 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050010942 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050010943 case OMPC_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010944 llvm_unreachable("Clause is not allowed.");
10945 }
10946 return Res;
10947}
10948
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010949// An OpenMP directive such as 'target parallel' has two captured regions:
10950// for the 'target' and 'parallel' respectively. This function returns
10951// the region in which to capture expressions associated with a clause.
10952// A return value of OMPD_unknown signifies that the expression should not
10953// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010954static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050010955 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010956 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010957 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010958 switch (CKind) {
10959 case OMPC_if:
10960 switch (DKind) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010961 case OMPD_target_parallel_for_simd:
10962 if (OpenMPVersion >= 50 &&
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010963 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010964 CaptureRegion = OMPD_parallel;
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010965 break;
10966 }
Alexey Bataevda17a532019-12-10 11:37:03 -050010967 LLVM_FALLTHROUGH;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010968 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010969 case OMPD_target_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010970 // If this clause applies to the nested 'parallel' region, capture within
10971 // the 'target' region, otherwise do not capture.
10972 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10973 CaptureRegion = OMPD_target;
10974 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010975 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfd0c91b2019-12-16 10:27:39 -050010976 if (OpenMPVersion >= 50 &&
10977 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10978 CaptureRegion = OMPD_parallel;
10979 break;
10980 }
10981 LLVM_FALLTHROUGH;
10982 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +000010983 // If this clause applies to the nested 'parallel' region, capture within
10984 // the 'teams' region, otherwise do not capture.
10985 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10986 CaptureRegion = OMPD_teams;
10987 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010988 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataev0b978942019-12-11 15:26:38 -050010989 if (OpenMPVersion >= 50 &&
10990 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10991 CaptureRegion = OMPD_parallel;
10992 break;
10993 }
10994 LLVM_FALLTHROUGH;
10995 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010996 CaptureRegion = OMPD_teams;
10997 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010998 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010999 case OMPD_target_enter_data:
11000 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011001 CaptureRegion = OMPD_task;
11002 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011003 case OMPD_parallel_master_taskloop:
11004 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
11005 CaptureRegion = OMPD_parallel;
11006 break;
Alexey Bataev5c517a62019-12-05 11:31:45 -050011007 case OMPD_parallel_master_taskloop_simd:
11008 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
11009 NameModifier == OMPD_taskloop) {
11010 CaptureRegion = OMPD_parallel;
11011 break;
11012 }
11013 if (OpenMPVersion <= 45)
11014 break;
11015 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11016 CaptureRegion = OMPD_taskloop;
11017 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050011018 case OMPD_parallel_for_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050011019 if (OpenMPVersion <= 45)
11020 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050011021 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11022 CaptureRegion = OMPD_parallel;
11023 break;
Alexey Bataev61205822019-12-04 09:50:21 -050011024 case OMPD_taskloop_simd:
Alexey Bataev853961f2019-12-05 09:50:18 -050011025 case OMPD_master_taskloop_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050011026 if (OpenMPVersion <= 45)
11027 break;
11028 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11029 CaptureRegion = OMPD_taskloop;
11030 break;
Alexey Bataev52812f22019-12-05 13:22:15 -050011031 case OMPD_distribute_parallel_for_simd:
11032 if (OpenMPVersion <= 45)
11033 break;
11034 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11035 CaptureRegion = OMPD_parallel;
11036 break;
Alexey Bataevef94cd12019-12-10 12:44:45 -050011037 case OMPD_target_simd:
11038 if (OpenMPVersion >= 50 &&
11039 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11040 CaptureRegion = OMPD_target;
11041 break;
Alexey Bataev7b774b72019-12-11 11:20:47 -050011042 case OMPD_teams_distribute_simd:
Alexey Bataev411e81a2019-12-16 11:16:46 -050011043 case OMPD_target_teams_distribute_simd:
Alexey Bataev7b774b72019-12-11 11:20:47 -050011044 if (OpenMPVersion >= 50 &&
11045 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11046 CaptureRegion = OMPD_teams;
11047 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011048 case OMPD_cancel:
11049 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011050 case OMPD_parallel_master:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011051 case OMPD_parallel_sections:
11052 case OMPD_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011053 case OMPD_target:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011054 case OMPD_target_teams:
11055 case OMPD_target_teams_distribute:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011056 case OMPD_distribute_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011057 case OMPD_task:
11058 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011059 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011060 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050011061 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050011062 case OMPD_for_simd:
Alexey Bataev779a1802019-12-06 12:21:31 -050011063 case OMPD_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011064 // Do not capture if-clause expressions.
11065 break;
11066 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011067 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011068 case OMPD_taskyield:
11069 case OMPD_barrier:
11070 case OMPD_taskwait:
11071 case OMPD_cancellation_point:
11072 case OMPD_flush:
11073 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011074 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011075 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011076 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011077 case OMPD_declare_target:
11078 case OMPD_end_declare_target:
11079 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011080 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011081 case OMPD_sections:
11082 case OMPD_section:
11083 case OMPD_single:
11084 case OMPD_master:
11085 case OMPD_critical:
11086 case OMPD_taskgroup:
11087 case OMPD_distribute:
11088 case OMPD_ordered:
11089 case OMPD_atomic:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011090 case OMPD_teams_distribute:
Kelvin Li1408f912018-09-26 04:28:39 +000011091 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011092 llvm_unreachable("Unexpected OpenMP directive with if-clause");
11093 case OMPD_unknown:
11094 llvm_unreachable("Unknown OpenMP directive");
11095 }
11096 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011097 case OMPC_num_threads:
11098 switch (DKind) {
11099 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011100 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000011101 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011102 CaptureRegion = OMPD_target;
11103 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000011104 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011105 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011106 case OMPD_target_teams_distribute_parallel_for:
11107 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011108 CaptureRegion = OMPD_teams;
11109 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011110 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011111 case OMPD_parallel_master:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011112 case OMPD_parallel_sections:
11113 case OMPD_parallel_for:
11114 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011115 case OMPD_distribute_parallel_for:
11116 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011117 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011118 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011119 // Do not capture num_threads-clause expressions.
11120 break;
11121 case OMPD_target_data:
11122 case OMPD_target_enter_data:
11123 case OMPD_target_exit_data:
11124 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011125 case OMPD_target:
11126 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011127 case OMPD_target_teams:
11128 case OMPD_target_teams_distribute:
11129 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011130 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011131 case OMPD_task:
11132 case OMPD_taskloop:
11133 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011134 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011135 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011136 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011137 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011138 case OMPD_taskyield:
11139 case OMPD_barrier:
11140 case OMPD_taskwait:
11141 case OMPD_cancellation_point:
11142 case OMPD_flush:
11143 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011144 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011145 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011146 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011147 case OMPD_declare_target:
11148 case OMPD_end_declare_target:
11149 case OMPD_teams:
11150 case OMPD_simd:
11151 case OMPD_for:
11152 case OMPD_for_simd:
11153 case OMPD_sections:
11154 case OMPD_section:
11155 case OMPD_single:
11156 case OMPD_master:
11157 case OMPD_critical:
11158 case OMPD_taskgroup:
11159 case OMPD_distribute:
11160 case OMPD_ordered:
11161 case OMPD_atomic:
11162 case OMPD_distribute_simd:
11163 case OMPD_teams_distribute:
11164 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011165 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011166 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
11167 case OMPD_unknown:
11168 llvm_unreachable("Unknown OpenMP directive");
11169 }
11170 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011171 case OMPC_num_teams:
11172 switch (DKind) {
11173 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011174 case OMPD_target_teams_distribute:
11175 case OMPD_target_teams_distribute_simd:
11176 case OMPD_target_teams_distribute_parallel_for:
11177 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011178 CaptureRegion = OMPD_target;
11179 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011180 case OMPD_teams_distribute_parallel_for:
11181 case OMPD_teams_distribute_parallel_for_simd:
11182 case OMPD_teams:
11183 case OMPD_teams_distribute:
11184 case OMPD_teams_distribute_simd:
11185 // Do not capture num_teams-clause expressions.
11186 break;
11187 case OMPD_distribute_parallel_for:
11188 case OMPD_distribute_parallel_for_simd:
11189 case OMPD_task:
11190 case OMPD_taskloop:
11191 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011192 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011193 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011194 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011195 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011196 case OMPD_target_data:
11197 case OMPD_target_enter_data:
11198 case OMPD_target_exit_data:
11199 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011200 case OMPD_cancel:
11201 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011202 case OMPD_parallel_master:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011203 case OMPD_parallel_sections:
11204 case OMPD_parallel_for:
11205 case OMPD_parallel_for_simd:
11206 case OMPD_target:
11207 case OMPD_target_simd:
11208 case OMPD_target_parallel:
11209 case OMPD_target_parallel_for:
11210 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011211 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011212 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011213 case OMPD_taskyield:
11214 case OMPD_barrier:
11215 case OMPD_taskwait:
11216 case OMPD_cancellation_point:
11217 case OMPD_flush:
11218 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011219 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011220 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011221 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011222 case OMPD_declare_target:
11223 case OMPD_end_declare_target:
11224 case OMPD_simd:
11225 case OMPD_for:
11226 case OMPD_for_simd:
11227 case OMPD_sections:
11228 case OMPD_section:
11229 case OMPD_single:
11230 case OMPD_master:
11231 case OMPD_critical:
11232 case OMPD_taskgroup:
11233 case OMPD_distribute:
11234 case OMPD_ordered:
11235 case OMPD_atomic:
11236 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011237 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011238 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11239 case OMPD_unknown:
11240 llvm_unreachable("Unknown OpenMP directive");
11241 }
11242 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011243 case OMPC_thread_limit:
11244 switch (DKind) {
11245 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011246 case OMPD_target_teams_distribute:
11247 case OMPD_target_teams_distribute_simd:
11248 case OMPD_target_teams_distribute_parallel_for:
11249 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011250 CaptureRegion = OMPD_target;
11251 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011252 case OMPD_teams_distribute_parallel_for:
11253 case OMPD_teams_distribute_parallel_for_simd:
11254 case OMPD_teams:
11255 case OMPD_teams_distribute:
11256 case OMPD_teams_distribute_simd:
11257 // Do not capture thread_limit-clause expressions.
11258 break;
11259 case OMPD_distribute_parallel_for:
11260 case OMPD_distribute_parallel_for_simd:
11261 case OMPD_task:
11262 case OMPD_taskloop:
11263 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011264 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011265 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011266 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011267 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011268 case OMPD_target_data:
11269 case OMPD_target_enter_data:
11270 case OMPD_target_exit_data:
11271 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011272 case OMPD_cancel:
11273 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011274 case OMPD_parallel_master:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011275 case OMPD_parallel_sections:
11276 case OMPD_parallel_for:
11277 case OMPD_parallel_for_simd:
11278 case OMPD_target:
11279 case OMPD_target_simd:
11280 case OMPD_target_parallel:
11281 case OMPD_target_parallel_for:
11282 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011283 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011284 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011285 case OMPD_taskyield:
11286 case OMPD_barrier:
11287 case OMPD_taskwait:
11288 case OMPD_cancellation_point:
11289 case OMPD_flush:
11290 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011291 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011292 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011293 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011294 case OMPD_declare_target:
11295 case OMPD_end_declare_target:
11296 case OMPD_simd:
11297 case OMPD_for:
11298 case OMPD_for_simd:
11299 case OMPD_sections:
11300 case OMPD_section:
11301 case OMPD_single:
11302 case OMPD_master:
11303 case OMPD_critical:
11304 case OMPD_taskgroup:
11305 case OMPD_distribute:
11306 case OMPD_ordered:
11307 case OMPD_atomic:
11308 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011309 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011310 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
11311 case OMPD_unknown:
11312 llvm_unreachable("Unknown OpenMP directive");
11313 }
11314 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011315 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011316 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000011317 case OMPD_parallel_for:
11318 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011319 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000011320 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011321 case OMPD_teams_distribute_parallel_for:
11322 case OMPD_teams_distribute_parallel_for_simd:
11323 case OMPD_target_parallel_for:
11324 case OMPD_target_parallel_for_simd:
11325 case OMPD_target_teams_distribute_parallel_for:
11326 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011327 CaptureRegion = OMPD_parallel;
11328 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011329 case OMPD_for:
11330 case OMPD_for_simd:
11331 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011332 break;
11333 case OMPD_task:
11334 case OMPD_taskloop:
11335 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011336 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011337 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011338 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011339 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011340 case OMPD_target_data:
11341 case OMPD_target_enter_data:
11342 case OMPD_target_exit_data:
11343 case OMPD_target_update:
11344 case OMPD_teams:
11345 case OMPD_teams_distribute:
11346 case OMPD_teams_distribute_simd:
11347 case OMPD_target_teams_distribute:
11348 case OMPD_target_teams_distribute_simd:
11349 case OMPD_target:
11350 case OMPD_target_simd:
11351 case OMPD_target_parallel:
11352 case OMPD_cancel:
11353 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011354 case OMPD_parallel_master:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011355 case OMPD_parallel_sections:
11356 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011357 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011358 case OMPD_taskyield:
11359 case OMPD_barrier:
11360 case OMPD_taskwait:
11361 case OMPD_cancellation_point:
11362 case OMPD_flush:
11363 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011364 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011365 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011366 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011367 case OMPD_declare_target:
11368 case OMPD_end_declare_target:
11369 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011370 case OMPD_sections:
11371 case OMPD_section:
11372 case OMPD_single:
11373 case OMPD_master:
11374 case OMPD_critical:
11375 case OMPD_taskgroup:
11376 case OMPD_distribute:
11377 case OMPD_ordered:
11378 case OMPD_atomic:
11379 case OMPD_distribute_simd:
11380 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011381 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011382 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11383 case OMPD_unknown:
11384 llvm_unreachable("Unknown OpenMP directive");
11385 }
11386 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011387 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011388 switch (DKind) {
11389 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011390 case OMPD_teams_distribute_parallel_for_simd:
11391 case OMPD_teams_distribute:
11392 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011393 case OMPD_target_teams_distribute_parallel_for:
11394 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011395 case OMPD_target_teams_distribute:
11396 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011397 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011398 break;
11399 case OMPD_distribute_parallel_for:
11400 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011401 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011402 case OMPD_distribute_simd:
11403 // Do not capture thread_limit-clause expressions.
11404 break;
11405 case OMPD_parallel_for:
11406 case OMPD_parallel_for_simd:
11407 case OMPD_target_parallel_for_simd:
11408 case OMPD_target_parallel_for:
11409 case OMPD_task:
11410 case OMPD_taskloop:
11411 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011412 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011413 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011414 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011415 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011416 case OMPD_target_data:
11417 case OMPD_target_enter_data:
11418 case OMPD_target_exit_data:
11419 case OMPD_target_update:
11420 case OMPD_teams:
11421 case OMPD_target:
11422 case OMPD_target_simd:
11423 case OMPD_target_parallel:
11424 case OMPD_cancel:
11425 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011426 case OMPD_parallel_master:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011427 case OMPD_parallel_sections:
11428 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011429 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011430 case OMPD_taskyield:
11431 case OMPD_barrier:
11432 case OMPD_taskwait:
11433 case OMPD_cancellation_point:
11434 case OMPD_flush:
11435 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011436 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011437 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011438 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011439 case OMPD_declare_target:
11440 case OMPD_end_declare_target:
11441 case OMPD_simd:
11442 case OMPD_for:
11443 case OMPD_for_simd:
11444 case OMPD_sections:
11445 case OMPD_section:
11446 case OMPD_single:
11447 case OMPD_master:
11448 case OMPD_critical:
11449 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011450 case OMPD_ordered:
11451 case OMPD_atomic:
11452 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011453 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011454 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11455 case OMPD_unknown:
11456 llvm_unreachable("Unknown OpenMP directive");
11457 }
11458 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011459 case OMPC_device:
11460 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011461 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011462 case OMPD_target_enter_data:
11463 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011464 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011465 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011466 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011467 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011468 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011469 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011470 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011471 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011472 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011473 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011474 CaptureRegion = OMPD_task;
11475 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011476 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011477 // Do not capture device-clause expressions.
11478 break;
11479 case OMPD_teams_distribute_parallel_for:
11480 case OMPD_teams_distribute_parallel_for_simd:
11481 case OMPD_teams:
11482 case OMPD_teams_distribute:
11483 case OMPD_teams_distribute_simd:
11484 case OMPD_distribute_parallel_for:
11485 case OMPD_distribute_parallel_for_simd:
11486 case OMPD_task:
11487 case OMPD_taskloop:
11488 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011489 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011490 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011491 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011492 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011493 case OMPD_cancel:
11494 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011495 case OMPD_parallel_master:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011496 case OMPD_parallel_sections:
11497 case OMPD_parallel_for:
11498 case OMPD_parallel_for_simd:
11499 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011500 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011501 case OMPD_taskyield:
11502 case OMPD_barrier:
11503 case OMPD_taskwait:
11504 case OMPD_cancellation_point:
11505 case OMPD_flush:
11506 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011507 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011508 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011509 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011510 case OMPD_declare_target:
11511 case OMPD_end_declare_target:
11512 case OMPD_simd:
11513 case OMPD_for:
11514 case OMPD_for_simd:
11515 case OMPD_sections:
11516 case OMPD_section:
11517 case OMPD_single:
11518 case OMPD_master:
11519 case OMPD_critical:
11520 case OMPD_taskgroup:
11521 case OMPD_distribute:
11522 case OMPD_ordered:
11523 case OMPD_atomic:
11524 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011525 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011526 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11527 case OMPD_unknown:
11528 llvm_unreachable("Unknown OpenMP directive");
11529 }
11530 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011531 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011532 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011533 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011534 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011535 switch (DKind) {
11536 case OMPD_task:
11537 case OMPD_taskloop:
11538 case OMPD_taskloop_simd:
11539 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011540 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011541 break;
11542 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011543 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011544 CaptureRegion = OMPD_parallel;
11545 break;
11546 case OMPD_target_update:
11547 case OMPD_target_enter_data:
11548 case OMPD_target_exit_data:
11549 case OMPD_target:
11550 case OMPD_target_simd:
11551 case OMPD_target_teams:
11552 case OMPD_target_parallel:
11553 case OMPD_target_teams_distribute:
11554 case OMPD_target_teams_distribute_simd:
11555 case OMPD_target_parallel_for:
11556 case OMPD_target_parallel_for_simd:
11557 case OMPD_target_teams_distribute_parallel_for:
11558 case OMPD_target_teams_distribute_parallel_for_simd:
11559 case OMPD_target_data:
11560 case OMPD_teams_distribute_parallel_for:
11561 case OMPD_teams_distribute_parallel_for_simd:
11562 case OMPD_teams:
11563 case OMPD_teams_distribute:
11564 case OMPD_teams_distribute_simd:
11565 case OMPD_distribute_parallel_for:
11566 case OMPD_distribute_parallel_for_simd:
11567 case OMPD_cancel:
11568 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011569 case OMPD_parallel_master:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011570 case OMPD_parallel_sections:
11571 case OMPD_parallel_for:
11572 case OMPD_parallel_for_simd:
11573 case OMPD_threadprivate:
11574 case OMPD_allocate:
11575 case OMPD_taskyield:
11576 case OMPD_barrier:
11577 case OMPD_taskwait:
11578 case OMPD_cancellation_point:
11579 case OMPD_flush:
11580 case OMPD_declare_reduction:
11581 case OMPD_declare_mapper:
11582 case OMPD_declare_simd:
11583 case OMPD_declare_variant:
11584 case OMPD_declare_target:
11585 case OMPD_end_declare_target:
11586 case OMPD_simd:
11587 case OMPD_for:
11588 case OMPD_for_simd:
11589 case OMPD_sections:
11590 case OMPD_section:
11591 case OMPD_single:
11592 case OMPD_master:
11593 case OMPD_critical:
11594 case OMPD_taskgroup:
11595 case OMPD_distribute:
11596 case OMPD_ordered:
11597 case OMPD_atomic:
11598 case OMPD_distribute_simd:
11599 case OMPD_requires:
11600 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11601 case OMPD_unknown:
11602 llvm_unreachable("Unknown OpenMP directive");
11603 }
11604 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011605 case OMPC_firstprivate:
11606 case OMPC_lastprivate:
11607 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011608 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011609 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011610 case OMPC_linear:
11611 case OMPC_default:
11612 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011613 case OMPC_safelen:
11614 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011615 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011616 case OMPC_collapse:
11617 case OMPC_private:
11618 case OMPC_shared:
11619 case OMPC_aligned:
11620 case OMPC_copyin:
11621 case OMPC_copyprivate:
11622 case OMPC_ordered:
11623 case OMPC_nowait:
11624 case OMPC_untied:
11625 case OMPC_mergeable:
11626 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011627 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011628 case OMPC_flush:
11629 case OMPC_read:
11630 case OMPC_write:
11631 case OMPC_update:
11632 case OMPC_capture:
11633 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050011634 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050011635 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050011636 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050011637 case OMPC_relaxed:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011638 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011639 case OMPC_threads:
11640 case OMPC_simd:
11641 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011642 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011643 case OMPC_hint:
11644 case OMPC_defaultmap:
11645 case OMPC_unknown:
11646 case OMPC_uniform:
11647 case OMPC_to:
11648 case OMPC_from:
11649 case OMPC_use_device_ptr:
11650 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011651 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011652 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011653 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011654 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011655 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011656 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011657 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011658 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050011659 case OMPC_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011660 llvm_unreachable("Unexpected OpenMP clause.");
11661 }
11662 return CaptureRegion;
11663}
11664
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011665OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11666 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011667 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011668 SourceLocation NameModifierLoc,
11669 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011670 SourceLocation EndLoc) {
11671 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011672 Stmt *HelperValStmt = nullptr;
11673 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011674 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11675 !Condition->isInstantiationDependent() &&
11676 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011677 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011678 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011679 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011680
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011681 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011682
11683 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011684 CaptureRegion = getOpenMPCaptureRegionForClause(
11685 DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011686 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011687 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011688 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011689 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11690 HelperValStmt = buildPreInits(Context, Captures);
11691 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011692 }
11693
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011694 return new (Context)
11695 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11696 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011697}
11698
Alexey Bataev3778b602014-07-17 07:32:53 +000011699OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11700 SourceLocation StartLoc,
11701 SourceLocation LParenLoc,
11702 SourceLocation EndLoc) {
11703 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011704 Stmt *HelperValStmt = nullptr;
11705 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011706 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11707 !Condition->isInstantiationDependent() &&
11708 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011709 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011710 if (Val.isInvalid())
11711 return nullptr;
11712
Richard Smith03a4aa32016-06-23 19:02:52 +000011713 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011714
11715 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011716 CaptureRegion =
11717 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011718 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11719 ValExpr = MakeFullExpr(ValExpr).get();
11720 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11721 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11722 HelperValStmt = buildPreInits(Context, Captures);
11723 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011724 }
11725
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011726 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11727 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011728}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011729
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011730ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11731 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011732 if (!Op)
11733 return ExprError();
11734
11735 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11736 public:
11737 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011738 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011739 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11740 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011741 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11742 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011743 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11744 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011745 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11746 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011747 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11748 QualType T,
11749 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011750 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11751 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011752 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11753 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011754 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011755 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011756 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011757 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11758 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011759 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11760 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011761 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11762 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011763 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011764 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011765 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011766 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11767 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011768 llvm_unreachable("conversion functions are permitted");
11769 }
11770 } ConvertDiagnoser;
11771 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11772}
11773
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011774static bool
11775isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11776 bool StrictlyPositive, bool BuildCapture = false,
11777 OpenMPDirectiveKind DKind = OMPD_unknown,
11778 OpenMPDirectiveKind *CaptureRegion = nullptr,
11779 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011780 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11781 !ValExpr->isInstantiationDependent()) {
11782 SourceLocation Loc = ValExpr->getExprLoc();
11783 ExprResult Value =
11784 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11785 if (Value.isInvalid())
11786 return false;
11787
11788 ValExpr = Value.get();
11789 // The expression must evaluate to a non-negative integer value.
11790 llvm::APSInt Result;
11791 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011792 Result.isSigned() &&
11793 !((!StrictlyPositive && Result.isNonNegative()) ||
11794 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011795 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011796 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11797 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011798 return false;
11799 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011800 if (!BuildCapture)
11801 return true;
Alexey Bataev61205822019-12-04 09:50:21 -050011802 *CaptureRegion =
11803 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011804 if (*CaptureRegion != OMPD_unknown &&
11805 !SemaRef.CurContext->isDependentContext()) {
11806 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11807 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11808 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11809 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11810 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011811 }
11812 return true;
11813}
11814
Alexey Bataev568a8332014-03-06 06:15:19 +000011815OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11816 SourceLocation StartLoc,
11817 SourceLocation LParenLoc,
11818 SourceLocation EndLoc) {
11819 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011820 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011821
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011822 // OpenMP [2.5, Restrictions]
11823 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011824 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011825 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011826 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011827
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011828 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011829 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050011830 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011831 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011832 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011833 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011834 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11835 HelperValStmt = buildPreInits(Context, Captures);
11836 }
11837
11838 return new (Context) OMPNumThreadsClause(
11839 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011840}
11841
Alexey Bataev62c87d22014-03-21 04:51:18 +000011842ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011843 OpenMPClauseKind CKind,
11844 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011845 if (!E)
11846 return ExprError();
11847 if (E->isValueDependent() || E->isTypeDependent() ||
11848 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011849 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011850 llvm::APSInt Result;
11851 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11852 if (ICE.isInvalid())
11853 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011854 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11855 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011856 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011857 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11858 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011859 return ExprError();
11860 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011861 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11862 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11863 << E->getSourceRange();
11864 return ExprError();
11865 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011866 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11867 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011868 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011869 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011870 return ICE;
11871}
11872
11873OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11874 SourceLocation LParenLoc,
11875 SourceLocation EndLoc) {
11876 // OpenMP [2.8.1, simd construct, Description]
11877 // The parameter of the safelen clause must be a constant
11878 // positive integer expression.
11879 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11880 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011881 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011882 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011883 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011884}
11885
Alexey Bataev66b15b52015-08-21 11:14:16 +000011886OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11887 SourceLocation LParenLoc,
11888 SourceLocation EndLoc) {
11889 // OpenMP [2.8.1, simd construct, Description]
11890 // The parameter of the simdlen clause must be a constant
11891 // positive integer expression.
11892 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11893 if (Simdlen.isInvalid())
11894 return nullptr;
11895 return new (Context)
11896 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11897}
11898
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011899/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011900static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11901 DSAStackTy *Stack) {
11902 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011903 if (!OMPAllocatorHandleT.isNull())
11904 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011905 // Build the predefined allocator expressions.
11906 bool ErrorFound = false;
11907 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11908 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11909 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11910 StringRef Allocator =
11911 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11912 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11913 auto *VD = dyn_cast_or_null<ValueDecl>(
11914 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11915 if (!VD) {
11916 ErrorFound = true;
11917 break;
11918 }
11919 QualType AllocatorType =
11920 VD->getType().getNonLValueExprType(S.getASTContext());
11921 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11922 if (!Res.isUsable()) {
11923 ErrorFound = true;
11924 break;
11925 }
11926 if (OMPAllocatorHandleT.isNull())
11927 OMPAllocatorHandleT = AllocatorType;
11928 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11929 ErrorFound = true;
11930 break;
11931 }
11932 Stack->setAllocator(AllocatorKind, Res.get());
11933 }
11934 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011935 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11936 return false;
11937 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011938 OMPAllocatorHandleT.addConst();
11939 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011940 return true;
11941}
11942
11943OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11944 SourceLocation LParenLoc,
11945 SourceLocation EndLoc) {
11946 // OpenMP [2.11.3, allocate Directive, Description]
11947 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011948 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011949 return nullptr;
11950
11951 ExprResult Allocator = DefaultLvalueConversion(A);
11952 if (Allocator.isInvalid())
11953 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011954 Allocator = PerformImplicitConversion(Allocator.get(),
11955 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011956 Sema::AA_Initializing,
11957 /*AllowExplicit=*/true);
11958 if (Allocator.isInvalid())
11959 return nullptr;
11960 return new (Context)
11961 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11962}
11963
Alexander Musman64d33f12014-06-04 07:53:32 +000011964OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11965 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011966 SourceLocation LParenLoc,
11967 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011968 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011969 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011970 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011971 // The parameter of the collapse clause must be a constant
11972 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011973 ExprResult NumForLoopsResult =
11974 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11975 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011976 return nullptr;
11977 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011978 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011979}
11980
Alexey Bataev10e775f2015-07-30 11:36:16 +000011981OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11982 SourceLocation EndLoc,
11983 SourceLocation LParenLoc,
11984 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011985 // OpenMP [2.7.1, loop construct, Description]
11986 // OpenMP [2.8.1, simd construct, Description]
11987 // OpenMP [2.9.6, distribute construct, Description]
11988 // The parameter of the ordered clause must be a constant
11989 // positive integer expression if any.
11990 if (NumForLoops && LParenLoc.isValid()) {
11991 ExprResult NumForLoopsResult =
11992 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11993 if (NumForLoopsResult.isInvalid())
11994 return nullptr;
11995 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011996 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011997 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011998 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011999 auto *Clause = OMPOrderedClause::Create(
12000 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
12001 StartLoc, LParenLoc, EndLoc);
12002 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
12003 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000012004}
12005
Alexey Bataeved09d242014-05-28 05:53:51 +000012006OMPClause *Sema::ActOnOpenMPSimpleClause(
12007 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
12008 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012009 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012010 switch (Kind) {
12011 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000012012 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000012013 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
12014 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012015 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012016 case OMPC_proc_bind:
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012017 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
12018 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012019 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012020 case OMPC_atomic_default_mem_order:
12021 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
12022 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
12023 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12024 break;
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012025 case OMPC_order:
12026 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
12027 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12028 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012029 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012030 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012031 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012032 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012033 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012034 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012035 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012036 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012037 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012038 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000012039 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000012040 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000012041 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012042 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012043 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000012044 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012045 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012046 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012047 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012048 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012049 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012050 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012051 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012052 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012053 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012054 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012055 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012056 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012057 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012058 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012059 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050012060 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050012061 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050012062 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012063 case OMPC_relaxed:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012064 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012065 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012066 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012067 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012068 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012069 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012070 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012071 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012072 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012073 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012074 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012075 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012076 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012077 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012078 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012079 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012080 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012081 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012082 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012083 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000012084 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012085 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012086 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012087 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000012088 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012089 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012090 case OMPC_nontemporal:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012091 llvm_unreachable("Clause is not allowed.");
12092 }
12093 return Res;
12094}
12095
Alexey Bataev6402bca2015-12-28 07:25:51 +000012096static std::string
12097getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
12098 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012099 SmallString<256> Buffer;
12100 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000012101 unsigned Skipped = Exclude.size();
12102 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000012103 for (unsigned I = First; I < Last; ++I) {
12104 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012105 --Skipped;
12106 continue;
12107 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012108 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
Alexey Bataev87a004d2020-01-02 09:26:32 -050012109 if (I + Skipped + 2 == Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000012110 Out << " or ";
Alexey Bataev87a004d2020-01-02 09:26:32 -050012111 else if (I + Skipped + 1 != Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000012112 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000012113 }
Benjamin Krameradcd0262020-01-28 20:23:46 +010012114 return std::string(Out.str());
Alexey Bataev6402bca2015-12-28 07:25:51 +000012115}
12116
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012117OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
12118 SourceLocation KindKwLoc,
12119 SourceLocation StartLoc,
12120 SourceLocation LParenLoc,
12121 SourceLocation EndLoc) {
12122 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000012123 static_assert(OMPC_DEFAULT_unknown > 0,
12124 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012125 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012126 << getListOfPossibleValues(OMPC_default, /*First=*/0,
12127 /*Last=*/OMPC_DEFAULT_unknown)
12128 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012129 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012130 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000012131 switch (Kind) {
12132 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012133 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012134 break;
12135 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012136 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012137 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012138 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012139 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000012140 break;
12141 }
Alexey Bataeved09d242014-05-28 05:53:51 +000012142 return new (Context)
12143 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012144}
12145
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012146OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012147 SourceLocation KindKwLoc,
12148 SourceLocation StartLoc,
12149 SourceLocation LParenLoc,
12150 SourceLocation EndLoc) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012151 if (Kind == OMP_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012152 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012153 << getListOfPossibleValues(OMPC_proc_bind,
12154 /*First=*/unsigned(OMP_PROC_BIND_master),
12155 /*Last=*/5)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012156 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012157 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012158 }
Alexey Bataeved09d242014-05-28 05:53:51 +000012159 return new (Context)
12160 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012161}
12162
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012163OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
12164 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
12165 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12166 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
12167 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12168 << getListOfPossibleValues(
12169 OMPC_atomic_default_mem_order, /*First=*/0,
12170 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
12171 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
12172 return nullptr;
12173 }
12174 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
12175 LParenLoc, EndLoc);
12176}
12177
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012178OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
12179 SourceLocation KindKwLoc,
12180 SourceLocation StartLoc,
12181 SourceLocation LParenLoc,
12182 SourceLocation EndLoc) {
12183 if (Kind == OMPC_ORDER_unknown) {
12184 static_assert(OMPC_ORDER_unknown > 0,
12185 "OMPC_ORDER_unknown not greater than 0");
12186 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12187 << getListOfPossibleValues(OMPC_order, /*First=*/0,
12188 /*Last=*/OMPC_ORDER_unknown)
12189 << getOpenMPClauseName(OMPC_order);
12190 return nullptr;
12191 }
12192 return new (Context)
12193 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12194}
12195
Alexey Bataev56dafe82014-06-20 07:16:17 +000012196OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012197 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012198 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012199 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012200 SourceLocation EndLoc) {
12201 OMPClause *Res = nullptr;
12202 switch (Kind) {
12203 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012204 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
12205 assert(Argument.size() == NumberOfElements &&
12206 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012207 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012208 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
12209 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
12210 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
12211 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
12212 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012213 break;
12214 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012215 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
12216 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
12217 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
12218 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000012219 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012220 case OMPC_dist_schedule:
12221 Res = ActOnOpenMPDistScheduleClause(
12222 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
12223 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
12224 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012225 case OMPC_defaultmap:
12226 enum { Modifier, DefaultmapKind };
12227 Res = ActOnOpenMPDefaultmapClause(
12228 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
12229 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000012230 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
12231 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012232 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000012233 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012234 case OMPC_num_threads:
12235 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012236 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012237 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012238 case OMPC_collapse:
12239 case OMPC_default:
12240 case OMPC_proc_bind:
12241 case OMPC_private:
12242 case OMPC_firstprivate:
12243 case OMPC_lastprivate:
12244 case OMPC_shared:
12245 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012246 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012247 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012248 case OMPC_linear:
12249 case OMPC_aligned:
12250 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012251 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012252 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012253 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012254 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012255 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012256 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012257 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012258 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012259 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012260 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012261 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012262 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012263 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050012264 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050012265 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050012266 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012267 case OMPC_relaxed:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012268 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012269 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012270 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012271 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012272 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012273 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012274 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012275 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012276 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012277 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012278 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012279 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012280 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012281 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012282 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012283 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012284 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012285 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000012286 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012287 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012288 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012289 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012290 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012291 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012292 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012293 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012294 case OMPC_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012295 llvm_unreachable("Clause is not allowed.");
12296 }
12297 return Res;
12298}
12299
Alexey Bataev6402bca2015-12-28 07:25:51 +000012300static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
12301 OpenMPScheduleClauseModifier M2,
12302 SourceLocation M1Loc, SourceLocation M2Loc) {
12303 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
12304 SmallVector<unsigned, 2> Excluded;
12305 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
12306 Excluded.push_back(M2);
12307 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
12308 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
12309 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
12310 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
12311 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
12312 << getListOfPossibleValues(OMPC_schedule,
12313 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
12314 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12315 Excluded)
12316 << getOpenMPClauseName(OMPC_schedule);
12317 return true;
12318 }
12319 return false;
12320}
12321
Alexey Bataev56dafe82014-06-20 07:16:17 +000012322OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012323 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012324 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012325 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
12326 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
12327 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
12328 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
12329 return nullptr;
12330 // OpenMP, 2.7.1, Loop Construct, Restrictions
12331 // Either the monotonic modifier or the nonmonotonic modifier can be specified
12332 // but not both.
12333 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
12334 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
12335 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
12336 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
12337 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
12338 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
12339 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
12340 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
12341 return nullptr;
12342 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012343 if (Kind == OMPC_SCHEDULE_unknown) {
12344 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000012345 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
12346 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
12347 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12348 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12349 Exclude);
12350 } else {
12351 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12352 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012353 }
12354 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12355 << Values << getOpenMPClauseName(OMPC_schedule);
12356 return nullptr;
12357 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000012358 // OpenMP, 2.7.1, Loop Construct, Restrictions
12359 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
12360 // schedule(guided).
12361 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
12362 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
12363 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
12364 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
12365 diag::err_omp_schedule_nonmonotonic_static);
12366 return nullptr;
12367 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012368 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012369 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000012370 if (ChunkSize) {
12371 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12372 !ChunkSize->isInstantiationDependent() &&
12373 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012374 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000012375 ExprResult Val =
12376 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12377 if (Val.isInvalid())
12378 return nullptr;
12379
12380 ValExpr = Val.get();
12381
12382 // OpenMP [2.7.1, Restrictions]
12383 // chunk_size must be a loop invariant integer expression with a positive
12384 // value.
12385 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000012386 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12387 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12388 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000012389 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000012390 return nullptr;
12391 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012392 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050012393 DSAStack->getCurrentDirective(), OMPC_schedule,
12394 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012395 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012396 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012397 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012398 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12399 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012400 }
12401 }
12402 }
12403
Alexey Bataev6402bca2015-12-28 07:25:51 +000012404 return new (Context)
12405 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012406 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012407}
12408
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012409OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12410 SourceLocation StartLoc,
12411 SourceLocation EndLoc) {
12412 OMPClause *Res = nullptr;
12413 switch (Kind) {
12414 case OMPC_ordered:
12415 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12416 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012417 case OMPC_nowait:
12418 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12419 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012420 case OMPC_untied:
12421 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12422 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012423 case OMPC_mergeable:
12424 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12425 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012426 case OMPC_read:
12427 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12428 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012429 case OMPC_write:
12430 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12431 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012432 case OMPC_update:
12433 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12434 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012435 case OMPC_capture:
12436 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12437 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012438 case OMPC_seq_cst:
12439 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12440 break;
Alexey Bataevea9166b2020-02-06 16:30:23 -050012441 case OMPC_acq_rel:
12442 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
12443 break;
Alexey Bataev04a830f2020-02-10 14:30:39 -050012444 case OMPC_acquire:
12445 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
12446 break;
Alexey Bataev95598342020-02-10 15:49:05 -050012447 case OMPC_release:
12448 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
12449 break;
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012450 case OMPC_relaxed:
12451 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
12452 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012453 case OMPC_threads:
12454 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12455 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012456 case OMPC_simd:
12457 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12458 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012459 case OMPC_nogroup:
12460 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12461 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012462 case OMPC_unified_address:
12463 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12464 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012465 case OMPC_unified_shared_memory:
12466 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12467 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012468 case OMPC_reverse_offload:
12469 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12470 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012471 case OMPC_dynamic_allocators:
12472 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12473 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012474 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012475 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012476 case OMPC_num_threads:
12477 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012478 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012479 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012480 case OMPC_collapse:
12481 case OMPC_schedule:
12482 case OMPC_private:
12483 case OMPC_firstprivate:
12484 case OMPC_lastprivate:
12485 case OMPC_shared:
12486 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012487 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012488 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012489 case OMPC_linear:
12490 case OMPC_aligned:
12491 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012492 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012493 case OMPC_default:
12494 case OMPC_proc_bind:
12495 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012496 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012497 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012498 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012499 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012500 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012501 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012502 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012503 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012504 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012505 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012506 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012507 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012508 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012509 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012510 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012511 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012512 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012513 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012514 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012515 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012516 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012517 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012518 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012519 case OMPC_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012520 llvm_unreachable("Clause is not allowed.");
12521 }
12522 return Res;
12523}
12524
Alexey Bataev236070f2014-06-20 11:19:47 +000012525OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12526 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012527 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012528 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12529}
12530
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012531OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12532 SourceLocation EndLoc) {
12533 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12534}
12535
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012536OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12537 SourceLocation EndLoc) {
12538 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12539}
12540
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012541OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12542 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012543 return new (Context) OMPReadClause(StartLoc, EndLoc);
12544}
12545
Alexey Bataevdea47612014-07-23 07:46:59 +000012546OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12547 SourceLocation EndLoc) {
12548 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12549}
12550
Alexey Bataev67a4f222014-07-23 10:25:33 +000012551OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12552 SourceLocation EndLoc) {
12553 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12554}
12555
Alexey Bataev459dec02014-07-24 06:46:57 +000012556OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12557 SourceLocation EndLoc) {
12558 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12559}
12560
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012561OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12562 SourceLocation EndLoc) {
12563 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12564}
12565
Alexey Bataevea9166b2020-02-06 16:30:23 -050012566OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
12567 SourceLocation EndLoc) {
12568 return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
12569}
12570
Alexey Bataev04a830f2020-02-10 14:30:39 -050012571OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
12572 SourceLocation EndLoc) {
12573 return new (Context) OMPAcquireClause(StartLoc, EndLoc);
12574}
12575
Alexey Bataev95598342020-02-10 15:49:05 -050012576OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
12577 SourceLocation EndLoc) {
12578 return new (Context) OMPReleaseClause(StartLoc, EndLoc);
12579}
12580
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012581OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
12582 SourceLocation EndLoc) {
12583 return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
12584}
12585
Alexey Bataev346265e2015-09-25 10:37:12 +000012586OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12587 SourceLocation EndLoc) {
12588 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12589}
12590
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012591OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12592 SourceLocation EndLoc) {
12593 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12594}
12595
Alexey Bataevb825de12015-12-07 10:51:44 +000012596OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12597 SourceLocation EndLoc) {
12598 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12599}
12600
Kelvin Li1408f912018-09-26 04:28:39 +000012601OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12602 SourceLocation EndLoc) {
12603 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12604}
12605
Patrick Lyster4a370b92018-10-01 13:47:43 +000012606OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12607 SourceLocation EndLoc) {
12608 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12609}
12610
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012611OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12612 SourceLocation EndLoc) {
12613 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12614}
12615
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012616OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12617 SourceLocation EndLoc) {
12618 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12619}
12620
Alexey Bataevc5e02582014-06-16 07:08:35 +000012621OMPClause *Sema::ActOnOpenMPVarListClause(
12622 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012623 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12624 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012625 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
Kelvin Lief579432018-12-18 22:18:41 +000012626 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012627 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
12628 SourceLocation DepLinMapLastLoc) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012629 SourceLocation StartLoc = Locs.StartLoc;
12630 SourceLocation LParenLoc = Locs.LParenLoc;
12631 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012632 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012633 switch (Kind) {
12634 case OMPC_private:
12635 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12636 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012637 case OMPC_firstprivate:
12638 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12639 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012640 case OMPC_lastprivate:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012641 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
12642 "Unexpected lastprivate modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012643 Res = ActOnOpenMPLastprivateClause(
12644 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
12645 DepLinMapLastLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012646 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012647 case OMPC_shared:
12648 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12649 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012650 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012651 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012652 EndLoc, ReductionOrMapperIdScopeSpec,
12653 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012654 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012655 case OMPC_task_reduction:
12656 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012657 EndLoc, ReductionOrMapperIdScopeSpec,
12658 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012659 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012660 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012661 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12662 EndLoc, ReductionOrMapperIdScopeSpec,
12663 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012664 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012665 case OMPC_linear:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012666 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
12667 "Unexpected linear modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012668 Res = ActOnOpenMPLinearClause(
12669 VarList, TailExpr, StartLoc, LParenLoc,
12670 static_cast<OpenMPLinearClauseKind>(ExtraModifier), DepLinMapLastLoc,
12671 ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012672 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012673 case OMPC_aligned:
12674 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12675 ColonLoc, EndLoc);
12676 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012677 case OMPC_copyin:
12678 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12679 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012680 case OMPC_copyprivate:
12681 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12682 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012683 case OMPC_flush:
12684 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12685 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012686 case OMPC_depend:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012687 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
12688 "Unexpected depend modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012689 Res = ActOnOpenMPDependClause(
12690 static_cast<OpenMPDependClauseKind>(ExtraModifier), DepLinMapLastLoc,
12691 ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012692 break;
12693 case OMPC_map:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012694 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
12695 "Unexpected map modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012696 Res = ActOnOpenMPMapClause(
12697 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
12698 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
12699 IsMapTypeImplicit, DepLinMapLastLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012700 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012701 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012702 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12703 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012704 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012705 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012706 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12707 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012708 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012709 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012710 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012711 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012712 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012713 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012714 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012715 case OMPC_allocate:
12716 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12717 ColonLoc, EndLoc);
12718 break;
Alexey Bataevb6e70842019-12-16 15:54:17 -050012719 case OMPC_nontemporal:
12720 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
12721 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012722 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012723 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012724 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012725 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012726 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012727 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012728 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012729 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012730 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012731 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012732 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012733 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012734 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012735 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012736 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012737 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012738 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012739 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012740 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012741 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050012742 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050012743 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050012744 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012745 case OMPC_relaxed:
Michael Wonge710d542015-08-07 16:16:36 +000012746 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012747 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012748 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012749 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012750 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012751 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012752 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012753 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012754 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012755 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012756 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012757 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012758 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012759 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012760 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012761 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012762 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012763 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012764 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012765 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012766 case OMPC_match:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012767 case OMPC_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012768 llvm_unreachable("Clause is not allowed.");
12769 }
12770 return Res;
12771}
12772
Alexey Bataev90c228f2016-02-08 09:29:13 +000012773ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012774 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012775 ExprResult Res = BuildDeclRefExpr(
12776 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12777 if (!Res.isUsable())
12778 return ExprError();
12779 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12780 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12781 if (!Res.isUsable())
12782 return ExprError();
12783 }
12784 if (VK != VK_LValue && Res.get()->isGLValue()) {
12785 Res = DefaultLvalueConversion(Res.get());
12786 if (!Res.isUsable())
12787 return ExprError();
12788 }
12789 return Res;
12790}
12791
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012792OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12793 SourceLocation StartLoc,
12794 SourceLocation LParenLoc,
12795 SourceLocation EndLoc) {
12796 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012797 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012798 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012799 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012800 SourceLocation ELoc;
12801 SourceRange ERange;
12802 Expr *SimpleRefExpr = RefExpr;
12803 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012804 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012805 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012806 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012807 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012808 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012809 ValueDecl *D = Res.first;
12810 if (!D)
12811 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012812
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012813 QualType Type = D->getType();
12814 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012815
12816 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12817 // A variable that appears in a private clause must not have an incomplete
12818 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012819 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012820 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012821 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012822
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012823 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12824 // A variable that is privatized must not have a const-qualified type
12825 // unless it is of class type with a mutable member. This restriction does
12826 // not apply to the firstprivate clause.
12827 //
12828 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12829 // A variable that appears in a private clause must not have a
12830 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012831 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012832 continue;
12833
Alexey Bataev758e55e2013-09-06 18:03:48 +000012834 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12835 // in a Construct]
12836 // Variables with the predetermined data-sharing attributes may not be
12837 // listed in data-sharing attributes clauses, except for the cases
12838 // listed below. For these exceptions only, listing a predetermined
12839 // variable in a data-sharing attribute clause is allowed and overrides
12840 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012841 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012842 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012843 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12844 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012845 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012846 continue;
12847 }
12848
Alexey Bataeve3727102018-04-18 15:57:46 +000012849 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012850 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012851 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012852 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012853 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12854 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012855 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012856 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012857 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012858 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012859 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012860 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012861 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012862 continue;
12863 }
12864
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012865 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12866 // A list item cannot appear in both a map clause and a data-sharing
12867 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012868 //
12869 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12870 // A list item cannot appear in both a map clause and a data-sharing
12871 // attribute clause on the same construct unless the construct is a
12872 // combined construct.
12873 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12874 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012875 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012876 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012877 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012878 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12879 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12880 ConflictKind = WhereFoundClauseKind;
12881 return true;
12882 })) {
12883 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012884 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012885 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012886 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012887 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012888 continue;
12889 }
12890 }
12891
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012892 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12893 // A variable of class type (or array thereof) that appears in a private
12894 // clause requires an accessible, unambiguous default constructor for the
12895 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012896 // Generate helper private variable and initialize it with the default
12897 // value. The address of the original variable is replaced by the address of
12898 // the new private variable in CodeGen. This new variable is not added to
12899 // IdResolver, so the code in the OpenMP region uses original variable for
12900 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012901 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012902 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012903 buildVarDecl(*this, ELoc, Type, D->getName(),
12904 D->hasAttrs() ? &D->getAttrs() : nullptr,
12905 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012906 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012907 if (VDPrivate->isInvalidDecl())
12908 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012909 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012910 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012911
Alexey Bataev90c228f2016-02-08 09:29:13 +000012912 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012913 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012914 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012915 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012916 Vars.push_back((VD || CurContext->isDependentContext())
12917 ? RefExpr->IgnoreParens()
12918 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012919 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012920 }
12921
Alexey Bataeved09d242014-05-28 05:53:51 +000012922 if (Vars.empty())
12923 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012924
Alexey Bataev03b340a2014-10-21 03:16:40 +000012925 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12926 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012927}
12928
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012929namespace {
12930class DiagsUninitializedSeveretyRAII {
12931private:
12932 DiagnosticsEngine &Diags;
12933 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012934 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012935
12936public:
12937 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12938 bool IsIgnored)
12939 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12940 if (!IsIgnored) {
12941 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12942 /*Map*/ diag::Severity::Ignored, Loc);
12943 }
12944 }
12945 ~DiagsUninitializedSeveretyRAII() {
12946 if (!IsIgnored)
12947 Diags.popMappings(SavedLoc);
12948 }
12949};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012950}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012951
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012952OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12953 SourceLocation StartLoc,
12954 SourceLocation LParenLoc,
12955 SourceLocation EndLoc) {
12956 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012957 SmallVector<Expr *, 8> PrivateCopies;
12958 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012959 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012960 bool IsImplicitClause =
12961 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012962 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012963
Alexey Bataeve3727102018-04-18 15:57:46 +000012964 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012965 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012966 SourceLocation ELoc;
12967 SourceRange ERange;
12968 Expr *SimpleRefExpr = RefExpr;
12969 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012970 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012971 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012972 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012973 PrivateCopies.push_back(nullptr);
12974 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012975 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012976 ValueDecl *D = Res.first;
12977 if (!D)
12978 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012979
Alexey Bataev60da77e2016-02-29 05:54:20 +000012980 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012981 QualType Type = D->getType();
12982 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012983
12984 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12985 // A variable that appears in a private clause must not have an incomplete
12986 // type or a reference type.
12987 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012988 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012989 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012990 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012991
12992 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12993 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012994 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012995 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012996 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012997
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012998 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012999 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013000 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013001 DSAStackTy::DSAVarData DVar =
13002 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000013003 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013004 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013005 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013006 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
13007 // A list item that specifies a given variable may not appear in more
13008 // than one clause on the same directive, except that a variable may be
13009 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013010 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13011 // A list item may appear in a firstprivate or lastprivate clause but not
13012 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013013 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000013014 (isOpenMPDistributeDirective(CurrDir) ||
13015 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013016 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013017 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000013018 << getOpenMPClauseName(DVar.CKind)
13019 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013020 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013021 continue;
13022 }
13023
13024 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13025 // in a Construct]
13026 // Variables with the predetermined data-sharing attributes may not be
13027 // listed in data-sharing attributes clauses, except for the cases
13028 // listed below. For these exceptions only, listing a predetermined
13029 // variable in a data-sharing attribute clause is allowed and overrides
13030 // the variable's predetermined data-sharing attributes.
13031 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13032 // in a Construct, C/C++, p.2]
13033 // Variables with const-qualified type having no mutable member may be
13034 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000013035 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013036 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
13037 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000013038 << getOpenMPClauseName(DVar.CKind)
13039 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013040 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013041 continue;
13042 }
13043
13044 // OpenMP [2.9.3.4, Restrictions, p.2]
13045 // A list item that is private within a parallel region must not appear
13046 // in a firstprivate clause on a worksharing construct if any of the
13047 // worksharing regions arising from the worksharing construct ever bind
13048 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013049 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13050 // A list item that is private within a teams region must not appear in a
13051 // firstprivate clause on a distribute construct if any of the distribute
13052 // regions arising from the distribute construct ever bind to any of the
13053 // teams regions arising from the teams construct.
13054 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13055 // A list item that appears in a reduction clause of a teams construct
13056 // must not appear in a firstprivate clause on a distribute construct if
13057 // any of the distribute regions arising from the distribute construct
13058 // ever bind to any of the teams regions arising from the teams construct.
13059 if ((isOpenMPWorksharingDirective(CurrDir) ||
13060 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013061 !isOpenMPParallelDirective(CurrDir) &&
13062 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000013063 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013064 if (DVar.CKind != OMPC_shared &&
13065 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013066 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013067 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000013068 Diag(ELoc, diag::err_omp_required_access)
13069 << getOpenMPClauseName(OMPC_firstprivate)
13070 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013071 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013072 continue;
13073 }
13074 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013075 // OpenMP [2.9.3.4, Restrictions, p.3]
13076 // A list item that appears in a reduction clause of a parallel construct
13077 // must not appear in a firstprivate clause on a worksharing or task
13078 // construct if any of the worksharing or task regions arising from the
13079 // worksharing or task construct ever bind to any of the parallel regions
13080 // arising from the parallel construct.
13081 // OpenMP [2.9.3.4, Restrictions, p.4]
13082 // A list item that appears in a reduction clause in worksharing
13083 // construct must not appear in a firstprivate clause in a task construct
13084 // encountered during execution of any of the worksharing regions arising
13085 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000013086 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013087 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013088 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
13089 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013090 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013091 isOpenMPWorksharingDirective(K) ||
13092 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013093 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013094 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013095 if (DVar.CKind == OMPC_reduction &&
13096 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013097 isOpenMPWorksharingDirective(DVar.DKind) ||
13098 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013099 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
13100 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013101 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013102 continue;
13103 }
13104 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000013105
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013106 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13107 // A list item cannot appear in both a map clause and a data-sharing
13108 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000013109 //
13110 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
13111 // A list item cannot appear in both a map clause and a data-sharing
13112 // attribute clause on the same construct unless the construct is a
13113 // combined construct.
13114 if ((LangOpts.OpenMP <= 45 &&
13115 isOpenMPTargetExecutionDirective(CurrDir)) ||
13116 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000013117 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000013118 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013119 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000013120 [&ConflictKind](
13121 OMPClauseMappableExprCommon::MappableExprComponentListRef,
13122 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000013123 ConflictKind = WhereFoundClauseKind;
13124 return true;
13125 })) {
13126 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013127 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000013128 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013129 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013130 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013131 continue;
13132 }
13133 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013134 }
13135
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013136 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000013137 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000013138 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013139 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
13140 << getOpenMPClauseName(OMPC_firstprivate) << Type
13141 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13142 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000013143 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013144 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000013145 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013146 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000013147 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013148 continue;
13149 }
13150
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013151 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013152 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013153 buildVarDecl(*this, ELoc, Type, D->getName(),
13154 D->hasAttrs() ? &D->getAttrs() : nullptr,
13155 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013156 // Generate helper private variable and initialize it with the value of the
13157 // original variable. The address of the original variable is replaced by
13158 // the address of the new private variable in the CodeGen. This new variable
13159 // is not added to IdResolver, so the code in the OpenMP region uses
13160 // original variable for proper diagnostics and variable capturing.
13161 Expr *VDInitRefExpr = nullptr;
13162 // For arrays generate initializer for single element and replace it by the
13163 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013164 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013165 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000013166 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013167 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013168 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013169 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013170 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
13171 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000013172 InitializedEntity Entity =
13173 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013174 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
13175
13176 InitializationSequence InitSeq(*this, Entity, Kind, Init);
13177 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
13178 if (Result.isInvalid())
13179 VDPrivate->setInvalidDecl();
13180 else
13181 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013182 // Remove temp variable declaration.
13183 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013184 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000013185 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
13186 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000013187 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13188 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000013189 AddInitializerToDecl(VDPrivate,
13190 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013191 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013192 }
13193 if (VDPrivate->isInvalidDecl()) {
13194 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000013195 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013196 diag::note_omp_task_predetermined_firstprivate_here);
13197 }
13198 continue;
13199 }
13200 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013201 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000013202 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
13203 RefExpr->getExprLoc());
13204 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013205 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013206 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013207 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013208 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013209 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013210 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013211 ExprCaptures.push_back(Ref->getDecl());
13212 }
Alexey Bataev417089f2016-02-17 13:19:37 +000013213 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000013214 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013215 Vars.push_back((VD || CurContext->isDependentContext())
13216 ? RefExpr->IgnoreParens()
13217 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013218 PrivateCopies.push_back(VDPrivateRefExpr);
13219 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013220 }
13221
Alexey Bataeved09d242014-05-28 05:53:51 +000013222 if (Vars.empty())
13223 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013224
13225 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013226 Vars, PrivateCopies, Inits,
13227 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013228}
13229
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013230OMPClause *Sema::ActOnOpenMPLastprivateClause(
13231 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
13232 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
13233 SourceLocation LParenLoc, SourceLocation EndLoc) {
13234 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
13235 assert(ColonLoc.isValid() && "Colon location must be valid.");
13236 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
13237 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
13238 /*Last=*/OMPC_LASTPRIVATE_unknown)
13239 << getOpenMPClauseName(OMPC_lastprivate);
13240 return nullptr;
13241 }
13242
Alexander Musman1bb328c2014-06-04 13:06:39 +000013243 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000013244 SmallVector<Expr *, 8> SrcExprs;
13245 SmallVector<Expr *, 8> DstExprs;
13246 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000013247 SmallVector<Decl *, 4> ExprCaptures;
13248 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000013249 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013250 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013251 SourceLocation ELoc;
13252 SourceRange ERange;
13253 Expr *SimpleRefExpr = RefExpr;
13254 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000013255 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013256 // It will be analyzed later.
13257 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013258 SrcExprs.push_back(nullptr);
13259 DstExprs.push_back(nullptr);
13260 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013261 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013262 ValueDecl *D = Res.first;
13263 if (!D)
13264 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013265
Alexey Bataev74caaf22016-02-20 04:09:36 +000013266 QualType Type = D->getType();
13267 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013268
13269 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
13270 // A variable that appears in a lastprivate clause must not have an
13271 // incomplete type or a reference type.
13272 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000013273 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000013274 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013275 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013276
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013277 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13278 // A variable that is privatized must not have a const-qualified type
13279 // unless it is of class type with a mutable member. This restriction does
13280 // not apply to the firstprivate clause.
13281 //
13282 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
13283 // A variable that appears in a lastprivate clause must not have a
13284 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013285 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013286 continue;
13287
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013288 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
13289 // A list item that appears in a lastprivate clause with the conditional
13290 // modifier must be a scalar variable.
13291 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
13292 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
13293 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13294 VarDecl::DeclarationOnly;
13295 Diag(D->getLocation(),
13296 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13297 << D;
13298 continue;
13299 }
13300
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013301 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013302 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13303 // in a Construct]
13304 // Variables with the predetermined data-sharing attributes may not be
13305 // listed in data-sharing attributes clauses, except for the cases
13306 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013307 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13308 // A list item may appear in a firstprivate or lastprivate clause but not
13309 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000013310 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013311 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000013312 (isOpenMPDistributeDirective(CurrDir) ||
13313 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000013314 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
13315 Diag(ELoc, diag::err_omp_wrong_dsa)
13316 << getOpenMPClauseName(DVar.CKind)
13317 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013318 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013319 continue;
13320 }
13321
Alexey Bataevf29276e2014-06-18 04:14:57 +000013322 // OpenMP [2.14.3.5, Restrictions, p.2]
13323 // A list item that is private within a parallel region, or that appears in
13324 // the reduction clause of a parallel construct, must not appear in a
13325 // lastprivate clause on a worksharing construct if any of the corresponding
13326 // worksharing regions ever binds to any of the corresponding parallel
13327 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000013328 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000013329 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013330 !isOpenMPParallelDirective(CurrDir) &&
13331 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000013332 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013333 if (DVar.CKind != OMPC_shared) {
13334 Diag(ELoc, diag::err_omp_required_access)
13335 << getOpenMPClauseName(OMPC_lastprivate)
13336 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013337 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013338 continue;
13339 }
13340 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013341
Alexander Musman1bb328c2014-06-04 13:06:39 +000013342 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000013343 // A variable of class type (or array thereof) that appears in a
13344 // lastprivate clause requires an accessible, unambiguous default
13345 // constructor for the class type, unless the list item is also specified
13346 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000013347 // A variable of class type (or array thereof) that appears in a
13348 // lastprivate clause requires an accessible, unambiguous copy assignment
13349 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000013350 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013351 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
13352 Type.getUnqualifiedType(), ".lastprivate.src",
13353 D->hasAttrs() ? &D->getAttrs() : nullptr);
13354 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000013355 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013356 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013357 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000013358 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013359 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000013360 // For arrays generate assignment operation for single element and replace
13361 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013362 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
13363 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013364 if (AssignmentOp.isInvalid())
13365 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013366 AssignmentOp =
13367 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000013368 if (AssignmentOp.isInvalid())
13369 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013370
Alexey Bataev74caaf22016-02-20 04:09:36 +000013371 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013372 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013373 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013374 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013375 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013376 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013377 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013378 ExprCaptures.push_back(Ref->getDecl());
13379 }
13380 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013381 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013382 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013383 ExprResult RefRes = DefaultLvalueConversion(Ref);
13384 if (!RefRes.isUsable())
13385 continue;
13386 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013387 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13388 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013389 if (!PostUpdateRes.isUsable())
13390 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013391 ExprPostUpdates.push_back(
13392 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013393 }
13394 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013395 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013396 Vars.push_back((VD || CurContext->isDependentContext())
13397 ? RefExpr->IgnoreParens()
13398 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000013399 SrcExprs.push_back(PseudoSrcExpr);
13400 DstExprs.push_back(PseudoDstExpr);
13401 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000013402 }
13403
13404 if (Vars.empty())
13405 return nullptr;
13406
13407 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000013408 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013409 LPKind, LPKindLoc, ColonLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013410 buildPreInits(Context, ExprCaptures),
13411 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000013412}
13413
Alexey Bataev758e55e2013-09-06 18:03:48 +000013414OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
13415 SourceLocation StartLoc,
13416 SourceLocation LParenLoc,
13417 SourceLocation EndLoc) {
13418 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013419 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013420 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013421 SourceLocation ELoc;
13422 SourceRange ERange;
13423 Expr *SimpleRefExpr = RefExpr;
13424 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013425 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000013426 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013427 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013428 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013429 ValueDecl *D = Res.first;
13430 if (!D)
13431 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013432
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013433 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013434 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13435 // in a Construct]
13436 // Variables with the predetermined data-sharing attributes may not be
13437 // listed in data-sharing attributes clauses, except for the cases
13438 // listed below. For these exceptions only, listing a predetermined
13439 // variable in a data-sharing attribute clause is allowed and overrides
13440 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000013441 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000013442 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
13443 DVar.RefExpr) {
13444 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13445 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013446 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013447 continue;
13448 }
13449
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013450 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013451 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000013452 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013453 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013454 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
13455 ? RefExpr->IgnoreParens()
13456 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013457 }
13458
Alexey Bataeved09d242014-05-28 05:53:51 +000013459 if (Vars.empty())
13460 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013461
13462 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13463}
13464
Alexey Bataevc5e02582014-06-16 07:08:35 +000013465namespace {
13466class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13467 DSAStackTy *Stack;
13468
13469public:
13470 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013471 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13472 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013473 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13474 return false;
13475 if (DVar.CKind != OMPC_unknown)
13476 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013477 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013478 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013479 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013480 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013481 }
13482 return false;
13483 }
13484 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013485 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013486 if (Child && Visit(Child))
13487 return true;
13488 }
13489 return false;
13490 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013491 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013492};
Alexey Bataev23b69422014-06-18 07:08:49 +000013493} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013494
Alexey Bataev60da77e2016-02-29 05:54:20 +000013495namespace {
13496// Transform MemberExpression for specified FieldDecl of current class to
13497// DeclRefExpr to specified OMPCapturedExprDecl.
13498class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13499 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013500 ValueDecl *Field = nullptr;
13501 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013502
13503public:
13504 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13505 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13506
13507 ExprResult TransformMemberExpr(MemberExpr *E) {
13508 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13509 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013510 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013511 return CapturedExpr;
13512 }
13513 return BaseTransform::TransformMemberExpr(E);
13514 }
13515 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13516};
13517} // namespace
13518
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013519template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013520static T filterLookupForUDReductionAndMapper(
13521 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013522 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013523 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013524 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013525 return Res;
13526 }
13527 }
13528 return T();
13529}
13530
Alexey Bataev43b90b72018-09-12 16:31:59 +000013531static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13532 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13533
13534 for (auto RD : D->redecls()) {
13535 // Don't bother with extra checks if we already know this one isn't visible.
13536 if (RD == D)
13537 continue;
13538
13539 auto ND = cast<NamedDecl>(RD);
13540 if (LookupResult::isVisible(SemaRef, ND))
13541 return ND;
13542 }
13543
13544 return nullptr;
13545}
13546
13547static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013548argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013549 SourceLocation Loc, QualType Ty,
13550 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13551 // Find all of the associated namespaces and classes based on the
13552 // arguments we have.
13553 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13554 Sema::AssociatedClassSet AssociatedClasses;
13555 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13556 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13557 AssociatedClasses);
13558
13559 // C++ [basic.lookup.argdep]p3:
13560 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13561 // and let Y be the lookup set produced by argument dependent
13562 // lookup (defined as follows). If X contains [...] then Y is
13563 // empty. Otherwise Y is the set of declarations found in the
13564 // namespaces associated with the argument types as described
13565 // below. The set of declarations found by the lookup of the name
13566 // is the union of X and Y.
13567 //
13568 // Here, we compute Y and add its members to the overloaded
13569 // candidate set.
13570 for (auto *NS : AssociatedNamespaces) {
13571 // When considering an associated namespace, the lookup is the
13572 // same as the lookup performed when the associated namespace is
13573 // used as a qualifier (3.4.3.2) except that:
13574 //
13575 // -- Any using-directives in the associated namespace are
13576 // ignored.
13577 //
13578 // -- Any namespace-scope friend functions declared in
13579 // associated classes are visible within their respective
13580 // namespaces even if they are not visible during an ordinary
13581 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013582 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013583 for (auto *D : R) {
13584 auto *Underlying = D;
13585 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13586 Underlying = USD->getTargetDecl();
13587
Michael Kruse4304e9d2019-02-19 16:38:20 +000013588 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13589 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013590 continue;
13591
13592 if (!SemaRef.isVisible(D)) {
13593 D = findAcceptableDecl(SemaRef, D);
13594 if (!D)
13595 continue;
13596 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13597 Underlying = USD->getTargetDecl();
13598 }
13599 Lookups.emplace_back();
13600 Lookups.back().addDecl(Underlying);
13601 }
13602 }
13603}
13604
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013605static ExprResult
13606buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13607 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13608 const DeclarationNameInfo &ReductionId, QualType Ty,
13609 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13610 if (ReductionIdScopeSpec.isInvalid())
13611 return ExprError();
13612 SmallVector<UnresolvedSet<8>, 4> Lookups;
13613 if (S) {
13614 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13615 Lookup.suppressDiagnostics();
13616 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013617 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013618 do {
13619 S = S->getParent();
13620 } while (S && !S->isDeclScope(D));
13621 if (S)
13622 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013623 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013624 Lookups.back().append(Lookup.begin(), Lookup.end());
13625 Lookup.clear();
13626 }
13627 } else if (auto *ULE =
13628 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13629 Lookups.push_back(UnresolvedSet<8>());
13630 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013631 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013632 if (D == PrevD)
13633 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013634 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013635 Lookups.back().addDecl(DRD);
13636 PrevD = D;
13637 }
13638 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013639 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13640 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013641 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013642 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013643 return !D->isInvalidDecl() &&
13644 (D->getType()->isDependentType() ||
13645 D->getType()->isInstantiationDependentType() ||
13646 D->getType()->containsUnexpandedParameterPack());
13647 })) {
13648 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013649 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013650 if (Set.empty())
13651 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013652 ResSet.append(Set.begin(), Set.end());
13653 // The last item marks the end of all declarations at the specified scope.
13654 ResSet.addDecl(Set[Set.size() - 1]);
13655 }
13656 return UnresolvedLookupExpr::Create(
13657 SemaRef.Context, /*NamingClass=*/nullptr,
13658 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13659 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13660 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013661 // Lookup inside the classes.
13662 // C++ [over.match.oper]p3:
13663 // For a unary operator @ with an operand of a type whose
13664 // cv-unqualified version is T1, and for a binary operator @ with
13665 // a left operand of a type whose cv-unqualified version is T1 and
13666 // a right operand of a type whose cv-unqualified version is T2,
13667 // three sets of candidate functions, designated member
13668 // candidates, non-member candidates and built-in candidates, are
13669 // constructed as follows:
13670 // -- If T1 is a complete class type or a class currently being
13671 // defined, the set of member candidates is the result of the
13672 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13673 // the set of member candidates is empty.
13674 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13675 Lookup.suppressDiagnostics();
13676 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13677 // Complete the type if it can be completed.
13678 // If the type is neither complete nor being defined, bail out now.
13679 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13680 TyRec->getDecl()->getDefinition()) {
13681 Lookup.clear();
13682 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13683 if (Lookup.empty()) {
13684 Lookups.emplace_back();
13685 Lookups.back().append(Lookup.begin(), Lookup.end());
13686 }
13687 }
13688 }
13689 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013690 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013691 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013692 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13693 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13694 if (!D->isInvalidDecl() &&
13695 SemaRef.Context.hasSameType(D->getType(), Ty))
13696 return D;
13697 return nullptr;
13698 }))
13699 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13700 VK_LValue, Loc);
13701 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013702 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13703 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13704 if (!D->isInvalidDecl() &&
13705 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13706 !Ty.isMoreQualifiedThan(D->getType()))
13707 return D;
13708 return nullptr;
13709 })) {
13710 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13711 /*DetectVirtual=*/false);
13712 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13713 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13714 VD->getType().getUnqualifiedType()))) {
13715 if (SemaRef.CheckBaseClassAccess(
13716 Loc, VD->getType(), Ty, Paths.front(),
13717 /*DiagID=*/0) != Sema::AR_inaccessible) {
13718 SemaRef.BuildBasePathArray(Paths, BasePath);
13719 return SemaRef.BuildDeclRefExpr(
13720 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13721 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013722 }
13723 }
13724 }
13725 }
13726 if (ReductionIdScopeSpec.isSet()) {
Alexey Bataevadd743b2020-01-03 11:58:16 -050013727 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
13728 << Ty << Range;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013729 return ExprError();
13730 }
13731 return ExprEmpty();
13732}
13733
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013734namespace {
13735/// Data for the reduction-based clauses.
13736struct ReductionData {
13737 /// List of original reduction items.
13738 SmallVector<Expr *, 8> Vars;
13739 /// List of private copies of the reduction items.
13740 SmallVector<Expr *, 8> Privates;
13741 /// LHS expressions for the reduction_op expressions.
13742 SmallVector<Expr *, 8> LHSs;
13743 /// RHS expressions for the reduction_op expressions.
13744 SmallVector<Expr *, 8> RHSs;
13745 /// Reduction operation expression.
13746 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013747 /// Taskgroup descriptors for the corresponding reduction items in
13748 /// in_reduction clauses.
13749 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013750 /// List of captures for clause.
13751 SmallVector<Decl *, 4> ExprCaptures;
13752 /// List of postupdate expressions.
13753 SmallVector<Expr *, 4> ExprPostUpdates;
13754 ReductionData() = delete;
13755 /// Reserves required memory for the reduction data.
13756 ReductionData(unsigned Size) {
13757 Vars.reserve(Size);
13758 Privates.reserve(Size);
13759 LHSs.reserve(Size);
13760 RHSs.reserve(Size);
13761 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013762 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013763 ExprCaptures.reserve(Size);
13764 ExprPostUpdates.reserve(Size);
13765 }
13766 /// Stores reduction item and reduction operation only (required for dependent
13767 /// reduction item).
13768 void push(Expr *Item, Expr *ReductionOp) {
13769 Vars.emplace_back(Item);
13770 Privates.emplace_back(nullptr);
13771 LHSs.emplace_back(nullptr);
13772 RHSs.emplace_back(nullptr);
13773 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013774 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013775 }
13776 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013777 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13778 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013779 Vars.emplace_back(Item);
13780 Privates.emplace_back(Private);
13781 LHSs.emplace_back(LHS);
13782 RHSs.emplace_back(RHS);
13783 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013784 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013785 }
13786};
13787} // namespace
13788
Alexey Bataeve3727102018-04-18 15:57:46 +000013789static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013790 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13791 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13792 const Expr *Length = OASE->getLength();
13793 if (Length == nullptr) {
13794 // For array sections of the form [1:] or [:], we would need to analyze
13795 // the lower bound...
13796 if (OASE->getColonLoc().isValid())
13797 return false;
13798
13799 // This is an array subscript which has implicit length 1!
13800 SingleElement = true;
13801 ArraySizes.push_back(llvm::APSInt::get(1));
13802 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013803 Expr::EvalResult Result;
13804 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013805 return false;
13806
Fangrui Song407659a2018-11-30 23:41:18 +000013807 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013808 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13809 ArraySizes.push_back(ConstantLengthValue);
13810 }
13811
13812 // Get the base of this array section and walk up from there.
13813 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13814
13815 // We require length = 1 for all array sections except the right-most to
13816 // guarantee that the memory region is contiguous and has no holes in it.
13817 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13818 Length = TempOASE->getLength();
13819 if (Length == nullptr) {
13820 // For array sections of the form [1:] or [:], we would need to analyze
13821 // the lower bound...
13822 if (OASE->getColonLoc().isValid())
13823 return false;
13824
13825 // This is an array subscript which has implicit length 1!
13826 ArraySizes.push_back(llvm::APSInt::get(1));
13827 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013828 Expr::EvalResult Result;
13829 if (!Length->EvaluateAsInt(Result, Context))
13830 return false;
13831
13832 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13833 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013834 return false;
13835
13836 ArraySizes.push_back(ConstantLengthValue);
13837 }
13838 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13839 }
13840
13841 // If we have a single element, we don't need to add the implicit lengths.
13842 if (!SingleElement) {
13843 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13844 // Has implicit length 1!
13845 ArraySizes.push_back(llvm::APSInt::get(1));
13846 Base = TempASE->getBase()->IgnoreParenImpCasts();
13847 }
13848 }
13849
13850 // This array section can be privatized as a single value or as a constant
13851 // sized array.
13852 return true;
13853}
13854
Alexey Bataeve3727102018-04-18 15:57:46 +000013855static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013856 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13857 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13858 SourceLocation ColonLoc, SourceLocation EndLoc,
13859 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013860 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013861 DeclarationName DN = ReductionId.getName();
13862 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013863 BinaryOperatorKind BOK = BO_Comma;
13864
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013865 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013866 // OpenMP [2.14.3.6, reduction clause]
13867 // C
13868 // reduction-identifier is either an identifier or one of the following
13869 // operators: +, -, *, &, |, ^, && and ||
13870 // C++
13871 // reduction-identifier is either an id-expression or one of the following
13872 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013873 switch (OOK) {
13874 case OO_Plus:
13875 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013876 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013877 break;
13878 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013879 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013880 break;
13881 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013882 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013883 break;
13884 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013885 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013886 break;
13887 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013888 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013889 break;
13890 case OO_AmpAmp:
13891 BOK = BO_LAnd;
13892 break;
13893 case OO_PipePipe:
13894 BOK = BO_LOr;
13895 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013896 case OO_New:
13897 case OO_Delete:
13898 case OO_Array_New:
13899 case OO_Array_Delete:
13900 case OO_Slash:
13901 case OO_Percent:
13902 case OO_Tilde:
13903 case OO_Exclaim:
13904 case OO_Equal:
13905 case OO_Less:
13906 case OO_Greater:
13907 case OO_LessEqual:
13908 case OO_GreaterEqual:
13909 case OO_PlusEqual:
13910 case OO_MinusEqual:
13911 case OO_StarEqual:
13912 case OO_SlashEqual:
13913 case OO_PercentEqual:
13914 case OO_CaretEqual:
13915 case OO_AmpEqual:
13916 case OO_PipeEqual:
13917 case OO_LessLess:
13918 case OO_GreaterGreater:
13919 case OO_LessLessEqual:
13920 case OO_GreaterGreaterEqual:
13921 case OO_EqualEqual:
13922 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013923 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013924 case OO_PlusPlus:
13925 case OO_MinusMinus:
13926 case OO_Comma:
13927 case OO_ArrowStar:
13928 case OO_Arrow:
13929 case OO_Call:
13930 case OO_Subscript:
13931 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013932 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013933 case NUM_OVERLOADED_OPERATORS:
13934 llvm_unreachable("Unexpected reduction identifier");
13935 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013936 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013937 if (II->isStr("max"))
13938 BOK = BO_GT;
13939 else if (II->isStr("min"))
13940 BOK = BO_LT;
13941 }
13942 break;
13943 }
13944 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013945 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013946 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013947 else
13948 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013949 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013950
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013951 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13952 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013953 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013954 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013955 // OpenMP [2.1, C/C++]
13956 // A list item is a variable or array section, subject to the restrictions
13957 // specified in Section 2.4 on page 42 and in each of the sections
13958 // describing clauses and directives for which a list appears.
13959 // OpenMP [2.14.3.3, Restrictions, p.1]
13960 // A variable that is part of another variable (as an array or
13961 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013962 if (!FirstIter && IR != ER)
13963 ++IR;
13964 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013965 SourceLocation ELoc;
13966 SourceRange ERange;
13967 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013968 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013969 /*AllowArraySection=*/true);
13970 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013971 // Try to find 'declare reduction' corresponding construct before using
13972 // builtin/overloaded operators.
13973 QualType Type = Context.DependentTy;
13974 CXXCastPath BasePath;
13975 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013976 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013977 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013978 Expr *ReductionOp = nullptr;
13979 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013980 (DeclareReductionRef.isUnset() ||
13981 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013982 ReductionOp = DeclareReductionRef.get();
13983 // It will be analyzed later.
13984 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013985 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013986 ValueDecl *D = Res.first;
13987 if (!D)
13988 continue;
13989
Alexey Bataev88202be2017-07-27 13:20:36 +000013990 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013991 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013992 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13993 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013994 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013995 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013996 } else if (OASE) {
13997 QualType BaseType =
13998 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13999 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000014000 Type = ATy->getElementType();
14001 else
14002 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000014003 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014004 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014005 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000014006 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014007 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000014008
Alexey Bataevc5e02582014-06-16 07:08:35 +000014009 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
14010 // A variable that appears in a private clause must not have an incomplete
14011 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000014012 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014013 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014014 continue;
14015 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000014016 // A list item that appears in a reduction clause must not be
14017 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000014018 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
14019 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014020 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000014021
14022 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000014023 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
14024 // If a list-item is a reference type then it must bind to the same object
14025 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000014026 if (!ASE && !OASE) {
14027 if (VD) {
14028 VarDecl *VDDef = VD->getDefinition();
14029 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
14030 DSARefChecker Check(Stack);
14031 if (Check.Visit(VDDef->getInit())) {
14032 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
14033 << getOpenMPClauseName(ClauseKind) << ERange;
14034 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
14035 continue;
14036 }
Alexey Bataeva1764212015-09-30 09:22:36 +000014037 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000014038 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014039
Alexey Bataevbc529672018-09-28 19:33:14 +000014040 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
14041 // in a Construct]
14042 // Variables with the predetermined data-sharing attributes may not be
14043 // listed in data-sharing attributes clauses, except for the cases
14044 // listed below. For these exceptions only, listing a predetermined
14045 // variable in a data-sharing attribute clause is allowed and overrides
14046 // the variable's predetermined data-sharing attributes.
14047 // OpenMP [2.14.3.6, Restrictions, p.3]
14048 // Any number of reduction clauses can be specified on the directive,
14049 // but a list item can appear only once in the reduction clauses for that
14050 // directive.
14051 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
14052 if (DVar.CKind == OMPC_reduction) {
14053 S.Diag(ELoc, diag::err_omp_once_referenced)
14054 << getOpenMPClauseName(ClauseKind);
14055 if (DVar.RefExpr)
14056 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
14057 continue;
14058 }
14059 if (DVar.CKind != OMPC_unknown) {
14060 S.Diag(ELoc, diag::err_omp_wrong_dsa)
14061 << getOpenMPClauseName(DVar.CKind)
14062 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000014063 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014064 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000014065 }
Alexey Bataevbc529672018-09-28 19:33:14 +000014066
14067 // OpenMP [2.14.3.6, Restrictions, p.1]
14068 // A list item that appears in a reduction clause of a worksharing
14069 // construct must be shared in the parallel regions to which any of the
14070 // worksharing regions arising from the worksharing construct bind.
14071 if (isOpenMPWorksharingDirective(CurrDir) &&
14072 !isOpenMPParallelDirective(CurrDir) &&
14073 !isOpenMPTeamsDirective(CurrDir)) {
14074 DVar = Stack->getImplicitDSA(D, true);
14075 if (DVar.CKind != OMPC_shared) {
14076 S.Diag(ELoc, diag::err_omp_required_access)
14077 << getOpenMPClauseName(OMPC_reduction)
14078 << getOpenMPClauseName(OMPC_shared);
14079 reportOriginalDsa(S, Stack, D, DVar);
14080 continue;
14081 }
14082 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000014083 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014084
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014085 // Try to find 'declare reduction' corresponding construct before using
14086 // builtin/overloaded operators.
14087 CXXCastPath BasePath;
14088 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014089 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014090 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
14091 if (DeclareReductionRef.isInvalid())
14092 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014093 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014094 (DeclareReductionRef.isUnset() ||
14095 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014096 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014097 continue;
14098 }
14099 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
14100 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014101 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014102 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014103 << Type << ReductionIdRange;
14104 continue;
14105 }
14106
14107 // OpenMP [2.14.3.6, reduction clause, Restrictions]
14108 // The type of a list item that appears in a reduction clause must be valid
14109 // for the reduction-identifier. For a max or min reduction in C, the type
14110 // of the list item must be an allowed arithmetic data type: char, int,
14111 // float, double, or _Bool, possibly modified with long, short, signed, or
14112 // unsigned. For a max or min reduction in C++, the type of the list item
14113 // must be an allowed arithmetic data type: char, wchar_t, int, float,
14114 // double, or bool, possibly modified with long, short, signed, or unsigned.
14115 if (DeclareReductionRef.isUnset()) {
14116 if ((BOK == BO_GT || BOK == BO_LT) &&
14117 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014118 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
14119 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000014120 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014121 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014122 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14123 VarDecl::DeclarationOnly;
14124 S.Diag(D->getLocation(),
14125 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014126 << D;
14127 }
14128 continue;
14129 }
14130 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014131 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000014132 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
14133 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014134 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014135 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14136 VarDecl::DeclarationOnly;
14137 S.Diag(D->getLocation(),
14138 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014139 << D;
14140 }
14141 continue;
14142 }
14143 }
14144
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014145 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014146 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
14147 D->hasAttrs() ? &D->getAttrs() : nullptr);
14148 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
14149 D->hasAttrs() ? &D->getAttrs() : nullptr);
14150 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000014151
14152 // Try if we can determine constant lengths for all array sections and avoid
14153 // the VLA.
14154 bool ConstantLengthOASE = false;
14155 if (OASE) {
14156 bool SingleElement;
14157 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000014158 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000014159 Context, OASE, SingleElement, ArraySizes);
14160
14161 // If we don't have a single element, we must emit a constant array type.
14162 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014163 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000014164 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
14165 ArrayType::Normal,
14166 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000014167 }
14168 }
14169
14170 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000014171 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000014172 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000014173 if (!Context.getTargetInfo().isVLASupported()) {
14174 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
14175 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
14176 S.Diag(ELoc, diag::note_vla_unsupported);
14177 } else {
14178 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
14179 S.targetDiag(ELoc, diag::note_vla_unsupported);
14180 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000014181 continue;
14182 }
David Majnemer9d168222016-08-05 17:44:54 +000014183 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014184 // Create pseudo array type for private copy. The size for this array will
14185 // be generated during codegen.
14186 // For array subscripts or single variables Private Ty is the same as Type
14187 // (type of the variable or single array element).
14188 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014189 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000014190 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014191 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000014192 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000014193 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014194 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014195 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014196 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014197 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014198 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
14199 D->hasAttrs() ? &D->getAttrs() : nullptr,
14200 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014201 // Add initializer for private variable.
14202 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014203 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
14204 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014205 if (DeclareReductionRef.isUsable()) {
14206 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
14207 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
14208 if (DRD->getInitializer()) {
14209 Init = DRDRef;
14210 RHSVD->setInit(DRDRef);
14211 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014212 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014213 } else {
14214 switch (BOK) {
14215 case BO_Add:
14216 case BO_Xor:
14217 case BO_Or:
14218 case BO_LOr:
14219 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
14220 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014221 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014222 break;
14223 case BO_Mul:
14224 case BO_LAnd:
14225 if (Type->isScalarType() || Type->isAnyComplexType()) {
14226 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014227 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000014228 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014229 break;
14230 case BO_And: {
14231 // '&' reduction op - initializer is '~0'.
14232 QualType OrigType = Type;
14233 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
14234 Type = ComplexTy->getElementType();
14235 if (Type->isRealFloatingType()) {
14236 llvm::APFloat InitValue =
14237 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
14238 /*isIEEE=*/true);
14239 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14240 Type, ELoc);
14241 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014242 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014243 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
14244 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
14245 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14246 }
14247 if (Init && OrigType->isAnyComplexType()) {
14248 // Init = 0xFFFF + 0xFFFFi;
14249 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014250 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014251 }
14252 Type = OrigType;
14253 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014254 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014255 case BO_LT:
14256 case BO_GT: {
14257 // 'min' reduction op - initializer is 'Largest representable number in
14258 // the reduction list item type'.
14259 // 'max' reduction op - initializer is 'Least representable number in
14260 // the reduction list item type'.
14261 if (Type->isIntegerType() || Type->isPointerType()) {
14262 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014263 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014264 QualType IntTy =
14265 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
14266 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014267 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
14268 : llvm::APInt::getMinValue(Size)
14269 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
14270 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014271 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14272 if (Type->isPointerType()) {
14273 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014274 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000014275 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014276 if (CastExpr.isInvalid())
14277 continue;
14278 Init = CastExpr.get();
14279 }
14280 } else if (Type->isRealFloatingType()) {
14281 llvm::APFloat InitValue = llvm::APFloat::getLargest(
14282 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
14283 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14284 Type, ELoc);
14285 }
14286 break;
14287 }
14288 case BO_PtrMemD:
14289 case BO_PtrMemI:
14290 case BO_MulAssign:
14291 case BO_Div:
14292 case BO_Rem:
14293 case BO_Sub:
14294 case BO_Shl:
14295 case BO_Shr:
14296 case BO_LE:
14297 case BO_GE:
14298 case BO_EQ:
14299 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000014300 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014301 case BO_AndAssign:
14302 case BO_XorAssign:
14303 case BO_OrAssign:
14304 case BO_Assign:
14305 case BO_AddAssign:
14306 case BO_SubAssign:
14307 case BO_DivAssign:
14308 case BO_RemAssign:
14309 case BO_ShlAssign:
14310 case BO_ShrAssign:
14311 case BO_Comma:
14312 llvm_unreachable("Unexpected reduction operation");
14313 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014314 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014315 if (Init && DeclareReductionRef.isUnset())
14316 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
14317 else if (!Init)
14318 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014319 if (RHSVD->isInvalidDecl())
14320 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000014321 if (!RHSVD->hasInit() &&
14322 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014323 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
14324 << Type << ReductionIdRange;
14325 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14326 VarDecl::DeclarationOnly;
14327 S.Diag(D->getLocation(),
14328 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000014329 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014330 continue;
14331 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014332 // Store initializer for single element in private copy. Will be used during
14333 // codegen.
14334 PrivateVD->setInit(RHSVD->getInit());
14335 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000014336 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014337 ExprResult ReductionOp;
14338 if (DeclareReductionRef.isUsable()) {
14339 QualType RedTy = DeclareReductionRef.get()->getType();
14340 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014341 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
14342 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014343 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014344 LHS = S.DefaultLvalueConversion(LHS.get());
14345 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014346 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14347 CK_UncheckedDerivedToBase, LHS.get(),
14348 &BasePath, LHS.get()->getValueKind());
14349 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14350 CK_UncheckedDerivedToBase, RHS.get(),
14351 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014352 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014353 FunctionProtoType::ExtProtoInfo EPI;
14354 QualType Params[] = {PtrRedTy, PtrRedTy};
14355 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
14356 auto *OVE = new (Context) OpaqueValueExpr(
14357 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014358 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014359 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000014360 ReductionOp =
14361 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014362 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014363 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014364 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014365 if (ReductionOp.isUsable()) {
14366 if (BOK != BO_LT && BOK != BO_GT) {
14367 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014368 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014369 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014370 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000014371 auto *ConditionalOp = new (Context)
14372 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
14373 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014374 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014375 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014376 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014377 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014378 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014379 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
14380 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014381 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014382 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014383 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000014384 }
14385
Alexey Bataevfa312f32017-07-21 18:48:21 +000014386 // OpenMP [2.15.4.6, Restrictions, p.2]
14387 // A list item that appears in an in_reduction clause of a task construct
14388 // must appear in a task_reduction clause of a construct associated with a
14389 // taskgroup region that includes the participating task in its taskgroup
14390 // set. The construct associated with the innermost region that meets this
14391 // condition must specify the same reduction-identifier as the in_reduction
14392 // clause.
14393 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000014394 SourceRange ParentSR;
14395 BinaryOperatorKind ParentBOK;
14396 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000014397 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000014398 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014399 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
14400 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014401 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014402 Stack->getTopMostTaskgroupReductionData(
14403 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014404 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
14405 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
14406 if (!IsParentBOK && !IsParentReductionOp) {
14407 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
14408 continue;
14409 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000014410 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
14411 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
14412 IsParentReductionOp) {
14413 bool EmitError = true;
14414 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
14415 llvm::FoldingSetNodeID RedId, ParentRedId;
14416 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
14417 DeclareReductionRef.get()->Profile(RedId, Context,
14418 /*Canonical=*/true);
14419 EmitError = RedId != ParentRedId;
14420 }
14421 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014422 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000014423 diag::err_omp_reduction_identifier_mismatch)
14424 << ReductionIdRange << RefExpr->getSourceRange();
14425 S.Diag(ParentSR.getBegin(),
14426 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000014427 << ParentSR
14428 << (IsParentBOK ? ParentBOKDSA.RefExpr
14429 : ParentReductionOpDSA.RefExpr)
14430 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000014431 continue;
14432 }
14433 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014434 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
14435 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000014436 }
14437
Alexey Bataev60da77e2016-02-29 05:54:20 +000014438 DeclRefExpr *Ref = nullptr;
14439 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014440 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014441 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014442 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000014443 VarsExpr =
14444 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
14445 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000014446 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014447 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014448 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014449 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014450 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014451 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014452 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014453 if (!RefRes.isUsable())
14454 continue;
14455 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014456 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14457 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014458 if (!PostUpdateRes.isUsable())
14459 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014460 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14461 Stack->getCurrentDirective() == OMPD_taskgroup) {
14462 S.Diag(RefExpr->getExprLoc(),
14463 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014464 << RefExpr->getSourceRange();
14465 continue;
14466 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014467 RD.ExprPostUpdates.emplace_back(
14468 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014469 }
14470 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014471 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014472 // All reduction items are still marked as reduction (to do not increase
14473 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014474 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014475 if (CurrDir == OMPD_taskgroup) {
14476 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014477 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14478 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014479 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014480 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014481 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014482 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14483 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014484 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014485 return RD.Vars.empty();
14486}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014487
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014488OMPClause *Sema::ActOnOpenMPReductionClause(
14489 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14490 SourceLocation ColonLoc, SourceLocation EndLoc,
14491 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14492 ArrayRef<Expr *> UnresolvedReductions) {
14493 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014494 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014495 StartLoc, LParenLoc, ColonLoc, EndLoc,
14496 ReductionIdScopeSpec, ReductionId,
14497 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014498 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014499
Alexey Bataevc5e02582014-06-16 07:08:35 +000014500 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014501 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14502 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14503 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14504 buildPreInits(Context, RD.ExprCaptures),
14505 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014506}
14507
Alexey Bataev169d96a2017-07-18 20:17:46 +000014508OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14509 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14510 SourceLocation ColonLoc, SourceLocation EndLoc,
14511 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14512 ArrayRef<Expr *> UnresolvedReductions) {
14513 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014514 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14515 StartLoc, LParenLoc, ColonLoc, EndLoc,
14516 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014517 UnresolvedReductions, RD))
14518 return nullptr;
14519
14520 return OMPTaskReductionClause::Create(
14521 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14522 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14523 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14524 buildPreInits(Context, RD.ExprCaptures),
14525 buildPostUpdate(*this, RD.ExprPostUpdates));
14526}
14527
Alexey Bataevfa312f32017-07-21 18:48:21 +000014528OMPClause *Sema::ActOnOpenMPInReductionClause(
14529 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14530 SourceLocation ColonLoc, SourceLocation EndLoc,
14531 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14532 ArrayRef<Expr *> UnresolvedReductions) {
14533 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014534 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014535 StartLoc, LParenLoc, ColonLoc, EndLoc,
14536 ReductionIdScopeSpec, ReductionId,
14537 UnresolvedReductions, RD))
14538 return nullptr;
14539
14540 return OMPInReductionClause::Create(
14541 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14542 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014543 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014544 buildPreInits(Context, RD.ExprCaptures),
14545 buildPostUpdate(*this, RD.ExprPostUpdates));
14546}
14547
Alexey Bataevecba70f2016-04-12 11:02:11 +000014548bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14549 SourceLocation LinLoc) {
14550 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14551 LinKind == OMPC_LINEAR_unknown) {
14552 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14553 return true;
14554 }
14555 return false;
14556}
14557
Alexey Bataeve3727102018-04-18 15:57:46 +000014558bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014559 OpenMPLinearClauseKind LinKind,
14560 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014561 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014562 // A variable must not have an incomplete type or a reference type.
14563 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14564 return true;
14565 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14566 !Type->isReferenceType()) {
14567 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14568 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14569 return true;
14570 }
14571 Type = Type.getNonReferenceType();
14572
Joel E. Dennybae586f2019-01-04 22:12:13 +000014573 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14574 // A variable that is privatized must not have a const-qualified type
14575 // unless it is of class type with a mutable member. This restriction does
14576 // not apply to the firstprivate clause.
14577 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014578 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014579
14580 // A list item must be of integral or pointer type.
14581 Type = Type.getUnqualifiedType().getCanonicalType();
14582 const auto *Ty = Type.getTypePtrOrNull();
Alexey Bataev3f2e3dc2020-01-07 09:26:10 -050014583 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
14584 !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
Alexey Bataevecba70f2016-04-12 11:02:11 +000014585 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14586 if (D) {
14587 bool IsDecl =
14588 !VD ||
14589 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14590 Diag(D->getLocation(),
14591 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14592 << D;
14593 }
14594 return true;
14595 }
14596 return false;
14597}
14598
Alexey Bataev182227b2015-08-20 10:54:39 +000014599OMPClause *Sema::ActOnOpenMPLinearClause(
14600 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14601 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14602 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014603 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014604 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014605 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014606 SmallVector<Decl *, 4> ExprCaptures;
14607 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014608 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014609 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014610 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014611 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014612 SourceLocation ELoc;
14613 SourceRange ERange;
14614 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014615 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014616 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014617 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014618 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014619 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014620 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014621 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014622 ValueDecl *D = Res.first;
14623 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014624 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014625
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014626 QualType Type = D->getType();
14627 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014628
14629 // OpenMP [2.14.3.7, linear clause]
14630 // A list-item cannot appear in more than one linear clause.
14631 // A list-item that appears in a linear clause cannot appear in any
14632 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014633 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014634 if (DVar.RefExpr) {
14635 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14636 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014637 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014638 continue;
14639 }
14640
Alexey Bataevecba70f2016-04-12 11:02:11 +000014641 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014642 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014643 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014644
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014645 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014646 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014647 buildVarDecl(*this, ELoc, Type, D->getName(),
14648 D->hasAttrs() ? &D->getAttrs() : nullptr,
14649 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014650 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014651 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014652 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014653 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014654 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014655 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014656 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014657 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014658 ExprCaptures.push_back(Ref->getDecl());
14659 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14660 ExprResult RefRes = DefaultLvalueConversion(Ref);
14661 if (!RefRes.isUsable())
14662 continue;
14663 ExprResult PostUpdateRes =
14664 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14665 SimpleRefExpr, RefRes.get());
14666 if (!PostUpdateRes.isUsable())
14667 continue;
14668 ExprPostUpdates.push_back(
14669 IgnoredValueConversions(PostUpdateRes.get()).get());
14670 }
14671 }
14672 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014673 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014674 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014675 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014676 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014677 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014678 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014679 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014680
14681 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014682 Vars.push_back((VD || CurContext->isDependentContext())
14683 ? RefExpr->IgnoreParens()
14684 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014685 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014686 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014687 }
14688
14689 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014690 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014691
14692 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014693 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014694 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14695 !Step->isInstantiationDependent() &&
14696 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014697 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014698 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014699 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014700 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014701 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014702
Alexander Musman3276a272015-03-21 10:12:56 +000014703 // Build var to save the step value.
14704 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014705 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014706 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014707 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014708 ExprResult CalcStep =
14709 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014710 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014711
Alexander Musman8dba6642014-04-22 13:09:42 +000014712 // Warn about zero linear step (it would be probably better specified as
14713 // making corresponding variables 'const').
14714 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014715 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14716 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014717 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14718 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014719 if (!IsConstant && CalcStep.isUsable()) {
14720 // Calculate the step beforehand instead of doing this on each iteration.
14721 // (This is not used if the number of iterations may be kfold-ed).
14722 CalcStepExpr = CalcStep.get();
14723 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014724 }
14725
Alexey Bataev182227b2015-08-20 10:54:39 +000014726 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14727 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014728 StepExpr, CalcStepExpr,
14729 buildPreInits(Context, ExprCaptures),
14730 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014731}
14732
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014733static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14734 Expr *NumIterations, Sema &SemaRef,
14735 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014736 // Walk the vars and build update/final expressions for the CodeGen.
14737 SmallVector<Expr *, 8> Updates;
14738 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014739 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014740 Expr *Step = Clause.getStep();
14741 Expr *CalcStep = Clause.getCalcStep();
14742 // OpenMP [2.14.3.7, linear clause]
14743 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014744 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014745 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014746 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014747 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14748 bool HasErrors = false;
14749 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014750 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014751 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14752 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014753 SourceLocation ELoc;
14754 SourceRange ERange;
14755 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014756 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014757 ValueDecl *D = Res.first;
14758 if (Res.second || !D) {
14759 Updates.push_back(nullptr);
14760 Finals.push_back(nullptr);
14761 HasErrors = true;
14762 continue;
14763 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014764 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014765 // OpenMP [2.15.11, distribute simd Construct]
14766 // A list item may not appear in a linear clause, unless it is the loop
14767 // iteration variable.
14768 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14769 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14770 SemaRef.Diag(ELoc,
14771 diag::err_omp_linear_distribute_var_non_loop_iteration);
14772 Updates.push_back(nullptr);
14773 Finals.push_back(nullptr);
14774 HasErrors = true;
14775 continue;
14776 }
Alexander Musman3276a272015-03-21 10:12:56 +000014777 Expr *InitExpr = *CurInit;
14778
14779 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014780 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014781 Expr *CapturedRef;
14782 if (LinKind == OMPC_LINEAR_uval)
14783 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14784 else
14785 CapturedRef =
14786 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14787 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14788 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014789
14790 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014791 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014792 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014793 Update = buildCounterUpdate(
14794 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14795 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014796 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014797 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014798 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014799 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014800
14801 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014802 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014803 if (!Info.first)
14804 Final =
14805 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014806 InitExpr, NumIterations, Step, /*Subtract=*/false,
14807 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014808 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014809 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014810 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014811 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014812
Alexander Musman3276a272015-03-21 10:12:56 +000014813 if (!Update.isUsable() || !Final.isUsable()) {
14814 Updates.push_back(nullptr);
14815 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014816 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014817 HasErrors = true;
14818 } else {
14819 Updates.push_back(Update.get());
14820 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014821 if (!Info.first)
14822 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014823 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014824 ++CurInit;
14825 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014826 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014827 if (Expr *S = Clause.getStep())
14828 UsedExprs.push_back(S);
14829 // Fill the remaining part with the nullptr.
14830 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014831 Clause.setUpdates(Updates);
14832 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014833 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014834 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014835}
14836
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014837OMPClause *Sema::ActOnOpenMPAlignedClause(
14838 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14839 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014840 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014841 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014842 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14843 SourceLocation ELoc;
14844 SourceRange ERange;
14845 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014846 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014847 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014848 // It will be analyzed later.
14849 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014850 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014851 ValueDecl *D = Res.first;
14852 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014853 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014854
Alexey Bataev1efd1662016-03-29 10:59:56 +000014855 QualType QType = D->getType();
14856 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014857
14858 // OpenMP [2.8.1, simd construct, Restrictions]
14859 // The type of list items appearing in the aligned clause must be
14860 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014861 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014862 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014863 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014864 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014865 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014866 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014867 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014868 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014869 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014870 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014871 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014872 continue;
14873 }
14874
14875 // OpenMP [2.8.1, simd construct, Restrictions]
14876 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014877 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevb6e70842019-12-16 15:54:17 -050014878 Diag(ELoc, diag::err_omp_used_in_clause_twice)
14879 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014880 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14881 << getOpenMPClauseName(OMPC_aligned);
14882 continue;
14883 }
14884
Alexey Bataev1efd1662016-03-29 10:59:56 +000014885 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014886 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014887 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14888 Vars.push_back(DefaultFunctionArrayConversion(
14889 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14890 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014891 }
14892
14893 // OpenMP [2.8.1, simd construct, Description]
14894 // The parameter of the aligned clause, alignment, must be a constant
14895 // positive integer expression.
14896 // If no optional parameter is specified, implementation-defined default
14897 // alignments for SIMD instructions on the target platforms are assumed.
14898 if (Alignment != nullptr) {
14899 ExprResult AlignResult =
14900 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14901 if (AlignResult.isInvalid())
14902 return nullptr;
14903 Alignment = AlignResult.get();
14904 }
14905 if (Vars.empty())
14906 return nullptr;
14907
14908 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14909 EndLoc, Vars, Alignment);
14910}
14911
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014912OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14913 SourceLocation StartLoc,
14914 SourceLocation LParenLoc,
14915 SourceLocation EndLoc) {
14916 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014917 SmallVector<Expr *, 8> SrcExprs;
14918 SmallVector<Expr *, 8> DstExprs;
14919 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014920 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014921 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14922 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014923 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014924 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014925 SrcExprs.push_back(nullptr);
14926 DstExprs.push_back(nullptr);
14927 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014928 continue;
14929 }
14930
Alexey Bataeved09d242014-05-28 05:53:51 +000014931 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014932 // OpenMP [2.1, C/C++]
14933 // A list item is a variable name.
14934 // OpenMP [2.14.4.1, Restrictions, p.1]
14935 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014936 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014937 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014938 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14939 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014940 continue;
14941 }
14942
14943 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014944 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014945
14946 QualType Type = VD->getType();
14947 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14948 // It will be analyzed later.
14949 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014950 SrcExprs.push_back(nullptr);
14951 DstExprs.push_back(nullptr);
14952 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014953 continue;
14954 }
14955
14956 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14957 // A list item that appears in a copyin clause must be threadprivate.
14958 if (!DSAStack->isThreadPrivate(VD)) {
14959 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014960 << getOpenMPClauseName(OMPC_copyin)
14961 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014962 continue;
14963 }
14964
14965 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14966 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014967 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014968 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014969 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14970 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014971 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014972 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014973 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014974 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014975 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014976 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014977 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014978 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014979 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014980 // For arrays generate assignment operation for single element and replace
14981 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014982 ExprResult AssignmentOp =
14983 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14984 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014985 if (AssignmentOp.isInvalid())
14986 continue;
14987 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014988 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014989 if (AssignmentOp.isInvalid())
14990 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014991
14992 DSAStack->addDSA(VD, DE, OMPC_copyin);
14993 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014994 SrcExprs.push_back(PseudoSrcExpr);
14995 DstExprs.push_back(PseudoDstExpr);
14996 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014997 }
14998
Alexey Bataeved09d242014-05-28 05:53:51 +000014999 if (Vars.empty())
15000 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000015001
Alexey Bataevf56f98c2015-04-16 05:39:01 +000015002 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15003 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000015004}
15005
Alexey Bataevbae9a792014-06-27 10:37:06 +000015006OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
15007 SourceLocation StartLoc,
15008 SourceLocation LParenLoc,
15009 SourceLocation EndLoc) {
15010 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000015011 SmallVector<Expr *, 8> SrcExprs;
15012 SmallVector<Expr *, 8> DstExprs;
15013 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000015014 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000015015 assert(RefExpr && "NULL expr in OpenMP linear clause.");
15016 SourceLocation ELoc;
15017 SourceRange ERange;
15018 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000015019 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000015020 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000015021 // It will be analyzed later.
15022 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000015023 SrcExprs.push_back(nullptr);
15024 DstExprs.push_back(nullptr);
15025 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015026 }
Alexey Bataeve122da12016-03-17 10:50:17 +000015027 ValueDecl *D = Res.first;
15028 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000015029 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000015030
Alexey Bataeve122da12016-03-17 10:50:17 +000015031 QualType Type = D->getType();
15032 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015033
15034 // OpenMP [2.14.4.2, Restrictions, p.2]
15035 // A list item that appears in a copyprivate clause may not appear in a
15036 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000015037 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015038 DSAStackTy::DSAVarData DVar =
15039 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000015040 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
15041 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000015042 Diag(ELoc, diag::err_omp_wrong_dsa)
15043 << getOpenMPClauseName(DVar.CKind)
15044 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000015045 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015046 continue;
15047 }
15048
15049 // OpenMP [2.11.4.2, Restrictions, p.1]
15050 // All list items that appear in a copyprivate clause must be either
15051 // threadprivate or private in the enclosing context.
15052 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000015053 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015054 if (DVar.CKind == OMPC_shared) {
15055 Diag(ELoc, diag::err_omp_required_access)
15056 << getOpenMPClauseName(OMPC_copyprivate)
15057 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000015058 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015059 continue;
15060 }
15061 }
15062 }
15063
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015064 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000015065 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015066 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000015067 << getOpenMPClauseName(OMPC_copyprivate) << Type
15068 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015069 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000015070 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015071 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000015072 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015073 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000015074 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015075 continue;
15076 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000015077
Alexey Bataevbae9a792014-06-27 10:37:06 +000015078 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
15079 // A variable of class type (or array thereof) that appears in a
15080 // copyin clause requires an accessible, unambiguous copy assignment
15081 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000015082 Type = Context.getBaseElementType(Type.getNonReferenceType())
15083 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015084 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015085 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000015086 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000015087 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
15088 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015089 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000015090 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000015091 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
15092 ExprResult AssignmentOp = BuildBinOp(
15093 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000015094 if (AssignmentOp.isInvalid())
15095 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000015096 AssignmentOp =
15097 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000015098 if (AssignmentOp.isInvalid())
15099 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000015100
15101 // No need to mark vars as copyprivate, they are already threadprivate or
15102 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000015103 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000015104 Vars.push_back(
15105 VD ? RefExpr->IgnoreParens()
15106 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000015107 SrcExprs.push_back(PseudoSrcExpr);
15108 DstExprs.push_back(PseudoDstExpr);
15109 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000015110 }
15111
15112 if (Vars.empty())
15113 return nullptr;
15114
Alexey Bataeva63048e2015-03-23 06:18:07 +000015115 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15116 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015117}
15118
Alexey Bataev6125da92014-07-21 11:26:11 +000015119OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
15120 SourceLocation StartLoc,
15121 SourceLocation LParenLoc,
15122 SourceLocation EndLoc) {
15123 if (VarList.empty())
15124 return nullptr;
15125
15126 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
15127}
Alexey Bataevdea47612014-07-23 07:46:59 +000015128
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015129OMPClause *
15130Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
15131 SourceLocation DepLoc, SourceLocation ColonLoc,
15132 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
15133 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000015134 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015135 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000015136 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000015137 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000015138 return nullptr;
15139 }
15140 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015141 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
15142 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000015143 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015144 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000015145 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
15146 /*Last=*/OMPC_DEPEND_unknown, Except)
15147 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015148 return nullptr;
15149 }
15150 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000015151 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015152 llvm::APSInt DepCounter(/*BitWidth=*/32);
15153 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000015154 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
15155 if (const Expr *OrderedCountExpr =
15156 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015157 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
15158 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015159 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015160 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015161 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000015162 assert(RefExpr && "NULL expr in OpenMP shared clause.");
15163 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
15164 // It will be analyzed later.
15165 Vars.push_back(RefExpr);
15166 continue;
15167 }
15168
15169 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000015170 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000015171 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000015172 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015173 DepCounter >= TotalDepCount) {
15174 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
15175 continue;
15176 }
15177 ++DepCounter;
15178 // OpenMP [2.13.9, Summary]
15179 // depend(dependence-type : vec), where dependence-type is:
15180 // 'sink' and where vec is the iteration vector, which has the form:
15181 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
15182 // where n is the value specified by the ordered clause in the loop
15183 // directive, xi denotes the loop iteration variable of the i-th nested
15184 // loop associated with the loop directive, and di is a constant
15185 // non-negative integer.
15186 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015187 // It will be analyzed later.
15188 Vars.push_back(RefExpr);
15189 continue;
15190 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015191 SimpleExpr = SimpleExpr->IgnoreImplicit();
15192 OverloadedOperatorKind OOK = OO_None;
15193 SourceLocation OOLoc;
15194 Expr *LHS = SimpleExpr;
15195 Expr *RHS = nullptr;
15196 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
15197 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
15198 OOLoc = BO->getOperatorLoc();
15199 LHS = BO->getLHS()->IgnoreParenImpCasts();
15200 RHS = BO->getRHS()->IgnoreParenImpCasts();
15201 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
15202 OOK = OCE->getOperator();
15203 OOLoc = OCE->getOperatorLoc();
15204 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
15205 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
15206 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
15207 OOK = MCE->getMethodDecl()
15208 ->getNameInfo()
15209 .getName()
15210 .getCXXOverloadedOperator();
15211 OOLoc = MCE->getCallee()->getExprLoc();
15212 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
15213 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015214 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015215 SourceLocation ELoc;
15216 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000015217 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015218 if (Res.second) {
15219 // It will be analyzed later.
15220 Vars.push_back(RefExpr);
15221 }
15222 ValueDecl *D = Res.first;
15223 if (!D)
15224 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015225
Alexey Bataev17daedf2018-02-15 22:42:57 +000015226 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
15227 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
15228 continue;
15229 }
15230 if (RHS) {
15231 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
15232 RHS, OMPC_depend, /*StrictlyPositive=*/false);
15233 if (RHSRes.isInvalid())
15234 continue;
15235 }
15236 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015237 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015238 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015239 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000015240 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000015241 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000015242 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
15243 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000015244 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000015245 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000015246 continue;
15247 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015248 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015249 } else {
Kelvin Li427ffa22020-01-03 11:55:37 -050015250 // OpenMP 5.0 [2.17.11, Restrictions]
15251 // List items used in depend clauses cannot be zero-length array sections.
15252 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
15253 if (OASE) {
15254 const Expr *Length = OASE->getLength();
15255 Expr::EvalResult Result;
15256 if (Length && !Length->isValueDependent() &&
15257 Length->EvaluateAsInt(Result, Context) &&
15258 Result.Val.getInt().isNullValue()) {
15259 Diag(ELoc,
15260 diag::err_omp_depend_zero_length_array_section_not_allowed)
15261 << SimpleExpr->getSourceRange();
15262 continue;
15263 }
15264 }
15265
Alexey Bataev17daedf2018-02-15 22:42:57 +000015266 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
15267 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
15268 (ASE &&
15269 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
15270 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
15271 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15272 << RefExpr->getSourceRange();
15273 continue;
15274 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000015275
15276 ExprResult Res;
15277 {
15278 Sema::TentativeAnalysisScope Trap(*this);
15279 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
15280 RefExpr->IgnoreParenImpCasts());
15281 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015282 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
15283 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15284 << RefExpr->getSourceRange();
15285 continue;
15286 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015287 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015288 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015289 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015290
15291 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
15292 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015293 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015294 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
15295 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
15296 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
15297 }
15298 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
15299 Vars.empty())
15300 return nullptr;
15301
Alexey Bataev8b427062016-05-25 12:36:08 +000015302 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000015303 DepKind, DepLoc, ColonLoc, Vars,
15304 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000015305 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
15306 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000015307 DSAStack->addDoacrossDependClause(C, OpsOffs);
15308 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015309}
Michael Wonge710d542015-08-07 16:16:36 +000015310
15311OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
15312 SourceLocation LParenLoc,
15313 SourceLocation EndLoc) {
15314 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015315 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000015316
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015317 // OpenMP [2.9.1, Restrictions]
15318 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015319 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000015320 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015321 return nullptr;
15322
Alexey Bataev931e19b2017-10-02 16:32:39 +000015323 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015324 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050015325 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000015326 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015327 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015328 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015329 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15330 HelperValStmt = buildPreInits(Context, Captures);
15331 }
15332
Alexey Bataev8451efa2018-01-15 19:06:12 +000015333 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
15334 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000015335}
Kelvin Li0bff7af2015-11-23 05:32:03 +000015336
Alexey Bataeve3727102018-04-18 15:57:46 +000015337static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000015338 DSAStackTy *Stack, QualType QTy,
15339 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000015340 NamedDecl *ND;
15341 if (QTy->isIncompleteType(&ND)) {
15342 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
15343 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015344 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000015345 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
Jonas Hahnfeld071dca22019-12-07 13:31:46 +010015346 !QTy.isTriviallyCopyableType(SemaRef.Context))
Alexey Bataev95c23e72018-02-27 21:31:11 +000015347 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015348 return true;
15349}
15350
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000015351/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015352/// (array section or array subscript) does NOT specify the whole size of the
15353/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015354static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015355 const Expr *E,
15356 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015357 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015358
15359 // If this is an array subscript, it refers to the whole size if the size of
15360 // the dimension is constant and equals 1. Also, an array section assumes the
15361 // format of an array subscript if no colon is used.
15362 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015363 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015364 return ATy->getSize().getSExtValue() != 1;
15365 // Size can't be evaluated statically.
15366 return false;
15367 }
15368
15369 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015370 const Expr *LowerBound = OASE->getLowerBound();
15371 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015372
15373 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000015374 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015375 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000015376 Expr::EvalResult Result;
15377 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015378 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000015379
15380 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015381 if (ConstLowerBound.getSExtValue())
15382 return true;
15383 }
15384
15385 // If we don't have a length we covering the whole dimension.
15386 if (!Length)
15387 return false;
15388
15389 // If the base is a pointer, we don't have a way to get the size of the
15390 // pointee.
15391 if (BaseQTy->isPointerType())
15392 return false;
15393
15394 // We can only check if the length is the same as the size of the dimension
15395 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000015396 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015397 if (!CATy)
15398 return false;
15399
Fangrui Song407659a2018-11-30 23:41:18 +000015400 Expr::EvalResult Result;
15401 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015402 return false; // Can't get the integer value as a constant.
15403
Fangrui Song407659a2018-11-30 23:41:18 +000015404 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015405 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
15406}
15407
15408// Return true if it can be proven that the provided array expression (array
15409// section or array subscript) does NOT specify a single element of the array
15410// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015411static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000015412 const Expr *E,
15413 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015414 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015415
15416 // An array subscript always refer to a single element. Also, an array section
15417 // assumes the format of an array subscript if no colon is used.
15418 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
15419 return false;
15420
15421 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015422 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015423
15424 // If we don't have a length we have to check if the array has unitary size
15425 // for this dimension. Also, we should always expect a length if the base type
15426 // is pointer.
15427 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015428 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015429 return ATy->getSize().getSExtValue() != 1;
15430 // We cannot assume anything.
15431 return false;
15432 }
15433
15434 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000015435 Expr::EvalResult Result;
15436 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015437 return false; // Can't get the integer value as a constant.
15438
Fangrui Song407659a2018-11-30 23:41:18 +000015439 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015440 return ConstLength.getSExtValue() != 1;
15441}
15442
Samuel Antao661c0902016-05-26 17:39:58 +000015443// Return the expression of the base of the mappable expression or null if it
15444// cannot be determined and do all the necessary checks to see if the expression
15445// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000015446// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015447static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000015448 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000015449 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015450 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015451 SourceLocation ELoc = E->getExprLoc();
15452 SourceRange ERange = E->getSourceRange();
15453
15454 // The base of elements of list in a map clause have to be either:
15455 // - a reference to variable or field.
15456 // - a member expression.
15457 // - an array expression.
15458 //
15459 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
15460 // reference to 'r'.
15461 //
15462 // If we have:
15463 //
15464 // struct SS {
15465 // Bla S;
15466 // foo() {
15467 // #pragma omp target map (S.Arr[:12]);
15468 // }
15469 // }
15470 //
15471 // We want to retrieve the member expression 'this->S';
15472
Alexey Bataeve3727102018-04-18 15:57:46 +000015473 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015474
Samuel Antao5de996e2016-01-22 20:21:36 +000015475 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15476 // If a list item is an array section, it must specify contiguous storage.
15477 //
15478 // For this restriction it is sufficient that we make sure only references
15479 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015480 // exist except in the rightmost expression (unless they cover the whole
15481 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015482 //
15483 // r.ArrS[3:5].Arr[6:7]
15484 //
15485 // r.ArrS[3:5].x
15486 //
15487 // but these would be valid:
15488 // r.ArrS[3].Arr[6:7]
15489 //
15490 // r.ArrS[3].x
15491
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015492 bool AllowUnitySizeArraySection = true;
15493 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015494
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015495 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015496 E = E->IgnoreParenImpCasts();
15497
15498 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15499 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015500 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015501
15502 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015503
15504 // If we got a reference to a declaration, we should not expect any array
15505 // section before that.
15506 AllowUnitySizeArraySection = false;
15507 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015508
15509 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015510 CurComponents.emplace_back(CurE, CurE->getDecl());
15511 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015512 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015513
15514 if (isa<CXXThisExpr>(BaseE))
15515 // We found a base expression: this->Val.
15516 RelevantExpr = CurE;
15517 else
15518 E = BaseE;
15519
15520 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015521 if (!NoDiagnose) {
15522 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15523 << CurE->getSourceRange();
15524 return nullptr;
15525 }
15526 if (RelevantExpr)
15527 return nullptr;
15528 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015529 }
15530
15531 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15532
15533 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15534 // A bit-field cannot appear in a map clause.
15535 //
15536 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015537 if (!NoDiagnose) {
15538 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15539 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15540 return nullptr;
15541 }
15542 if (RelevantExpr)
15543 return nullptr;
15544 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015545 }
15546
15547 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15548 // If the type of a list item is a reference to a type T then the type
15549 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015550 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015551
15552 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15553 // A list item cannot be a variable that is a member of a structure with
15554 // a union type.
15555 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015556 if (CurType->isUnionType()) {
15557 if (!NoDiagnose) {
15558 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15559 << CurE->getSourceRange();
15560 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015561 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015562 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015563 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015564
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015565 // If we got a member expression, we should not expect any array section
15566 // before that:
15567 //
15568 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15569 // If a list item is an element of a structure, only the rightmost symbol
15570 // of the variable reference can be an array section.
15571 //
15572 AllowUnitySizeArraySection = false;
15573 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015574
15575 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015576 CurComponents.emplace_back(CurE, FD);
15577 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015578 E = CurE->getBase()->IgnoreParenImpCasts();
15579
15580 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015581 if (!NoDiagnose) {
15582 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15583 << 0 << CurE->getSourceRange();
15584 return nullptr;
15585 }
15586 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015587 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015588
15589 // If we got an array subscript that express the whole dimension we
15590 // can have any array expressions before. If it only expressing part of
15591 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015592 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015593 E->getType()))
15594 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015595
Patrick Lystere13b1e32019-01-02 19:28:48 +000015596 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15597 Expr::EvalResult Result;
15598 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15599 if (!Result.Val.getInt().isNullValue()) {
15600 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15601 diag::err_omp_invalid_map_this_expr);
15602 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15603 diag::note_omp_invalid_subscript_on_this_ptr_map);
15604 }
15605 }
15606 RelevantExpr = TE;
15607 }
15608
Samuel Antao90927002016-04-26 14:54:23 +000015609 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015610 CurComponents.emplace_back(CurE, nullptr);
15611 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015612 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015613 E = CurE->getBase()->IgnoreParenImpCasts();
15614
Alexey Bataev27041fa2017-12-05 15:22:49 +000015615 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015616 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15617
Samuel Antao5de996e2016-01-22 20:21:36 +000015618 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15619 // If the type of a list item is a reference to a type T then the type
15620 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015621 if (CurType->isReferenceType())
15622 CurType = CurType->getPointeeType();
15623
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015624 bool IsPointer = CurType->isAnyPointerType();
15625
15626 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015627 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15628 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015629 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015630 }
15631
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015632 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015633 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015634 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015635 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015636
Samuel Antaodab51bb2016-07-18 23:22:11 +000015637 if (AllowWholeSizeArraySection) {
15638 // Any array section is currently allowed. Allowing a whole size array
15639 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015640 //
15641 // If this array section refers to the whole dimension we can still
15642 // accept other array sections before this one, except if the base is a
15643 // pointer. Otherwise, only unitary sections are accepted.
15644 if (NotWhole || IsPointer)
15645 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015646 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015647 // A unity or whole array section is not allowed and that is not
15648 // compatible with the properties of the current array section.
15649 SemaRef.Diag(
15650 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15651 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015652 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015653 }
Samuel Antao90927002016-04-26 14:54:23 +000015654
Patrick Lystere13b1e32019-01-02 19:28:48 +000015655 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15656 Expr::EvalResult ResultR;
15657 Expr::EvalResult ResultL;
15658 if (CurE->getLength()->EvaluateAsInt(ResultR,
15659 SemaRef.getASTContext())) {
15660 if (!ResultR.Val.getInt().isOneValue()) {
15661 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15662 diag::err_omp_invalid_map_this_expr);
15663 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15664 diag::note_omp_invalid_length_on_this_ptr_mapping);
15665 }
15666 }
15667 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15668 ResultL, SemaRef.getASTContext())) {
15669 if (!ResultL.Val.getInt().isNullValue()) {
15670 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15671 diag::err_omp_invalid_map_this_expr);
15672 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15673 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15674 }
15675 }
15676 RelevantExpr = TE;
15677 }
15678
Samuel Antao90927002016-04-26 14:54:23 +000015679 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015680 CurComponents.emplace_back(CurE, nullptr);
15681 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015682 if (!NoDiagnose) {
15683 // If nothing else worked, this is not a valid map clause expression.
15684 SemaRef.Diag(
15685 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15686 << ERange;
15687 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015688 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015689 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015690 }
15691
15692 return RelevantExpr;
15693}
15694
15695// Return true if expression E associated with value VD has conflicts with other
15696// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015697static bool checkMapConflicts(
15698 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015699 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015700 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15701 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015702 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015703 SourceLocation ELoc = E->getExprLoc();
15704 SourceRange ERange = E->getSourceRange();
15705
15706 // In order to easily check the conflicts we need to match each component of
15707 // the expression under test with the components of the expressions that are
15708 // already in the stack.
15709
Samuel Antao5de996e2016-01-22 20:21:36 +000015710 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015711 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015712 "Map clause expression with unexpected base!");
15713
15714 // Variables to help detecting enclosing problems in data environment nests.
15715 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015716 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015717
Samuel Antao90927002016-04-26 14:54:23 +000015718 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15719 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015720 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15721 ERange, CKind, &EnclosingExpr,
15722 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15723 StackComponents,
15724 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015725 assert(!StackComponents.empty() &&
15726 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015727 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015728 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015729 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015730
Samuel Antao90927002016-04-26 14:54:23 +000015731 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015732 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015733
Samuel Antao5de996e2016-01-22 20:21:36 +000015734 // Expressions must start from the same base. Here we detect at which
15735 // point both expressions diverge from each other and see if we can
15736 // detect if the memory referred to both expressions is contiguous and
15737 // do not overlap.
15738 auto CI = CurComponents.rbegin();
15739 auto CE = CurComponents.rend();
15740 auto SI = StackComponents.rbegin();
15741 auto SE = StackComponents.rend();
15742 for (; CI != CE && SI != SE; ++CI, ++SI) {
15743
15744 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15745 // At most one list item can be an array item derived from a given
15746 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015747 if (CurrentRegionOnly &&
15748 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15749 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15750 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15751 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15752 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015753 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015754 << CI->getAssociatedExpression()->getSourceRange();
15755 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15756 diag::note_used_here)
15757 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015758 return true;
15759 }
15760
15761 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015762 if (CI->getAssociatedExpression()->getStmtClass() !=
15763 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015764 break;
15765
15766 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015767 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015768 break;
15769 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015770 // Check if the extra components of the expressions in the enclosing
15771 // data environment are redundant for the current base declaration.
15772 // If they are, the maps completely overlap, which is legal.
15773 for (; SI != SE; ++SI) {
15774 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015775 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015776 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015777 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015778 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015779 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015780 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015781 Type =
15782 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15783 }
15784 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015785 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015786 SemaRef, SI->getAssociatedExpression(), Type))
15787 break;
15788 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015789
15790 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15791 // List items of map clauses in the same construct must not share
15792 // original storage.
15793 //
15794 // If the expressions are exactly the same or one is a subset of the
15795 // other, it means they are sharing storage.
15796 if (CI == CE && SI == SE) {
15797 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015798 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015799 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015800 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015801 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015802 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15803 << ERange;
15804 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015805 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15806 << RE->getSourceRange();
15807 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015808 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015809 // If we find the same expression in the enclosing data environment,
15810 // that is legal.
15811 IsEnclosedByDataEnvironmentExpr = true;
15812 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015813 }
15814
Samuel Antao90927002016-04-26 14:54:23 +000015815 QualType DerivedType =
15816 std::prev(CI)->getAssociatedDeclaration()->getType();
15817 SourceLocation DerivedLoc =
15818 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015819
15820 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15821 // If the type of a list item is a reference to a type T then the type
15822 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015823 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015824
15825 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15826 // A variable for which the type is pointer and an array section
15827 // derived from that variable must not appear as list items of map
15828 // clauses of the same construct.
15829 //
15830 // Also, cover one of the cases in:
15831 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15832 // If any part of the original storage of a list item has corresponding
15833 // storage in the device data environment, all of the original storage
15834 // must have corresponding storage in the device data environment.
15835 //
15836 if (DerivedType->isAnyPointerType()) {
15837 if (CI == CE || SI == SE) {
15838 SemaRef.Diag(
15839 DerivedLoc,
15840 diag::err_omp_pointer_mapped_along_with_derived_section)
15841 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015842 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15843 << RE->getSourceRange();
15844 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015845 }
15846 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015847 SI->getAssociatedExpression()->getStmtClass() ||
15848 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15849 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015850 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015851 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015852 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015853 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15854 << RE->getSourceRange();
15855 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015856 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015857 }
15858
15859 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15860 // List items of map clauses in the same construct must not share
15861 // original storage.
15862 //
15863 // An expression is a subset of the other.
15864 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015865 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015866 if (CI != CE || SI != SE) {
15867 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15868 // a pointer.
15869 auto Begin =
15870 CI != CE ? CurComponents.begin() : StackComponents.begin();
15871 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15872 auto It = Begin;
15873 while (It != End && !It->getAssociatedDeclaration())
15874 std::advance(It, 1);
15875 assert(It != End &&
15876 "Expected at least one component with the declaration.");
15877 if (It != Begin && It->getAssociatedDeclaration()
15878 ->getType()
15879 .getCanonicalType()
15880 ->isAnyPointerType()) {
15881 IsEnclosedByDataEnvironmentExpr = false;
15882 EnclosingExpr = nullptr;
15883 return false;
15884 }
15885 }
Samuel Antao661c0902016-05-26 17:39:58 +000015886 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015887 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015888 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015889 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15890 << ERange;
15891 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015892 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15893 << RE->getSourceRange();
15894 return true;
15895 }
15896
15897 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015898 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015899 if (!CurrentRegionOnly && SI != SE)
15900 EnclosingExpr = RE;
15901
15902 // The current expression is a subset of the expression in the data
15903 // environment.
15904 IsEnclosedByDataEnvironmentExpr |=
15905 (!CurrentRegionOnly && CI != CE && SI == SE);
15906
15907 return false;
15908 });
15909
15910 if (CurrentRegionOnly)
15911 return FoundError;
15912
15913 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15914 // If any part of the original storage of a list item has corresponding
15915 // storage in the device data environment, all of the original storage must
15916 // have corresponding storage in the device data environment.
15917 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15918 // If a list item is an element of a structure, and a different element of
15919 // the structure has a corresponding list item in the device data environment
15920 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015921 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015922 // data environment prior to the task encountering the construct.
15923 //
15924 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15925 SemaRef.Diag(ELoc,
15926 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15927 << ERange;
15928 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15929 << EnclosingExpr->getSourceRange();
15930 return true;
15931 }
15932
15933 return FoundError;
15934}
15935
Michael Kruse4304e9d2019-02-19 16:38:20 +000015936// Look up the user-defined mapper given the mapper name and mapped type, and
15937// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015938static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15939 CXXScopeSpec &MapperIdScopeSpec,
15940 const DeclarationNameInfo &MapperId,
15941 QualType Type,
15942 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015943 if (MapperIdScopeSpec.isInvalid())
15944 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015945 // Get the actual type for the array type.
15946 if (Type->isArrayType()) {
15947 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15948 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15949 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015950 // Find all user-defined mappers with the given MapperId.
15951 SmallVector<UnresolvedSet<8>, 4> Lookups;
15952 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15953 Lookup.suppressDiagnostics();
15954 if (S) {
15955 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15956 NamedDecl *D = Lookup.getRepresentativeDecl();
15957 while (S && !S->isDeclScope(D))
15958 S = S->getParent();
15959 if (S)
15960 S = S->getParent();
15961 Lookups.emplace_back();
15962 Lookups.back().append(Lookup.begin(), Lookup.end());
15963 Lookup.clear();
15964 }
15965 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15966 // Extract the user-defined mappers with the given MapperId.
15967 Lookups.push_back(UnresolvedSet<8>());
15968 for (NamedDecl *D : ULE->decls()) {
15969 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15970 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15971 Lookups.back().addDecl(DMD);
15972 }
15973 }
15974 // Defer the lookup for dependent types. The results will be passed through
15975 // UnresolvedMapper on instantiation.
15976 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15977 Type->isInstantiationDependentType() ||
15978 Type->containsUnexpandedParameterPack() ||
15979 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15980 return !D->isInvalidDecl() &&
15981 (D->getType()->isDependentType() ||
15982 D->getType()->isInstantiationDependentType() ||
15983 D->getType()->containsUnexpandedParameterPack());
15984 })) {
15985 UnresolvedSet<8> URS;
15986 for (const UnresolvedSet<8> &Set : Lookups) {
15987 if (Set.empty())
15988 continue;
15989 URS.append(Set.begin(), Set.end());
15990 }
15991 return UnresolvedLookupExpr::Create(
15992 SemaRef.Context, /*NamingClass=*/nullptr,
15993 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15994 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15995 }
Michael Kruse945249b2019-09-26 22:53:01 +000015996 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015997 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15998 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015999 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
16000 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
16001 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
16002 return ExprError();
16003 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016004 // Perform argument dependent lookup.
16005 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
16006 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
16007 // Return the first user-defined mapper with the desired type.
16008 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16009 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
16010 if (!D->isInvalidDecl() &&
16011 SemaRef.Context.hasSameType(D->getType(), Type))
16012 return D;
16013 return nullptr;
16014 }))
16015 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
16016 // Find the first user-defined mapper with a type derived from the desired
16017 // type.
16018 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16019 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
16020 if (!D->isInvalidDecl() &&
16021 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
16022 !Type.isMoreQualifiedThan(D->getType()))
16023 return D;
16024 return nullptr;
16025 })) {
16026 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
16027 /*DetectVirtual=*/false);
16028 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
16029 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
16030 VD->getType().getUnqualifiedType()))) {
16031 if (SemaRef.CheckBaseClassAccess(
16032 Loc, VD->getType(), Type, Paths.front(),
16033 /*DiagID=*/0) != Sema::AR_inaccessible) {
16034 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
16035 }
16036 }
16037 }
16038 }
16039 // Report error if a mapper is specified, but cannot be found.
16040 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
16041 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
16042 << Type << MapperId.getName();
16043 return ExprError();
16044 }
16045 return ExprEmpty();
16046}
16047
Samuel Antao661c0902016-05-26 17:39:58 +000016048namespace {
16049// Utility struct that gathers all the related lists associated with a mappable
16050// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000016051struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000016052 // The list of expressions.
16053 ArrayRef<Expr *> VarList;
16054 // The list of processed expressions.
16055 SmallVector<Expr *, 16> ProcessedVarList;
16056 // The mappble components for each expression.
16057 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
16058 // The base declaration of the variable.
16059 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000016060 // The reference to the user-defined mapper associated with every expression.
16061 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000016062
16063 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
16064 // We have a list of components and base declarations for each entry in the
16065 // variable list.
16066 VarComponents.reserve(VarList.size());
16067 VarBaseDeclarations.reserve(VarList.size());
16068 }
16069};
16070}
16071
16072// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000016073// \a CKind. In the check process the valid expressions, mappable expression
16074// components, variables, and user-defined mappers are extracted and used to
16075// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
16076// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
16077// and \a MapperId are expected to be valid if the clause kind is 'map'.
16078static void checkMappableExpressionList(
16079 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
16080 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016081 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
16082 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016083 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000016084 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016085 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
16086 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000016087 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000016088
16089 // If the identifier of user-defined mapper is not specified, it is "default".
16090 // We do not change the actual name in this clause to distinguish whether a
16091 // mapper is specified explicitly, i.e., it is not explicitly specified when
16092 // MapperId.getName() is empty.
16093 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
16094 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
16095 MapperId.setName(DeclNames.getIdentifier(
16096 &SemaRef.getASTContext().Idents.get("default")));
16097 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016098
16099 // Iterators to find the current unresolved mapper expression.
16100 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
16101 bool UpdateUMIt = false;
16102 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000016103
Samuel Antao90927002016-04-26 14:54:23 +000016104 // Keep track of the mappable components and base declarations in this clause.
16105 // Each entry in the list is going to have a list of components associated. We
16106 // record each set of the components so that we can build the clause later on.
16107 // In the end we should have the same amount of declarations and component
16108 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000016109
Alexey Bataeve3727102018-04-18 15:57:46 +000016110 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016111 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000016112 SourceLocation ELoc = RE->getExprLoc();
16113
Michael Kruse4304e9d2019-02-19 16:38:20 +000016114 // Find the current unresolved mapper expression.
16115 if (UpdateUMIt && UMIt != UMEnd) {
16116 UMIt++;
16117 assert(
16118 UMIt != UMEnd &&
16119 "Expect the size of UnresolvedMappers to match with that of VarList");
16120 }
16121 UpdateUMIt = true;
16122 if (UMIt != UMEnd)
16123 UnresolvedMapper = *UMIt;
16124
Alexey Bataeve3727102018-04-18 15:57:46 +000016125 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000016126
16127 if (VE->isValueDependent() || VE->isTypeDependent() ||
16128 VE->isInstantiationDependent() ||
16129 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000016130 // Try to find the associated user-defined mapper.
16131 ExprResult ER = buildUserDefinedMapperRef(
16132 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16133 VE->getType().getCanonicalType(), UnresolvedMapper);
16134 if (ER.isInvalid())
16135 continue;
16136 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000016137 // We can only analyze this information once the missing information is
16138 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000016139 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016140 continue;
16141 }
16142
Alexey Bataeve3727102018-04-18 15:57:46 +000016143 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000016144
Samuel Antao5de996e2016-01-22 20:21:36 +000016145 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000016146 SemaRef.Diag(ELoc,
16147 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000016148 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000016149 continue;
16150 }
16151
Samuel Antao90927002016-04-26 14:54:23 +000016152 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
16153 ValueDecl *CurDeclaration = nullptr;
16154
16155 // Obtain the array or member expression bases if required. Also, fill the
16156 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000016157 const Expr *BE = checkMapClauseExpressionBase(
16158 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000016159 if (!BE)
16160 continue;
16161
Samuel Antao90927002016-04-26 14:54:23 +000016162 assert(!CurComponents.empty() &&
16163 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000016164
Patrick Lystere13b1e32019-01-02 19:28:48 +000016165 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
16166 // Add store "this" pointer to class in DSAStackTy for future checking
16167 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000016168 // Try to find the associated user-defined mapper.
16169 ExprResult ER = buildUserDefinedMapperRef(
16170 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16171 VE->getType().getCanonicalType(), UnresolvedMapper);
16172 if (ER.isInvalid())
16173 continue;
16174 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000016175 // Skip restriction checking for variable or field declarations
16176 MVLI.ProcessedVarList.push_back(RE);
16177 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16178 MVLI.VarComponents.back().append(CurComponents.begin(),
16179 CurComponents.end());
16180 MVLI.VarBaseDeclarations.push_back(nullptr);
16181 continue;
16182 }
16183
Samuel Antao90927002016-04-26 14:54:23 +000016184 // For the following checks, we rely on the base declaration which is
16185 // expected to be associated with the last component. The declaration is
16186 // expected to be a variable or a field (if 'this' is being mapped).
16187 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
16188 assert(CurDeclaration && "Null decl on map clause.");
16189 assert(
16190 CurDeclaration->isCanonicalDecl() &&
16191 "Expecting components to have associated only canonical declarations.");
16192
16193 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000016194 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000016195
16196 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000016197 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000016198
16199 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000016200 // threadprivate variables cannot appear in a map clause.
16201 // OpenMP 4.5 [2.10.5, target update Construct]
16202 // threadprivate variables cannot appear in a from clause.
16203 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016204 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016205 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
16206 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000016207 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016208 continue;
16209 }
16210
Samuel Antao5de996e2016-01-22 20:21:36 +000016211 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
16212 // A list item cannot appear in both a map clause and a data-sharing
16213 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000016214
Samuel Antao5de996e2016-01-22 20:21:36 +000016215 // Check conflicts with other map clause expressions. We check the conflicts
16216 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000016217 // environment, because the restrictions are different. We only have to
16218 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000016219 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016220 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016221 break;
Samuel Antao661c0902016-05-26 17:39:58 +000016222 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000016223 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016224 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016225 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000016226
Samuel Antao661c0902016-05-26 17:39:58 +000016227 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000016228 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16229 // If the type of a list item is a reference to a type T then the type will
16230 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000016231 auto I = llvm::find_if(
16232 CurComponents,
16233 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
16234 return MC.getAssociatedDeclaration();
16235 });
16236 assert(I != CurComponents.end() && "Null decl on map clause.");
Alexey Bataev48bad082020-01-14 14:13:47 -050016237 QualType Type;
16238 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
16239 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
16240 if (ASE) {
16241 Type = ASE->getType().getNonReferenceType();
16242 } else if (OASE) {
16243 QualType BaseType =
16244 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16245 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16246 Type = ATy->getElementType();
16247 else
16248 Type = BaseType->getPointeeType();
16249 Type = Type.getNonReferenceType();
16250 } else {
16251 Type = VE->getType();
16252 }
Samuel Antao5de996e2016-01-22 20:21:36 +000016253
Samuel Antao661c0902016-05-26 17:39:58 +000016254 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
16255 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000016256 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000016257 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000016258 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000016259 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000016260 continue;
16261
Alexey Bataev48bad082020-01-14 14:13:47 -050016262 Type = I->getAssociatedDeclaration()->getType().getNonReferenceType();
16263
Samuel Antao661c0902016-05-26 17:39:58 +000016264 if (CKind == OMPC_map) {
16265 // target enter data
16266 // OpenMP [2.10.2, Restrictions, p. 99]
16267 // A map-type must be specified in all map clauses and must be either
16268 // to or alloc.
16269 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
16270 if (DKind == OMPD_target_enter_data &&
16271 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
16272 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16273 << (IsMapTypeImplicit ? 1 : 0)
16274 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16275 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016276 continue;
16277 }
Samuel Antao661c0902016-05-26 17:39:58 +000016278
16279 // target exit_data
16280 // OpenMP [2.10.3, Restrictions, p. 102]
16281 // A map-type must be specified in all map clauses and must be either
16282 // from, release, or delete.
16283 if (DKind == OMPD_target_exit_data &&
16284 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
16285 MapType == OMPC_MAP_delete)) {
16286 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16287 << (IsMapTypeImplicit ? 1 : 0)
16288 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16289 << getOpenMPDirectiveName(DKind);
16290 continue;
16291 }
16292
16293 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16294 // A list item cannot appear in both a map clause and a data-sharing
16295 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000016296 //
16297 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16298 // A list item cannot appear in both a map clause and a data-sharing
16299 // attribute clause on the same construct unless the construct is a
16300 // combined construct.
16301 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
16302 isOpenMPTargetExecutionDirective(DKind)) ||
16303 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016304 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016305 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000016306 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000016307 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000016308 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000016309 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016310 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000016311 continue;
16312 }
16313 }
Michael Kruse01f670d2019-02-22 22:29:42 +000016314 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016315
Michael Kruse01f670d2019-02-22 22:29:42 +000016316 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000016317 ExprResult ER = buildUserDefinedMapperRef(
16318 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16319 Type.getCanonicalType(), UnresolvedMapper);
16320 if (ER.isInvalid())
16321 continue;
16322 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016323
Samuel Antao90927002016-04-26 14:54:23 +000016324 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000016325 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000016326
16327 // Store the components in the stack so that they can be used to check
16328 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000016329 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
16330 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000016331
16332 // Save the components and declaration to create the clause. For purposes of
16333 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000016334 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000016335 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16336 MVLI.VarComponents.back().append(CurComponents.begin(),
16337 CurComponents.end());
16338 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
16339 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016340 }
Samuel Antao661c0902016-05-26 17:39:58 +000016341}
16342
Michael Kruse4304e9d2019-02-19 16:38:20 +000016343OMPClause *Sema::ActOnOpenMPMapClause(
16344 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16345 ArrayRef<SourceLocation> MapTypeModifiersLoc,
16346 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
16347 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
16348 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
16349 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
16350 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
16351 OMPC_MAP_MODIFIER_unknown,
16352 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000016353 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
16354
16355 // Process map-type-modifiers, flag errors for duplicate modifiers.
16356 unsigned Count = 0;
16357 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
16358 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
16359 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
16360 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
16361 continue;
16362 }
16363 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000016364 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000016365 Modifiers[Count] = MapTypeModifiers[I];
16366 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
16367 ++Count;
16368 }
16369
Michael Kruse4304e9d2019-02-19 16:38:20 +000016370 MappableVarListInfo MVLI(VarList);
16371 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016372 MapperIdScopeSpec, MapperId, UnresolvedMappers,
16373 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000016374
Samuel Antao5de996e2016-01-22 20:21:36 +000016375 // We need to produce a map clause even if we don't have variables so that
16376 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000016377 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
16378 MVLI.VarBaseDeclarations, MVLI.VarComponents,
16379 MVLI.UDMapperList, Modifiers, ModifiersLoc,
16380 MapperIdScopeSpec.getWithLocInContext(Context),
16381 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016382}
Kelvin Li099bb8c2015-11-24 20:50:12 +000016383
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016384QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
16385 TypeResult ParsedType) {
16386 assert(ParsedType.isUsable());
16387
16388 QualType ReductionType = GetTypeFromParser(ParsedType.get());
16389 if (ReductionType.isNull())
16390 return QualType();
16391
16392 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
16393 // A type name in a declare reduction directive cannot be a function type, an
16394 // array type, a reference type, or a type qualified with const, volatile or
16395 // restrict.
16396 if (ReductionType.hasQualifiers()) {
16397 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
16398 return QualType();
16399 }
16400
16401 if (ReductionType->isFunctionType()) {
16402 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
16403 return QualType();
16404 }
16405 if (ReductionType->isReferenceType()) {
16406 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
16407 return QualType();
16408 }
16409 if (ReductionType->isArrayType()) {
16410 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
16411 return QualType();
16412 }
16413 return ReductionType;
16414}
16415
16416Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
16417 Scope *S, DeclContext *DC, DeclarationName Name,
16418 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
16419 AccessSpecifier AS, Decl *PrevDeclInScope) {
16420 SmallVector<Decl *, 8> Decls;
16421 Decls.reserve(ReductionTypes.size());
16422
16423 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000016424 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016425 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
16426 // A reduction-identifier may not be re-declared in the current scope for the
16427 // same type or for a type that is compatible according to the base language
16428 // rules.
16429 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16430 OMPDeclareReductionDecl *PrevDRD = nullptr;
16431 bool InCompoundScope = true;
16432 if (S != nullptr) {
16433 // Find previous declaration with the same name not referenced in other
16434 // declarations.
16435 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16436 InCompoundScope =
16437 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16438 LookupName(Lookup, S);
16439 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16440 /*AllowInlineNamespace=*/false);
16441 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000016442 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016443 while (Filter.hasNext()) {
16444 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
16445 if (InCompoundScope) {
16446 auto I = UsedAsPrevious.find(PrevDecl);
16447 if (I == UsedAsPrevious.end())
16448 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000016449 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016450 UsedAsPrevious[D] = true;
16451 }
16452 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16453 PrevDecl->getLocation();
16454 }
16455 Filter.done();
16456 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016457 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016458 if (!PrevData.second) {
16459 PrevDRD = PrevData.first;
16460 break;
16461 }
16462 }
16463 }
16464 } else if (PrevDeclInScope != nullptr) {
16465 auto *PrevDRDInScope = PrevDRD =
16466 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
16467 do {
16468 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
16469 PrevDRDInScope->getLocation();
16470 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
16471 } while (PrevDRDInScope != nullptr);
16472 }
Alexey Bataeve3727102018-04-18 15:57:46 +000016473 for (const auto &TyData : ReductionTypes) {
16474 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016475 bool Invalid = false;
16476 if (I != PreviousRedeclTypes.end()) {
16477 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
16478 << TyData.first;
16479 Diag(I->second, diag::note_previous_definition);
16480 Invalid = true;
16481 }
16482 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
16483 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
16484 Name, TyData.first, PrevDRD);
16485 DC->addDecl(DRD);
16486 DRD->setAccess(AS);
16487 Decls.push_back(DRD);
16488 if (Invalid)
16489 DRD->setInvalidDecl();
16490 else
16491 PrevDRD = DRD;
16492 }
16493
16494 return DeclGroupPtrTy::make(
16495 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16496}
16497
16498void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16499 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16500
16501 // Enter new function scope.
16502 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016503 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016504 getCurFunction()->setHasOMPDeclareReductionCombiner();
16505
16506 if (S != nullptr)
16507 PushDeclContext(S, DRD);
16508 else
16509 CurContext = DRD;
16510
Faisal Valid143a0c2017-04-01 21:30:49 +000016511 PushExpressionEvaluationContext(
16512 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016513
16514 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016515 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16516 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16517 // uses semantics of argument handles by value, but it should be passed by
16518 // reference. C lang does not support references, so pass all parameters as
16519 // pointers.
16520 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016521 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016522 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016523 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16524 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16525 // uses semantics of argument handles by value, but it should be passed by
16526 // reference. C lang does not support references, so pass all parameters as
16527 // pointers.
16528 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016529 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016530 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16531 if (S != nullptr) {
16532 PushOnScopeChains(OmpInParm, S);
16533 PushOnScopeChains(OmpOutParm, S);
16534 } else {
16535 DRD->addDecl(OmpInParm);
16536 DRD->addDecl(OmpOutParm);
16537 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016538 Expr *InE =
16539 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16540 Expr *OutE =
16541 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16542 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016543}
16544
16545void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16546 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16547 DiscardCleanupsInEvaluationContext();
16548 PopExpressionEvaluationContext();
16549
16550 PopDeclContext();
16551 PopFunctionScopeInfo();
16552
16553 if (Combiner != nullptr)
16554 DRD->setCombiner(Combiner);
16555 else
16556 DRD->setInvalidDecl();
16557}
16558
Alexey Bataev070f43a2017-09-06 14:49:58 +000016559VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016560 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16561
16562 // Enter new function scope.
16563 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016564 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016565
16566 if (S != nullptr)
16567 PushDeclContext(S, DRD);
16568 else
16569 CurContext = DRD;
16570
Faisal Valid143a0c2017-04-01 21:30:49 +000016571 PushExpressionEvaluationContext(
16572 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016573
16574 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016575 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16576 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16577 // uses semantics of argument handles by value, but it should be passed by
16578 // reference. C lang does not support references, so pass all parameters as
16579 // pointers.
16580 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016581 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016582 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016583 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16584 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16585 // uses semantics of argument handles by value, but it should be passed by
16586 // reference. C lang does not support references, so pass all parameters as
16587 // pointers.
16588 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016589 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016590 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016591 if (S != nullptr) {
16592 PushOnScopeChains(OmpPrivParm, S);
16593 PushOnScopeChains(OmpOrigParm, S);
16594 } else {
16595 DRD->addDecl(OmpPrivParm);
16596 DRD->addDecl(OmpOrigParm);
16597 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016598 Expr *OrigE =
16599 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16600 Expr *PrivE =
16601 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16602 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016603 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016604}
16605
Alexey Bataev070f43a2017-09-06 14:49:58 +000016606void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16607 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016608 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16609 DiscardCleanupsInEvaluationContext();
16610 PopExpressionEvaluationContext();
16611
16612 PopDeclContext();
16613 PopFunctionScopeInfo();
16614
Alexey Bataev070f43a2017-09-06 14:49:58 +000016615 if (Initializer != nullptr) {
16616 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16617 } else if (OmpPrivParm->hasInit()) {
16618 DRD->setInitializer(OmpPrivParm->getInit(),
16619 OmpPrivParm->isDirectInit()
16620 ? OMPDeclareReductionDecl::DirectInit
16621 : OMPDeclareReductionDecl::CopyInit);
16622 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016623 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016624 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016625}
16626
16627Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16628 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016629 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016630 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016631 if (S)
16632 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16633 /*AddToContext=*/false);
16634 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016635 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016636 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016637 }
16638 return DeclReductions;
16639}
16640
Michael Kruse251e1482019-02-01 20:25:04 +000016641TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16642 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16643 QualType T = TInfo->getType();
16644 if (D.isInvalidType())
16645 return true;
16646
16647 if (getLangOpts().CPlusPlus) {
16648 // Check that there are no default arguments (C++ only).
16649 CheckExtraCXXDefaultArguments(D);
16650 }
16651
16652 return CreateParsedType(T, TInfo);
16653}
16654
16655QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16656 TypeResult ParsedType) {
16657 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16658
16659 QualType MapperType = GetTypeFromParser(ParsedType.get());
16660 assert(!MapperType.isNull() && "Expect valid mapper type");
16661
16662 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16663 // The type must be of struct, union or class type in C and C++
16664 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16665 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16666 return QualType();
16667 }
16668 return MapperType;
16669}
16670
16671OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16672 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16673 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16674 Decl *PrevDeclInScope) {
16675 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16676 forRedeclarationInCurContext());
16677 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16678 // A mapper-identifier may not be redeclared in the current scope for the
16679 // same type or for a type that is compatible according to the base language
16680 // rules.
16681 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16682 OMPDeclareMapperDecl *PrevDMD = nullptr;
16683 bool InCompoundScope = true;
16684 if (S != nullptr) {
16685 // Find previous declaration with the same name not referenced in other
16686 // declarations.
16687 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16688 InCompoundScope =
16689 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16690 LookupName(Lookup, S);
16691 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16692 /*AllowInlineNamespace=*/false);
16693 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16694 LookupResult::Filter Filter = Lookup.makeFilter();
16695 while (Filter.hasNext()) {
16696 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16697 if (InCompoundScope) {
16698 auto I = UsedAsPrevious.find(PrevDecl);
16699 if (I == UsedAsPrevious.end())
16700 UsedAsPrevious[PrevDecl] = false;
16701 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16702 UsedAsPrevious[D] = true;
16703 }
16704 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16705 PrevDecl->getLocation();
16706 }
16707 Filter.done();
16708 if (InCompoundScope) {
16709 for (const auto &PrevData : UsedAsPrevious) {
16710 if (!PrevData.second) {
16711 PrevDMD = PrevData.first;
16712 break;
16713 }
16714 }
16715 }
16716 } else if (PrevDeclInScope) {
16717 auto *PrevDMDInScope = PrevDMD =
16718 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16719 do {
16720 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16721 PrevDMDInScope->getLocation();
16722 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16723 } while (PrevDMDInScope != nullptr);
16724 }
16725 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16726 bool Invalid = false;
16727 if (I != PreviousRedeclTypes.end()) {
16728 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16729 << MapperType << Name;
16730 Diag(I->second, diag::note_previous_definition);
16731 Invalid = true;
16732 }
16733 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16734 MapperType, VN, PrevDMD);
16735 DC->addDecl(DMD);
16736 DMD->setAccess(AS);
16737 if (Invalid)
16738 DMD->setInvalidDecl();
16739
16740 // Enter new function scope.
16741 PushFunctionScope();
16742 setFunctionHasBranchProtectedScope();
16743
16744 CurContext = DMD;
16745
16746 return DMD;
16747}
16748
16749void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16750 Scope *S,
16751 QualType MapperType,
16752 SourceLocation StartLoc,
16753 DeclarationName VN) {
16754 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16755 if (S)
16756 PushOnScopeChains(VD, S);
16757 else
16758 DMD->addDecl(VD);
16759 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16760 DMD->setMapperVarRef(MapperVarRefExpr);
16761}
16762
16763Sema::DeclGroupPtrTy
16764Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16765 ArrayRef<OMPClause *> ClauseList) {
16766 PopDeclContext();
16767 PopFunctionScopeInfo();
16768
16769 if (D) {
16770 if (S)
16771 PushOnScopeChains(D, S, /*AddToContext=*/false);
16772 D->CreateClauses(Context, ClauseList);
16773 }
16774
16775 return DeclGroupPtrTy::make(DeclGroupRef(D));
16776}
16777
David Majnemer9d168222016-08-05 17:44:54 +000016778OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016779 SourceLocation StartLoc,
16780 SourceLocation LParenLoc,
16781 SourceLocation EndLoc) {
16782 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016783 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016784
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016785 // OpenMP [teams Constrcut, Restrictions]
16786 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016787 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016788 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016789 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016790
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016791 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016792 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016793 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016794 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016795 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016796 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016797 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16798 HelperValStmt = buildPreInits(Context, Captures);
16799 }
16800
16801 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16802 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016803}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016804
16805OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16806 SourceLocation StartLoc,
16807 SourceLocation LParenLoc,
16808 SourceLocation EndLoc) {
16809 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016810 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016811
16812 // OpenMP [teams Constrcut, Restrictions]
16813 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016814 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016815 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016816 return nullptr;
16817
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016818 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016819 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16820 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016821 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016822 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016823 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016824 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16825 HelperValStmt = buildPreInits(Context, Captures);
16826 }
16827
16828 return new (Context) OMPThreadLimitClause(
16829 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016830}
Alexey Bataeva0569352015-12-01 10:17:31 +000016831
16832OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16833 SourceLocation StartLoc,
16834 SourceLocation LParenLoc,
16835 SourceLocation EndLoc) {
16836 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016837 Stmt *HelperValStmt = nullptr;
16838 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016839
16840 // OpenMP [2.9.1, task Constrcut]
16841 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016842 if (!isNonNegativeIntegerValue(
16843 ValExpr, *this, OMPC_priority,
16844 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16845 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016846 return nullptr;
16847
Alexey Bataev31ba4762019-10-16 18:09:37 +000016848 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16849 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016850}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016851
16852OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16853 SourceLocation StartLoc,
16854 SourceLocation LParenLoc,
16855 SourceLocation EndLoc) {
16856 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016857 Stmt *HelperValStmt = nullptr;
16858 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016859
16860 // OpenMP [2.9.2, taskloop Constrcut]
16861 // The parameter of the grainsize clause must be a positive integer
16862 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016863 if (!isNonNegativeIntegerValue(
16864 ValExpr, *this, OMPC_grainsize,
16865 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16866 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016867 return nullptr;
16868
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016869 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16870 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016871}
Alexey Bataev382967a2015-12-08 12:06:20 +000016872
16873OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16874 SourceLocation StartLoc,
16875 SourceLocation LParenLoc,
16876 SourceLocation EndLoc) {
16877 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016878 Stmt *HelperValStmt = nullptr;
16879 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016880
16881 // OpenMP [2.9.2, taskloop Constrcut]
16882 // The parameter of the num_tasks clause must be a positive integer
16883 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016884 if (!isNonNegativeIntegerValue(
16885 ValExpr, *this, OMPC_num_tasks,
16886 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16887 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016888 return nullptr;
16889
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016890 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16891 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016892}
16893
Alexey Bataev28c75412015-12-15 08:19:24 +000016894OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16895 SourceLocation LParenLoc,
16896 SourceLocation EndLoc) {
16897 // OpenMP [2.13.2, critical construct, Description]
16898 // ... where hint-expression is an integer constant expression that evaluates
16899 // to a valid lock hint.
16900 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16901 if (HintExpr.isInvalid())
16902 return nullptr;
16903 return new (Context)
16904 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16905}
16906
Carlo Bertollib4adf552016-01-15 18:50:31 +000016907OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16908 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16909 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16910 SourceLocation EndLoc) {
16911 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16912 std::string Values;
16913 Values += "'";
16914 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16915 Values += "'";
16916 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16917 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16918 return nullptr;
16919 }
16920 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016921 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016922 if (ChunkSize) {
16923 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16924 !ChunkSize->isInstantiationDependent() &&
16925 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016926 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016927 ExprResult Val =
16928 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16929 if (Val.isInvalid())
16930 return nullptr;
16931
16932 ValExpr = Val.get();
16933
16934 // OpenMP [2.7.1, Restrictions]
16935 // chunk_size must be a loop invariant integer expression with a positive
16936 // value.
16937 llvm::APSInt Result;
16938 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16939 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16940 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16941 << "dist_schedule" << ChunkSize->getSourceRange();
16942 return nullptr;
16943 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016944 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016945 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16946 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016947 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016948 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016949 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016950 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16951 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016952 }
16953 }
16954 }
16955
16956 return new (Context)
16957 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016958 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016959}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016960
16961OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16962 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16963 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16964 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016965 if (getLangOpts().OpenMP < 50) {
16966 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16967 Kind != OMPC_DEFAULTMAP_scalar) {
16968 std::string Value;
16969 SourceLocation Loc;
16970 Value += "'";
16971 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16972 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16973 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16974 Loc = MLoc;
16975 } else {
16976 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16977 OMPC_DEFAULTMAP_scalar);
16978 Loc = KindLoc;
16979 }
16980 Value += "'";
16981 Diag(Loc, diag::err_omp_unexpected_clause_value)
16982 << Value << getOpenMPClauseName(OMPC_defaultmap);
16983 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016984 }
cchene06f3e02019-11-15 13:02:06 -050016985 } else {
16986 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16987 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16988 if (!isDefaultmapKind || !isDefaultmapModifier) {
16989 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16990 "'firstprivate', 'none', 'default'";
16991 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16992 if (!isDefaultmapKind && isDefaultmapModifier) {
16993 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16994 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16995 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16996 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16997 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16998 } else {
16999 Diag(MLoc, diag::err_omp_unexpected_clause_value)
17000 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
17001 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
17002 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
17003 }
17004 return nullptr;
17005 }
17006
17007 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
17008 // At most one defaultmap clause for each category can appear on the
17009 // directive.
17010 if (DSAStack->checkDefaultmapCategory(Kind)) {
17011 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
17012 return nullptr;
17013 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000017014 }
cchene06f3e02019-11-15 13:02:06 -050017015 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000017016
17017 return new (Context)
17018 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
17019}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017020
17021bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
17022 DeclContext *CurLexicalContext = getCurLexicalContext();
17023 if (!CurLexicalContext->isFileContext() &&
17024 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000017025 !CurLexicalContext->isExternCXXContext() &&
17026 !isa<CXXRecordDecl>(CurLexicalContext) &&
17027 !isa<ClassTemplateDecl>(CurLexicalContext) &&
17028 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
17029 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017030 Diag(Loc, diag::err_omp_region_not_file_context);
17031 return false;
17032 }
Kelvin Libc38e632018-09-10 02:07:09 +000017033 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017034 return true;
17035}
17036
17037void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000017038 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017039 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000017040 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017041}
17042
Alexey Bataev729e2422019-08-23 16:11:14 +000017043NamedDecl *
17044Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
17045 const DeclarationNameInfo &Id,
17046 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017047 LookupResult Lookup(*this, Id, LookupOrdinaryName);
17048 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
17049
17050 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000017051 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017052 Lookup.suppressDiagnostics();
17053
17054 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000017055 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017056 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000017057 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017058 CTK_ErrorRecovery)) {
17059 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
17060 << Id.getName());
17061 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000017062 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017063 }
17064
17065 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000017066 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017067 }
17068
17069 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000017070 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
17071 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017072 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000017073 return nullptr;
17074 }
17075 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
17076 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
17077 return ND;
17078}
17079
17080void Sema::ActOnOpenMPDeclareTargetName(
17081 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
17082 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
17083 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
17084 isa<FunctionTemplateDecl>(ND)) &&
17085 "Expected variable, function or function template.");
17086
17087 // Diagnose marking after use as it may lead to incorrect diagnosis and
17088 // codegen.
17089 if (LangOpts.OpenMP >= 50 &&
17090 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
17091 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
17092
17093 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17094 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
17095 if (DevTy.hasValue() && *DevTy != DT) {
17096 Diag(Loc, diag::err_omp_device_type_mismatch)
17097 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
17098 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
17099 return;
17100 }
17101 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
17102 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
17103 if (!Res) {
17104 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
17105 SourceRange(Loc, Loc));
17106 ND->addAttr(A);
17107 if (ASTMutationListener *ML = Context.getASTMutationListener())
17108 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
17109 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
17110 } else if (*Res != MT) {
17111 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000017112 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017113}
17114
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017115static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
17116 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000017117 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017118 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000017119 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000017120 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
17121 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
17122 if (SemaRef.LangOpts.OpenMP >= 50 &&
17123 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
17124 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
17125 VD->hasGlobalStorage()) {
17126 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
17127 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
17128 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
17129 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
17130 // If a lambda declaration and definition appears between a
17131 // declare target directive and the matching end declare target
17132 // directive, all variables that are captured by the lambda
17133 // expression must also appear in a to clause.
17134 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000017135 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000017136 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
17137 << VD << 0 << SR;
17138 return;
17139 }
17140 }
17141 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000017142 return;
17143 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
17144 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017145}
17146
17147static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
17148 Sema &SemaRef, DSAStackTy *Stack,
17149 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000017150 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000017151 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
17152 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017153}
17154
Kelvin Li1ce87c72017-12-12 20:08:12 +000017155void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
17156 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017157 if (!D || D->isInvalidDecl())
17158 return;
17159 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000017160 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000017161 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000017162 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000017163 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
17164 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000017165 return;
17166 // 2.10.6: threadprivate variable cannot appear in a declare target
17167 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017168 if (DSAStack->isThreadPrivate(VD)) {
17169 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000017170 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017171 return;
17172 }
17173 }
Alexey Bataev97b72212018-08-14 18:31:20 +000017174 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
17175 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017176 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000017177 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
17178 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017179 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000017180 Diag(IdLoc, diag::err_omp_function_in_link_clause);
17181 Diag(FD->getLocation(), diag::note_defined_here) << FD;
17182 return;
17183 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017184 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000017185 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17186 OMPDeclareTargetDeclAttr::getDeviceType(FD);
17187 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
17188 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017189 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000017190 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
17191 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
17192 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000017193 }
Alexey Bataev30a78212018-09-11 13:59:10 +000017194 if (auto *VD = dyn_cast<ValueDecl>(D)) {
17195 // Problem if any with var declared with incomplete type will be reported
17196 // as normal, so no need to check it here.
17197 if ((E || !VD->getType()->isIncompleteType()) &&
17198 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
17199 return;
17200 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
17201 // Checking declaration inside declare target region.
17202 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
17203 isa<FunctionTemplateDecl>(D)) {
17204 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000017205 Context, OMPDeclareTargetDeclAttr::MT_To,
17206 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000017207 D->addAttr(A);
17208 if (ASTMutationListener *ML = Context.getASTMutationListener())
17209 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
17210 }
17211 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017212 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017213 }
Alexey Bataev30a78212018-09-11 13:59:10 +000017214 if (!E)
17215 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017216 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
17217}
Samuel Antao661c0902016-05-26 17:39:58 +000017218
17219OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000017220 CXXScopeSpec &MapperIdScopeSpec,
17221 DeclarationNameInfo &MapperId,
17222 const OMPVarListLocTy &Locs,
17223 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000017224 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017225 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
17226 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000017227 if (MVLI.ProcessedVarList.empty())
17228 return nullptr;
17229
Michael Kruse01f670d2019-02-22 22:29:42 +000017230 return OMPToClause::Create(
17231 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17232 MVLI.VarComponents, MVLI.UDMapperList,
17233 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000017234}
Samuel Antaoec172c62016-05-26 17:49:04 +000017235
17236OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000017237 CXXScopeSpec &MapperIdScopeSpec,
17238 DeclarationNameInfo &MapperId,
17239 const OMPVarListLocTy &Locs,
17240 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000017241 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017242 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
17243 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000017244 if (MVLI.ProcessedVarList.empty())
17245 return nullptr;
17246
Michael Kruse0336c752019-02-25 20:34:15 +000017247 return OMPFromClause::Create(
17248 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17249 MVLI.VarComponents, MVLI.UDMapperList,
17250 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000017251}
Carlo Bertolli2404b172016-07-13 15:37:16 +000017252
17253OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017254 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000017255 MappableVarListInfo MVLI(VarList);
17256 SmallVector<Expr *, 8> PrivateCopies;
17257 SmallVector<Expr *, 8> Inits;
17258
Alexey Bataeve3727102018-04-18 15:57:46 +000017259 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017260 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
17261 SourceLocation ELoc;
17262 SourceRange ERange;
17263 Expr *SimpleRefExpr = RefExpr;
17264 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17265 if (Res.second) {
17266 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000017267 MVLI.ProcessedVarList.push_back(RefExpr);
17268 PrivateCopies.push_back(nullptr);
17269 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017270 }
17271 ValueDecl *D = Res.first;
17272 if (!D)
17273 continue;
17274
17275 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000017276 Type = Type.getNonReferenceType().getUnqualifiedType();
17277
17278 auto *VD = dyn_cast<VarDecl>(D);
17279
17280 // Item should be a pointer or reference to pointer.
17281 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017282 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
17283 << 0 << RefExpr->getSourceRange();
17284 continue;
17285 }
Samuel Antaocc10b852016-07-28 14:23:26 +000017286
17287 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000017288 auto VDPrivate =
17289 buildVarDecl(*this, ELoc, Type, D->getName(),
17290 D->hasAttrs() ? &D->getAttrs() : nullptr,
17291 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000017292 if (VDPrivate->isInvalidDecl())
17293 continue;
17294
17295 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000017296 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000017297 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
17298
17299 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000017300 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000017301 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000017302 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
17303 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000017304 AddInitializerToDecl(VDPrivate,
17305 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000017306 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000017307
17308 // If required, build a capture to implement the privatization initialized
17309 // with the current list item value.
17310 DeclRefExpr *Ref = nullptr;
17311 if (!VD)
17312 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17313 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
17314 PrivateCopies.push_back(VDPrivateRefExpr);
17315 Inits.push_back(VDInitRefExpr);
17316
17317 // We need to add a data sharing attribute for this variable to make sure it
17318 // is correctly captured. A variable that shows up in a use_device_ptr has
17319 // similar properties of a first private variable.
17320 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
17321
17322 // Create a mappable component for the list item. List items in this clause
17323 // only need a component.
17324 MVLI.VarBaseDeclarations.push_back(D);
17325 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17326 MVLI.VarComponents.back().push_back(
17327 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000017328 }
17329
Samuel Antaocc10b852016-07-28 14:23:26 +000017330 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000017331 return nullptr;
17332
Samuel Antaocc10b852016-07-28 14:23:26 +000017333 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000017334 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
17335 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017336}
Carlo Bertolli70594e92016-07-13 17:16:49 +000017337
17338OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017339 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000017340 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000017341 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000017342 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000017343 SourceLocation ELoc;
17344 SourceRange ERange;
17345 Expr *SimpleRefExpr = RefExpr;
17346 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17347 if (Res.second) {
17348 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000017349 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017350 }
17351 ValueDecl *D = Res.first;
17352 if (!D)
17353 continue;
17354
17355 QualType Type = D->getType();
17356 // item should be a pointer or array or reference to pointer or array
17357 if (!Type.getNonReferenceType()->isPointerType() &&
17358 !Type.getNonReferenceType()->isArrayType()) {
17359 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
17360 << 0 << RefExpr->getSourceRange();
17361 continue;
17362 }
Samuel Antao6890b092016-07-28 14:25:09 +000017363
17364 // Check if the declaration in the clause does not show up in any data
17365 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000017366 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000017367 if (isOpenMPPrivate(DVar.CKind)) {
17368 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17369 << getOpenMPClauseName(DVar.CKind)
17370 << getOpenMPClauseName(OMPC_is_device_ptr)
17371 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000017372 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000017373 continue;
17374 }
17375
Alexey Bataeve3727102018-04-18 15:57:46 +000017376 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000017377 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000017378 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000017379 [&ConflictExpr](
17380 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
17381 OpenMPClauseKind) -> bool {
17382 ConflictExpr = R.front().getAssociatedExpression();
17383 return true;
17384 })) {
17385 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
17386 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
17387 << ConflictExpr->getSourceRange();
17388 continue;
17389 }
17390
17391 // Store the components in the stack so that they can be used to check
17392 // against other clauses later on.
17393 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
17394 DSAStack->addMappableExpressionComponents(
17395 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
17396
17397 // Record the expression we've just processed.
17398 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
17399
17400 // Create a mappable component for the list item. List items in this clause
17401 // only need a component. We use a null declaration to signal fields in
17402 // 'this'.
17403 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
17404 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
17405 "Unexpected device pointer expression!");
17406 MVLI.VarBaseDeclarations.push_back(
17407 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
17408 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17409 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017410 }
17411
Samuel Antao6890b092016-07-28 14:25:09 +000017412 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000017413 return nullptr;
17414
Michael Kruse4304e9d2019-02-19 16:38:20 +000017415 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
17416 MVLI.VarBaseDeclarations,
17417 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017418}
Alexey Bataeve04483e2019-03-27 14:14:31 +000017419
17420OMPClause *Sema::ActOnOpenMPAllocateClause(
17421 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17422 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
17423 if (Allocator) {
17424 // OpenMP [2.11.4 allocate Clause, Description]
17425 // allocator is an expression of omp_allocator_handle_t type.
17426 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
17427 return nullptr;
17428
17429 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
17430 if (AllocatorRes.isInvalid())
17431 return nullptr;
17432 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
17433 DSAStack->getOMPAllocatorHandleT(),
17434 Sema::AA_Initializing,
17435 /*AllowExplicit=*/true);
17436 if (AllocatorRes.isInvalid())
17437 return nullptr;
17438 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000017439 } else {
17440 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
17441 // allocate clauses that appear on a target construct or on constructs in a
17442 // target region must specify an allocator expression unless a requires
17443 // directive with the dynamic_allocators clause is present in the same
17444 // compilation unit.
17445 if (LangOpts.OpenMPIsDevice &&
17446 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
17447 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017448 }
17449 // Analyze and build list of variables.
17450 SmallVector<Expr *, 8> Vars;
17451 for (Expr *RefExpr : VarList) {
17452 assert(RefExpr && "NULL expr in OpenMP private clause.");
17453 SourceLocation ELoc;
17454 SourceRange ERange;
17455 Expr *SimpleRefExpr = RefExpr;
17456 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17457 if (Res.second) {
17458 // It will be analyzed later.
17459 Vars.push_back(RefExpr);
17460 }
17461 ValueDecl *D = Res.first;
17462 if (!D)
17463 continue;
17464
17465 auto *VD = dyn_cast<VarDecl>(D);
17466 DeclRefExpr *Ref = nullptr;
17467 if (!VD && !CurContext->isDependentContext())
17468 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17469 Vars.push_back((VD || CurContext->isDependentContext())
17470 ? RefExpr->IgnoreParens()
17471 : Ref);
17472 }
17473
17474 if (Vars.empty())
17475 return nullptr;
17476
Alexey Bataevf3c508f2020-01-23 10:47:16 -050017477 if (Allocator)
17478 DSAStack->addInnerAllocatorExpr(Allocator);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017479 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
17480 ColonLoc, EndLoc, Vars);
17481}
Alexey Bataevb6e70842019-12-16 15:54:17 -050017482
17483OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
17484 SourceLocation StartLoc,
17485 SourceLocation LParenLoc,
17486 SourceLocation EndLoc) {
17487 SmallVector<Expr *, 8> Vars;
17488 for (Expr *RefExpr : VarList) {
17489 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
17490 SourceLocation ELoc;
17491 SourceRange ERange;
17492 Expr *SimpleRefExpr = RefExpr;
17493 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17494 if (Res.second)
17495 // It will be analyzed later.
17496 Vars.push_back(RefExpr);
17497 ValueDecl *D = Res.first;
17498 if (!D)
17499 continue;
17500
Alexey Bataevb6e70842019-12-16 15:54:17 -050017501 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
17502 // A list-item cannot appear in more than one nontemporal clause.
17503 if (const Expr *PrevRef =
17504 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
17505 Diag(ELoc, diag::err_omp_used_in_clause_twice)
17506 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
17507 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17508 << getOpenMPClauseName(OMPC_nontemporal);
17509 continue;
17510 }
17511
Alexey Bataev0860db92019-12-19 10:01:10 -050017512 Vars.push_back(RefExpr);
Alexey Bataevb6e70842019-12-16 15:54:17 -050017513 }
17514
17515 if (Vars.empty())
17516 return nullptr;
17517
17518 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17519 Vars);
17520}