blob: bd1c4777bc0d587abe791bdc3b6937a15a373498 [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 Bataev6d4ed052015-07-01 06:57:41 +00004162 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
4163 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00004164 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4165 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00004166 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004167 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00004168 // OpenMP [2.16, Nesting of Regions]
4169 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004170 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00004171 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004172 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004173 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4174 // OpenMP [2.16, Nesting of Regions]
4175 // A critical region may not be nested (closely or otherwise) inside a
4176 // critical region with the same name. Note that this restriction is not
4177 // sufficient to prevent deadlock.
4178 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00004179 bool DeadLock = Stack->hasDirective(
4180 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4181 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00004182 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00004183 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4184 PreviousCriticalLoc = Loc;
4185 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004186 }
4187 return false;
David Majnemer9d168222016-08-05 17:44:54 +00004188 },
4189 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004190 if (DeadLock) {
4191 SemaRef.Diag(StartLoc,
4192 diag::err_omp_prohibited_region_critical_same_name)
4193 << CurrentName.getName();
4194 if (PreviousCriticalLoc.isValid())
4195 SemaRef.Diag(PreviousCriticalLoc,
4196 diag::note_omp_previous_critical_region);
4197 return true;
4198 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004199 } else if (CurrentRegion == OMPD_barrier) {
4200 // OpenMP [2.16, Nesting of Regions]
4201 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004202 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004203 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4204 isOpenMPTaskingDirective(ParentRegion) ||
4205 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004206 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004207 ParentRegion == OMPD_critical ||
4208 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00004209 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00004210 !isOpenMPParallelDirective(CurrentRegion) &&
4211 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004212 // OpenMP [2.16, Nesting of Regions]
4213 // A worksharing region may not be closely nested inside a worksharing,
4214 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004215 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4216 isOpenMPTaskingDirective(ParentRegion) ||
4217 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004218 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004219 ParentRegion == OMPD_critical ||
4220 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004221 Recommend = ShouldBeInParallelRegion;
4222 } else if (CurrentRegion == OMPD_ordered) {
4223 // OpenMP [2.16, Nesting of Regions]
4224 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00004225 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004226 // An ordered region must be closely nested inside a loop region (or
4227 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004228 // OpenMP [2.8.1,simd Construct, Restrictions]
4229 // An ordered construct with the simd clause is the only OpenMP construct
4230 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004231 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004232 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004233 !(isOpenMPSimdDirective(ParentRegion) ||
4234 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004235 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00004236 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004237 // OpenMP [2.16, Nesting of Regions]
4238 // If specified, a teams construct must be contained within a target
4239 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00004240 NestingProhibited =
4241 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4242 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4243 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00004244 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004245 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004246 }
Kelvin Libf594a52016-12-17 05:48:59 +00004247 if (!NestingProhibited &&
4248 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4249 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4250 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004251 // OpenMP [2.16, Nesting of Regions]
4252 // distribute, parallel, parallel sections, parallel workshare, and the
4253 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4254 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004255 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4256 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00004257 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004258 }
David Majnemer9d168222016-08-05 17:44:54 +00004259 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00004260 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004261 // OpenMP 4.5 [2.17 Nesting of Regions]
4262 // The region associated with the distribute construct must be strictly
4263 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00004264 NestingProhibited =
4265 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004266 Recommend = ShouldBeInTeamsRegion;
4267 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004268 if (!NestingProhibited &&
4269 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4270 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4271 // OpenMP 4.5 [2.17 Nesting of Regions]
4272 // If a target, target update, target data, target enter data, or
4273 // target exit data construct is encountered during execution of a
4274 // target region, the behavior is unspecified.
4275 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004276 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00004277 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004278 if (isOpenMPTargetExecutionDirective(K)) {
4279 OffendingRegion = K;
4280 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004281 }
4282 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004283 },
4284 false /* don't skip top directive */);
4285 CloseNesting = false;
4286 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004287 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00004288 if (OrphanSeen) {
4289 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4290 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4291 } else {
4292 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4293 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4294 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4295 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004296 return true;
4297 }
4298 }
4299 return false;
4300}
4301
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004302struct Kind2Unsigned {
4303 using argument_type = OpenMPDirectiveKind;
4304 unsigned operator()(argument_type DK) { return unsigned(DK); }
4305};
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004306static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4307 ArrayRef<OMPClause *> Clauses,
4308 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4309 bool ErrorFound = false;
4310 unsigned NamedModifiersNumber = 0;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004311 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4312 FoundNameModifiers.resize(unsigned(OMPD_unknown) + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004313 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004314 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004315 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4316 // At most one if clause without a directive-name-modifier can appear on
4317 // the directive.
4318 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4319 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004320 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004321 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4322 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4323 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004324 } else if (CurNM != OMPD_unknown) {
4325 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004326 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004327 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004328 FoundNameModifiers[CurNM] = IC;
4329 if (CurNM == OMPD_unknown)
4330 continue;
4331 // Check if the specified name modifier is allowed for the current
4332 // directive.
4333 // At most one if clause with the particular directive-name-modifier can
4334 // appear on the directive.
4335 bool MatchFound = false;
4336 for (auto NM : AllowedNameModifiers) {
4337 if (CurNM == NM) {
4338 MatchFound = true;
4339 break;
4340 }
4341 }
4342 if (!MatchFound) {
4343 S.Diag(IC->getNameModifierLoc(),
4344 diag::err_omp_wrong_if_directive_name_modifier)
4345 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4346 ErrorFound = true;
4347 }
4348 }
4349 }
4350 // If any if clause on the directive includes a directive-name-modifier then
4351 // all if clauses on the directive must include a directive-name-modifier.
4352 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4353 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004354 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004355 diag::err_omp_no_more_if_clause);
4356 } else {
4357 std::string Values;
4358 std::string Sep(", ");
4359 unsigned AllowedCnt = 0;
4360 unsigned TotalAllowedNum =
4361 AllowedNameModifiers.size() - NamedModifiersNumber;
4362 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4363 ++Cnt) {
4364 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4365 if (!FoundNameModifiers[NM]) {
4366 Values += "'";
4367 Values += getOpenMPDirectiveName(NM);
4368 Values += "'";
4369 if (AllowedCnt + 2 == TotalAllowedNum)
4370 Values += " or ";
4371 else if (AllowedCnt + 1 != TotalAllowedNum)
4372 Values += Sep;
4373 ++AllowedCnt;
4374 }
4375 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004376 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004377 diag::err_omp_unnamed_if_clause)
4378 << (TotalAllowedNum > 1) << Values;
4379 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004380 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004381 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4382 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004383 ErrorFound = true;
4384 }
4385 return ErrorFound;
4386}
4387
Alexey Bataev0860db92019-12-19 10:01:10 -05004388static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4389 SourceLocation &ELoc,
4390 SourceRange &ERange,
4391 bool AllowArraySection) {
Alexey Bataeve106f252019-04-01 14:25:31 +00004392 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4393 RefExpr->containsUnexpandedParameterPack())
4394 return std::make_pair(nullptr, true);
4395
4396 // OpenMP [3.1, C/C++]
4397 // A list item is a variable name.
4398 // OpenMP [2.9.3.3, Restrictions, p.1]
4399 // A variable that is part of another variable (as an array or
4400 // structure element) cannot appear in a private clause.
4401 RefExpr = RefExpr->IgnoreParens();
4402 enum {
4403 NoArrayExpr = -1,
4404 ArraySubscript = 0,
4405 OMPArraySection = 1
4406 } IsArrayExpr = NoArrayExpr;
4407 if (AllowArraySection) {
4408 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4409 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4410 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4411 Base = TempASE->getBase()->IgnoreParenImpCasts();
4412 RefExpr = Base;
4413 IsArrayExpr = ArraySubscript;
4414 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4415 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4416 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4417 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4418 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4419 Base = TempASE->getBase()->IgnoreParenImpCasts();
4420 RefExpr = Base;
4421 IsArrayExpr = OMPArraySection;
4422 }
4423 }
4424 ELoc = RefExpr->getExprLoc();
4425 ERange = RefExpr->getSourceRange();
4426 RefExpr = RefExpr->IgnoreParenImpCasts();
4427 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4428 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4429 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4430 (S.getCurrentThisType().isNull() || !ME ||
4431 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4432 !isa<FieldDecl>(ME->getMemberDecl()))) {
4433 if (IsArrayExpr != NoArrayExpr) {
4434 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4435 << ERange;
4436 } else {
4437 S.Diag(ELoc,
4438 AllowArraySection
4439 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4440 : diag::err_omp_expected_var_name_member_expr)
4441 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4442 }
4443 return std::make_pair(nullptr, false);
4444 }
4445 return std::make_pair(
4446 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4447}
4448
4449static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004450 ArrayRef<OMPClause *> Clauses) {
4451 assert(!S.CurContext->isDependentContext() &&
4452 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004453 auto AllocateRange =
4454 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004455 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4456 DeclToCopy;
4457 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4458 return isOpenMPPrivate(C->getClauseKind());
4459 });
4460 for (OMPClause *Cl : PrivateRange) {
4461 MutableArrayRef<Expr *>::iterator I, It, Et;
4462 if (Cl->getClauseKind() == OMPC_private) {
4463 auto *PC = cast<OMPPrivateClause>(Cl);
4464 I = PC->private_copies().begin();
4465 It = PC->varlist_begin();
4466 Et = PC->varlist_end();
4467 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4468 auto *PC = cast<OMPFirstprivateClause>(Cl);
4469 I = PC->private_copies().begin();
4470 It = PC->varlist_begin();
4471 Et = PC->varlist_end();
4472 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4473 auto *PC = cast<OMPLastprivateClause>(Cl);
4474 I = PC->private_copies().begin();
4475 It = PC->varlist_begin();
4476 Et = PC->varlist_end();
4477 } else if (Cl->getClauseKind() == OMPC_linear) {
4478 auto *PC = cast<OMPLinearClause>(Cl);
4479 I = PC->privates().begin();
4480 It = PC->varlist_begin();
4481 Et = PC->varlist_end();
4482 } else if (Cl->getClauseKind() == OMPC_reduction) {
4483 auto *PC = cast<OMPReductionClause>(Cl);
4484 I = PC->privates().begin();
4485 It = PC->varlist_begin();
4486 Et = PC->varlist_end();
4487 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4488 auto *PC = cast<OMPTaskReductionClause>(Cl);
4489 I = PC->privates().begin();
4490 It = PC->varlist_begin();
4491 Et = PC->varlist_end();
4492 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4493 auto *PC = cast<OMPInReductionClause>(Cl);
4494 I = PC->privates().begin();
4495 It = PC->varlist_begin();
4496 Et = PC->varlist_end();
4497 } else {
4498 llvm_unreachable("Expected private clause.");
4499 }
4500 for (Expr *E : llvm::make_range(It, Et)) {
4501 if (!*I) {
4502 ++I;
4503 continue;
4504 }
4505 SourceLocation ELoc;
4506 SourceRange ERange;
4507 Expr *SimpleRefExpr = E;
4508 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4509 /*AllowArraySection=*/true);
4510 DeclToCopy.try_emplace(Res.first,
4511 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4512 ++I;
4513 }
4514 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004515 for (OMPClause *C : AllocateRange) {
4516 auto *AC = cast<OMPAllocateClause>(C);
4517 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4518 getAllocatorKind(S, Stack, AC->getAllocator());
4519 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4520 // For task, taskloop or target directives, allocation requests to memory
4521 // allocators with the trait access set to thread result in unspecified
4522 // behavior.
4523 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4524 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4525 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4526 S.Diag(AC->getAllocator()->getExprLoc(),
4527 diag::warn_omp_allocate_thread_on_task_target_directive)
4528 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004529 }
4530 for (Expr *E : AC->varlists()) {
4531 SourceLocation ELoc;
4532 SourceRange ERange;
4533 Expr *SimpleRefExpr = E;
4534 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4535 ValueDecl *VD = Res.first;
4536 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4537 if (!isOpenMPPrivate(Data.CKind)) {
4538 S.Diag(E->getExprLoc(),
4539 diag::err_omp_expected_private_copy_for_allocate);
4540 continue;
4541 }
4542 VarDecl *PrivateVD = DeclToCopy[VD];
4543 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4544 AllocatorKind, AC->getAllocator()))
4545 continue;
4546 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4547 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004548 }
4549 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004550}
4551
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004552StmtResult Sema::ActOnOpenMPExecutableDirective(
4553 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4554 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4555 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004556 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004557 // First check CancelRegion which is then used in checkNestingOfRegions.
4558 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4559 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004560 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004561 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004562
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004563 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004564 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004565 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004566 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004567 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004568 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4569
4570 // Check default data sharing attributes for referenced variables.
4571 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004572 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4573 Stmt *S = AStmt;
4574 while (--ThisCaptureLevel >= 0)
4575 S = cast<CapturedStmt>(S)->getCapturedStmt();
4576 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004577 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4578 !isOpenMPTaskingDirective(Kind)) {
4579 // Visit subcaptures to generate implicit clauses for captured vars.
4580 auto *CS = cast<CapturedStmt>(AStmt);
4581 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4582 getOpenMPCaptureRegions(CaptureRegions, Kind);
4583 // Ignore outer tasking regions for target directives.
4584 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4585 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4586 DSAChecker.visitSubCaptures(CS);
4587 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004588 if (DSAChecker.isErrorFound())
4589 return StmtError();
4590 // Generate list of implicitly defined firstprivate variables.
4591 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004592
Alexey Bataev88202be2017-07-27 13:20:36 +00004593 SmallVector<Expr *, 4> ImplicitFirstprivates(
4594 DSAChecker.getImplicitFirstprivate().begin(),
4595 DSAChecker.getImplicitFirstprivate().end());
cchene06f3e02019-11-15 13:02:06 -05004596 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4597 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4598 ArrayRef<Expr *> ImplicitMap =
4599 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4600 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4601 }
Alexey Bataev88202be2017-07-27 13:20:36 +00004602 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004603 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004604 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004605 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004606 if (E)
4607 ImplicitFirstprivates.emplace_back(E);
4608 }
4609 }
4610 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004611 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004612 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4613 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004614 ClausesWithImplicit.push_back(Implicit);
4615 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004616 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004617 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004618 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004619 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004620 }
cchene06f3e02019-11-15 13:02:06 -05004621 int ClauseKindCnt = -1;
4622 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4623 ++ClauseKindCnt;
4624 if (ImplicitMap.empty())
4625 continue;
Michael Kruse4304e9d2019-02-19 16:38:20 +00004626 CXXScopeSpec MapperIdScopeSpec;
4627 DeclarationNameInfo MapperId;
cchene06f3e02019-11-15 13:02:06 -05004628 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004629 if (OMPClause *Implicit = ActOnOpenMPMapClause(
cchene06f3e02019-11-15 13:02:06 -05004630 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4631 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4632 ImplicitMap, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004633 ClausesWithImplicit.emplace_back(Implicit);
4634 ErrorFound |=
cchene06f3e02019-11-15 13:02:06 -05004635 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004636 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004637 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004638 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004639 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004640 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004641
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004642 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004643 switch (Kind) {
4644 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004645 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4646 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004647 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004648 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004649 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004650 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4651 VarsWithInheritedDSA);
Alexey Bataevd08c0562019-11-19 12:07:54 -05004652 if (LangOpts.OpenMP >= 50)
4653 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004654 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004655 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004656 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4657 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004658 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004659 case OMPD_for_simd:
4660 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4661 EndLoc, VarsWithInheritedDSA);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05004662 if (LangOpts.OpenMP >= 50)
4663 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004664 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004665 case OMPD_sections:
4666 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4667 EndLoc);
4668 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004669 case OMPD_section:
4670 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004671 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004672 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4673 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004674 case OMPD_single:
4675 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4676 EndLoc);
4677 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004678 case OMPD_master:
4679 assert(ClausesWithImplicit.empty() &&
4680 "No clauses are allowed for 'omp master' directive");
4681 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4682 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004683 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004684 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4685 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004686 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004687 case OMPD_parallel_for:
4688 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4689 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004690 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004691 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004692 case OMPD_parallel_for_simd:
4693 Res = ActOnOpenMPParallelForSimdDirective(
4694 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004695 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevf59614d2019-11-21 10:00:56 -05004696 if (LangOpts.OpenMP >= 50)
4697 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004698 break;
cchen47d60942019-12-05 13:43:48 -05004699 case OMPD_parallel_master:
4700 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
4701 StartLoc, EndLoc);
4702 AllowedNameModifiers.push_back(OMPD_parallel);
4703 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004704 case OMPD_parallel_sections:
4705 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4706 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004707 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004708 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004709 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004710 Res =
4711 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004712 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004713 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004714 case OMPD_taskyield:
4715 assert(ClausesWithImplicit.empty() &&
4716 "No clauses are allowed for 'omp taskyield' directive");
4717 assert(AStmt == nullptr &&
4718 "No associated statement allowed for 'omp taskyield' directive");
4719 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4720 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004721 case OMPD_barrier:
4722 assert(ClausesWithImplicit.empty() &&
4723 "No clauses are allowed for 'omp barrier' directive");
4724 assert(AStmt == nullptr &&
4725 "No associated statement allowed for 'omp barrier' directive");
4726 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4727 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004728 case OMPD_taskwait:
4729 assert(ClausesWithImplicit.empty() &&
4730 "No clauses are allowed for 'omp taskwait' directive");
4731 assert(AStmt == nullptr &&
4732 "No associated statement allowed for 'omp taskwait' directive");
4733 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4734 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004735 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004736 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4737 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004738 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004739 case OMPD_flush:
4740 assert(AStmt == nullptr &&
4741 "No associated statement allowed for 'omp flush' directive");
4742 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4743 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004744 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004745 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4746 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004747 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004748 case OMPD_atomic:
4749 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4750 EndLoc);
4751 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004752 case OMPD_teams:
4753 Res =
4754 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4755 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004756 case OMPD_target:
4757 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4758 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004759 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004760 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004761 case OMPD_target_parallel:
4762 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4763 StartLoc, EndLoc);
4764 AllowedNameModifiers.push_back(OMPD_target);
4765 AllowedNameModifiers.push_back(OMPD_parallel);
4766 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004767 case OMPD_target_parallel_for:
4768 Res = ActOnOpenMPTargetParallelForDirective(
4769 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4770 AllowedNameModifiers.push_back(OMPD_target);
4771 AllowedNameModifiers.push_back(OMPD_parallel);
4772 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004773 case OMPD_cancellation_point:
4774 assert(ClausesWithImplicit.empty() &&
4775 "No clauses are allowed for 'omp cancellation point' directive");
4776 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4777 "cancellation point' directive");
4778 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4779 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004780 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004781 assert(AStmt == nullptr &&
4782 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004783 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4784 CancelRegion);
4785 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004786 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004787 case OMPD_target_data:
4788 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4789 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004790 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004791 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004792 case OMPD_target_enter_data:
4793 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004794 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004795 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4796 break;
Samuel Antao72590762016-01-19 20:04:50 +00004797 case OMPD_target_exit_data:
4798 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004799 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004800 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4801 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004802 case OMPD_taskloop:
4803 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4804 EndLoc, VarsWithInheritedDSA);
4805 AllowedNameModifiers.push_back(OMPD_taskloop);
4806 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004807 case OMPD_taskloop_simd:
4808 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4809 EndLoc, VarsWithInheritedDSA);
4810 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev61205822019-12-04 09:50:21 -05004811 if (LangOpts.OpenMP >= 50)
4812 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004813 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004814 case OMPD_master_taskloop:
4815 Res = ActOnOpenMPMasterTaskLoopDirective(
4816 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4817 AllowedNameModifiers.push_back(OMPD_taskloop);
4818 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004819 case OMPD_master_taskloop_simd:
4820 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4821 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4822 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev853961f2019-12-05 09:50:18 -05004823 if (LangOpts.OpenMP >= 50)
4824 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004825 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004826 case OMPD_parallel_master_taskloop:
4827 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4828 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4829 AllowedNameModifiers.push_back(OMPD_taskloop);
4830 AllowedNameModifiers.push_back(OMPD_parallel);
4831 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004832 case OMPD_parallel_master_taskloop_simd:
4833 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4834 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4835 AllowedNameModifiers.push_back(OMPD_taskloop);
4836 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5c517a62019-12-05 11:31:45 -05004837 if (LangOpts.OpenMP >= 50)
4838 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev14a388f2019-10-25 10:27:13 -04004839 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004840 case OMPD_distribute:
4841 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4842 EndLoc, VarsWithInheritedDSA);
4843 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004844 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004845 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4846 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004847 AllowedNameModifiers.push_back(OMPD_target_update);
4848 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004849 case OMPD_distribute_parallel_for:
4850 Res = ActOnOpenMPDistributeParallelForDirective(
4851 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4852 AllowedNameModifiers.push_back(OMPD_parallel);
4853 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004854 case OMPD_distribute_parallel_for_simd:
4855 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4856 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4857 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev52812f22019-12-05 13:22:15 -05004858 if (LangOpts.OpenMP >= 50)
4859 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4a39add2016-07-05 05:00:15 +00004860 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004861 case OMPD_distribute_simd:
4862 Res = ActOnOpenMPDistributeSimdDirective(
4863 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev779a1802019-12-06 12:21:31 -05004864 if (LangOpts.OpenMP >= 50)
4865 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li787f3fc2016-07-06 04:45:38 +00004866 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004867 case OMPD_target_parallel_for_simd:
4868 Res = ActOnOpenMPTargetParallelForSimdDirective(
4869 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4870 AllowedNameModifiers.push_back(OMPD_target);
4871 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevda17a532019-12-10 11:37:03 -05004872 if (LangOpts.OpenMP >= 50)
4873 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lia579b912016-07-14 02:54:56 +00004874 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004875 case OMPD_target_simd:
4876 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4877 EndLoc, VarsWithInheritedDSA);
4878 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataevef94cd12019-12-10 12:44:45 -05004879 if (LangOpts.OpenMP >= 50)
4880 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li986330c2016-07-20 22:57:10 +00004881 break;
Kelvin Li02532872016-08-05 14:37:37 +00004882 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004883 Res = ActOnOpenMPTeamsDistributeDirective(
4884 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004885 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004886 case OMPD_teams_distribute_simd:
4887 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4888 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev7b774b72019-12-11 11:20:47 -05004889 if (LangOpts.OpenMP >= 50)
4890 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4e325f72016-10-25 12:50:55 +00004891 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004892 case OMPD_teams_distribute_parallel_for_simd:
4893 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4894 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4895 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev0b978942019-12-11 15:26:38 -05004896 if (LangOpts.OpenMP >= 50)
4897 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li579e41c2016-11-30 23:51:03 +00004898 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004899 case OMPD_teams_distribute_parallel_for:
4900 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4901 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4902 AllowedNameModifiers.push_back(OMPD_parallel);
4903 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004904 case OMPD_target_teams:
4905 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4906 EndLoc);
4907 AllowedNameModifiers.push_back(OMPD_target);
4908 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004909 case OMPD_target_teams_distribute:
4910 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4911 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4912 AllowedNameModifiers.push_back(OMPD_target);
4913 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004914 case OMPD_target_teams_distribute_parallel_for:
4915 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4916 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4917 AllowedNameModifiers.push_back(OMPD_target);
4918 AllowedNameModifiers.push_back(OMPD_parallel);
4919 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004920 case OMPD_target_teams_distribute_parallel_for_simd:
4921 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4922 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4923 AllowedNameModifiers.push_back(OMPD_target);
4924 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevfd0c91b2019-12-16 10:27:39 -05004925 if (LangOpts.OpenMP >= 50)
4926 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li1851df52017-01-03 05:23:48 +00004927 break;
Kelvin Lida681182017-01-10 18:08:18 +00004928 case OMPD_target_teams_distribute_simd:
4929 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4930 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4931 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev411e81a2019-12-16 11:16:46 -05004932 if (LangOpts.OpenMP >= 50)
4933 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lida681182017-01-10 18:08:18 +00004934 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004935 case OMPD_declare_target:
4936 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004937 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004938 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004939 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004940 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004941 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004942 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004943 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004944 llvm_unreachable("OpenMP Directive is not allowed");
4945 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004946 llvm_unreachable("Unknown OpenMP directive");
4947 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004948
Roman Lebedevb5700602019-03-20 16:32:36 +00004949 ErrorFound = Res.isInvalid() || ErrorFound;
4950
Alexey Bataev412254a2019-05-09 18:44:53 +00004951 // Check variables in the clauses if default(none) was specified.
4952 if (DSAStack->getDefaultDSA() == DSA_none) {
4953 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4954 for (OMPClause *C : Clauses) {
4955 switch (C->getClauseKind()) {
4956 case OMPC_num_threads:
4957 case OMPC_dist_schedule:
4958 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004959 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004960 break;
4961 continue;
4962 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004963 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004964 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4965 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004966 if (isOpenMPParallelDirective(Kind) &&
4967 isOpenMPTaskLoopDirective(Kind) &&
4968 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4969 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004970 continue;
4971 case OMPC_schedule:
4972 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004973 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004974 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004975 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004976 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004977 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004978 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004979 break;
4980 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004981 case OMPC_ordered:
4982 case OMPC_device:
4983 case OMPC_num_teams:
4984 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004985 case OMPC_hint:
4986 case OMPC_collapse:
4987 case OMPC_safelen:
4988 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004989 case OMPC_default:
4990 case OMPC_proc_bind:
4991 case OMPC_private:
4992 case OMPC_firstprivate:
4993 case OMPC_lastprivate:
4994 case OMPC_shared:
4995 case OMPC_reduction:
4996 case OMPC_task_reduction:
4997 case OMPC_in_reduction:
4998 case OMPC_linear:
4999 case OMPC_aligned:
5000 case OMPC_copyin:
5001 case OMPC_copyprivate:
5002 case OMPC_nowait:
5003 case OMPC_untied:
5004 case OMPC_mergeable:
5005 case OMPC_allocate:
5006 case OMPC_read:
5007 case OMPC_write:
5008 case OMPC_update:
5009 case OMPC_capture:
5010 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -05005011 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -05005012 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -05005013 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -05005014 case OMPC_relaxed:
Alexey Bataev412254a2019-05-09 18:44:53 +00005015 case OMPC_depend:
5016 case OMPC_threads:
5017 case OMPC_simd:
5018 case OMPC_map:
5019 case OMPC_nogroup:
5020 case OMPC_defaultmap:
5021 case OMPC_to:
5022 case OMPC_from:
5023 case OMPC_use_device_ptr:
5024 case OMPC_is_device_ptr:
Alexey Bataevb6e70842019-12-16 15:54:17 -05005025 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -05005026 case OMPC_order:
Alexey Bataev412254a2019-05-09 18:44:53 +00005027 continue;
5028 case OMPC_allocator:
5029 case OMPC_flush:
5030 case OMPC_threadprivate:
5031 case OMPC_uniform:
5032 case OMPC_unknown:
5033 case OMPC_unified_address:
5034 case OMPC_unified_shared_memory:
5035 case OMPC_reverse_offload:
5036 case OMPC_dynamic_allocators:
5037 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00005038 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00005039 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00005040 llvm_unreachable("Unexpected clause");
5041 }
5042 for (Stmt *CC : C->children()) {
5043 if (CC)
5044 DSAChecker.Visit(CC);
5045 }
5046 }
Alexey Bataevcb8e6912020-01-31 16:09:26 -05005047 for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
Alexey Bataev412254a2019-05-09 18:44:53 +00005048 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
5049 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005050 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00005051 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
5052 continue;
5053 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05005054 if (DSAStack->getDefaultDSA() == DSA_none) {
5055 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
5056 << P.first << P.second->getSourceRange();
5057 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
5058 } else if (getLangOpts().OpenMP >= 50) {
5059 Diag(P.second->getExprLoc(),
5060 diag::err_omp_defaultmap_no_attr_for_variable)
5061 << P.first << P.second->getSourceRange();
5062 Diag(DSAStack->getDefaultDSALocation(),
5063 diag::note_omp_defaultmap_attr_none);
5064 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00005065 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005066
5067 if (!AllowedNameModifiers.empty())
5068 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
5069 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00005070
Alexey Bataeved09d242014-05-28 05:53:51 +00005071 if (ErrorFound)
5072 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00005073
5074 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
5075 Res.getAs<OMPExecutableDirective>()
5076 ->getStructuredBlock()
5077 ->setIsOMPStructuredBlock(true);
5078 }
5079
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00005080 if (!CurContext->isDependentContext() &&
5081 isOpenMPTargetExecutionDirective(Kind) &&
5082 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
5083 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
5084 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
5085 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
5086 // Register target to DSA Stack.
5087 DSAStack->addTargetDirLocation(StartLoc);
5088 }
5089
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005090 return Res;
5091}
5092
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005093Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
5094 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00005095 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00005096 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
5097 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005098 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00005099 assert(Linears.size() == LinModifiers.size());
5100 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00005101 if (!DG || DG.get().isNull())
5102 return DeclGroupPtrTy();
5103
Alexey Bataevd158cf62019-09-13 20:18:17 +00005104 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005105 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005106 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5107 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005108 return DG;
5109 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005110 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00005111 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5112 ADecl = FTD->getTemplatedDecl();
5113
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005114 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5115 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005116 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005117 return DeclGroupPtrTy();
5118 }
5119
Alexey Bataev2af33e32016-04-07 12:45:37 +00005120 // OpenMP [2.8.2, declare simd construct, Description]
5121 // The parameter of the simdlen clause must be a constant positive integer
5122 // expression.
5123 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005124 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00005125 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005126 // OpenMP [2.8.2, declare simd construct, Description]
5127 // The special this pointer can be used as if was one of the arguments to the
5128 // function in any of the linear, aligned, or uniform clauses.
5129 // The uniform clause declares one or more arguments to have an invariant
5130 // value for all concurrent invocations of the function in the execution of a
5131 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00005132 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5133 const Expr *UniformedLinearThis = nullptr;
5134 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005135 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005136 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5137 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005138 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5139 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00005140 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00005141 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005142 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005143 }
5144 if (isa<CXXThisExpr>(E)) {
5145 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005146 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005147 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005148 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5149 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00005150 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00005151 // OpenMP [2.8.2, declare simd construct, Description]
5152 // The aligned clause declares that the object to which each list item points
5153 // is aligned to the number of bytes expressed in the optional parameter of
5154 // the aligned clause.
5155 // The special this pointer can be used as if was one of the arguments to the
5156 // function in any of the linear, aligned, or uniform clauses.
5157 // The type of list items appearing in the aligned clause must be array,
5158 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00005159 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5160 const Expr *AlignedThis = nullptr;
5161 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005162 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005163 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5164 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5165 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005166 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5167 FD->getParamDecl(PVD->getFunctionScopeIndex())
5168 ->getCanonicalDecl() == CanonPVD) {
5169 // OpenMP [2.8.1, simd construct, Restrictions]
5170 // A list-item cannot appear in more than one aligned clause.
5171 if (AlignedArgs.count(CanonPVD) > 0) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005172 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5173 << 1 << getOpenMPClauseName(OMPC_aligned)
5174 << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005175 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5176 diag::note_omp_explicit_dsa)
5177 << getOpenMPClauseName(OMPC_aligned);
5178 continue;
5179 }
5180 AlignedArgs[CanonPVD] = E;
5181 QualType QTy = PVD->getType()
5182 .getNonReferenceType()
5183 .getUnqualifiedType()
5184 .getCanonicalType();
5185 const Type *Ty = QTy.getTypePtrOrNull();
5186 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5187 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5188 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5189 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5190 }
5191 continue;
5192 }
5193 }
5194 if (isa<CXXThisExpr>(E)) {
5195 if (AlignedThis) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005196 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5197 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005198 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5199 << getOpenMPClauseName(OMPC_aligned);
5200 }
5201 AlignedThis = E;
5202 continue;
5203 }
5204 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5205 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5206 }
5207 // The optional parameter of the aligned clause, alignment, must be a constant
5208 // positive integer expression. If no optional parameter is specified,
5209 // implementation-defined default alignments for SIMD instructions on the
5210 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005211 SmallVector<const Expr *, 4> NewAligns;
5212 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005213 ExprResult Align;
5214 if (E)
5215 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5216 NewAligns.push_back(Align.get());
5217 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005218 // OpenMP [2.8.2, declare simd construct, Description]
5219 // The linear clause declares one or more list items to be private to a SIMD
5220 // lane and to have a linear relationship with respect to the iteration space
5221 // of a loop.
5222 // The special this pointer can be used as if was one of the arguments to the
5223 // function in any of the linear, aligned, or uniform clauses.
5224 // When a linear-step expression is specified in a linear clause it must be
5225 // either a constant integer expression or an integer-typed parameter that is
5226 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005227 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005228 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5229 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005230 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005231 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5232 ++MI;
5233 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005234 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5235 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5236 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005237 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5238 FD->getParamDecl(PVD->getFunctionScopeIndex())
5239 ->getCanonicalDecl() == CanonPVD) {
5240 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5241 // A list-item cannot appear in more than one linear clause.
5242 if (LinearArgs.count(CanonPVD) > 0) {
5243 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5244 << getOpenMPClauseName(OMPC_linear)
5245 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5246 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5247 diag::note_omp_explicit_dsa)
5248 << getOpenMPClauseName(OMPC_linear);
5249 continue;
5250 }
5251 // Each argument can appear in at most one uniform or linear clause.
5252 if (UniformedArgs.count(CanonPVD) > 0) {
5253 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5254 << getOpenMPClauseName(OMPC_linear)
5255 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5256 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5257 diag::note_omp_explicit_dsa)
5258 << getOpenMPClauseName(OMPC_uniform);
5259 continue;
5260 }
5261 LinearArgs[CanonPVD] = E;
5262 if (E->isValueDependent() || E->isTypeDependent() ||
5263 E->isInstantiationDependent() ||
5264 E->containsUnexpandedParameterPack())
5265 continue;
5266 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5267 PVD->getOriginalType());
5268 continue;
5269 }
5270 }
5271 if (isa<CXXThisExpr>(E)) {
5272 if (UniformedLinearThis) {
5273 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5274 << getOpenMPClauseName(OMPC_linear)
5275 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5276 << E->getSourceRange();
5277 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5278 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5279 : OMPC_linear);
5280 continue;
5281 }
5282 UniformedLinearThis = E;
5283 if (E->isValueDependent() || E->isTypeDependent() ||
5284 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5285 continue;
5286 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5287 E->getType());
5288 continue;
5289 }
5290 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5291 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5292 }
5293 Expr *Step = nullptr;
5294 Expr *NewStep = nullptr;
5295 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005296 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005297 // Skip the same step expression, it was checked already.
5298 if (Step == E || !E) {
5299 NewSteps.push_back(E ? NewStep : nullptr);
5300 continue;
5301 }
5302 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005303 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5304 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5305 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005306 if (UniformedArgs.count(CanonPVD) == 0) {
5307 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5308 << Step->getSourceRange();
5309 } else if (E->isValueDependent() || E->isTypeDependent() ||
5310 E->isInstantiationDependent() ||
5311 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005312 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005313 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005314 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005315 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5316 << Step->getSourceRange();
5317 }
5318 continue;
5319 }
5320 NewStep = Step;
5321 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5322 !Step->isInstantiationDependent() &&
5323 !Step->containsUnexpandedParameterPack()) {
5324 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5325 .get();
5326 if (NewStep)
5327 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5328 }
5329 NewSteps.push_back(NewStep);
5330 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005331 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5332 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005333 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005334 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5335 const_cast<Expr **>(Linears.data()), Linears.size(),
5336 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5337 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005338 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005339 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005340}
5341
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005342static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5343 QualType NewType) {
5344 assert(NewType->isFunctionProtoType() &&
5345 "Expected function type with prototype.");
5346 assert(FD->getType()->isFunctionNoProtoType() &&
5347 "Expected function with type with no prototype.");
5348 assert(FDWithProto->getType()->isFunctionProtoType() &&
5349 "Expected function with prototype.");
5350 // Synthesize parameters with the same types.
5351 FD->setType(NewType);
5352 SmallVector<ParmVarDecl *, 16> Params;
5353 for (const ParmVarDecl *P : FDWithProto->parameters()) {
5354 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5355 SourceLocation(), nullptr, P->getType(),
5356 /*TInfo=*/nullptr, SC_None, nullptr);
5357 Param->setScopeInfo(0, Params.size());
5358 Param->setImplicit();
5359 Params.push_back(Param);
5360 }
5361
5362 FD->setParams(Params);
5363}
5364
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005365Optional<std::pair<FunctionDecl *, Expr *>>
5366Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5367 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005368 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005369 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005370
5371 const int VariantId = 1;
5372 // Must be applied only to single decl.
5373 if (!DG.get().isSingleDecl()) {
5374 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5375 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005376 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005377 }
5378 Decl *ADecl = DG.get().getSingleDecl();
5379 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5380 ADecl = FTD->getTemplatedDecl();
5381
5382 // Decl must be a function.
5383 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5384 if (!FD) {
5385 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5386 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005387 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005388 }
5389
5390 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5391 return FD->hasAttrs() &&
5392 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5393 FD->hasAttr<TargetAttr>());
5394 };
5395 // OpenMP is not compatible with CPU-specific attributes.
5396 if (HasMultiVersionAttributes(FD)) {
5397 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5398 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005399 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005400 }
5401
5402 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005403 if (FD->isUsed(false))
5404 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005405 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005406
5407 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005408 const FunctionDecl *Definition;
5409 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5410 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005411 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5412 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005413
5414 // The VariantRef must point to function.
5415 if (!VariantRef) {
5416 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005417 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005418 }
5419
5420 // Do not check templates, wait until instantiation.
5421 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5422 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005423 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5424 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005425
5426 // Convert VariantRef expression to the type of the original function to
5427 // resolve possible conflicts.
5428 ExprResult VariantRefCast;
5429 if (LangOpts.CPlusPlus) {
5430 QualType FnPtrType;
5431 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5432 if (Method && !Method->isStatic()) {
5433 const Type *ClassType =
5434 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5435 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5436 ExprResult ER;
5437 {
5438 // Build adrr_of unary op to correctly handle type checks for member
5439 // functions.
5440 Sema::TentativeAnalysisScope Trap(*this);
5441 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5442 VariantRef);
5443 }
5444 if (!ER.isUsable()) {
5445 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5446 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005447 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005448 }
5449 VariantRef = ER.get();
5450 } else {
5451 FnPtrType = Context.getPointerType(FD->getType());
5452 }
5453 ImplicitConversionSequence ICS =
5454 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5455 /*SuppressUserConversions=*/false,
Richard Smithd28763c2020-01-29 12:07:14 -08005456 AllowedExplicit::None,
Alexey Bataevd158cf62019-09-13 20:18:17 +00005457 /*InOverloadResolution=*/false,
5458 /*CStyle=*/false,
5459 /*AllowObjCWritebackConversion=*/false);
5460 if (ICS.isFailure()) {
5461 Diag(VariantRef->getExprLoc(),
5462 diag::err_omp_declare_variant_incompat_types)
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005463 << VariantRef->getType()
5464 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
5465 << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005466 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005467 }
5468 VariantRefCast = PerformImplicitConversion(
5469 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5470 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005471 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005472 // Drop previously built artificial addr_of unary op for member functions.
5473 if (Method && !Method->isStatic()) {
5474 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5475 if (auto *UO = dyn_cast<UnaryOperator>(
5476 PossibleAddrOfVariantRef->IgnoreImplicit()))
5477 VariantRefCast = UO->getSubExpr();
5478 }
5479 } else {
5480 VariantRefCast = VariantRef;
5481 }
5482
5483 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5484 if (!ER.isUsable() ||
5485 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5486 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5487 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005488 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005489 }
5490
5491 // The VariantRef must point to function.
5492 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5493 if (!DRE) {
5494 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5495 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005496 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005497 }
5498 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5499 if (!NewFD) {
5500 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5501 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005502 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005503 }
5504
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005505 // Check if function types are compatible in C.
5506 if (!LangOpts.CPlusPlus) {
5507 QualType NewType =
5508 Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
5509 if (NewType.isNull()) {
5510 Diag(VariantRef->getExprLoc(),
5511 diag::err_omp_declare_variant_incompat_types)
5512 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
5513 return None;
5514 }
5515 if (NewType->isFunctionProtoType()) {
5516 if (FD->getType()->isFunctionNoProtoType())
5517 setPrototype(*this, FD, NewFD, NewType);
5518 else if (NewFD->getType()->isFunctionNoProtoType())
5519 setPrototype(*this, NewFD, FD, NewType);
5520 }
5521 }
5522
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005523 // Check if variant function is not marked with declare variant directive.
5524 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5525 Diag(VariantRef->getExprLoc(),
5526 diag::warn_omp_declare_variant_marked_as_declare_variant)
5527 << VariantRef->getSourceRange();
5528 SourceRange SR =
5529 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5530 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005531 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005532 }
5533
Alexey Bataevd158cf62019-09-13 20:18:17 +00005534 enum DoesntSupport {
5535 VirtFuncs = 1,
5536 Constructors = 3,
5537 Destructors = 4,
5538 DeletedFuncs = 5,
5539 DefaultedFuncs = 6,
5540 ConstexprFuncs = 7,
5541 ConstevalFuncs = 8,
5542 };
5543 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5544 if (CXXFD->isVirtual()) {
5545 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5546 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005547 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005548 }
5549
5550 if (isa<CXXConstructorDecl>(FD)) {
5551 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5552 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005553 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005554 }
5555
5556 if (isa<CXXDestructorDecl>(FD)) {
5557 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5558 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005559 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005560 }
5561 }
5562
5563 if (FD->isDeleted()) {
5564 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5565 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005566 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005567 }
5568
5569 if (FD->isDefaulted()) {
5570 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5571 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005572 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005573 }
5574
5575 if (FD->isConstexpr()) {
5576 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5577 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005578 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005579 }
5580
5581 // Check general compatibility.
5582 if (areMultiversionVariantFunctionsCompatible(
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005583 FD, NewFD, PartialDiagnostic::NullDiagnostic(),
5584 PartialDiagnosticAt(SourceLocation(),
5585 PartialDiagnostic::NullDiagnostic()),
Alexey Bataevd158cf62019-09-13 20:18:17 +00005586 PartialDiagnosticAt(
5587 VariantRef->getExprLoc(),
5588 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5589 PartialDiagnosticAt(VariantRef->getExprLoc(),
5590 PDiag(diag::err_omp_declare_variant_diff)
5591 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005592 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5593 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005594 return None;
5595 return std::make_pair(FD, cast<Expr>(DRE));
5596}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005597
Alexey Bataev9ff34742019-09-25 19:43:37 +00005598void Sema::ActOnOpenMPDeclareVariantDirective(
5599 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005600 ArrayRef<OMPCtxSelectorData> Data) {
5601 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005602 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005603 SmallVector<Expr *, 4> CtxScores;
5604 SmallVector<unsigned, 4> CtxSets;
5605 SmallVector<unsigned, 4> Ctxs;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005606 SmallVector<StringRef, 4> ImplVendors, DeviceKinds;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005607 bool IsError = false;
5608 for (const OMPCtxSelectorData &D : Data) {
5609 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5610 OpenMPContextSelectorKind Ctx = D.Ctx;
5611 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5612 return;
5613 Expr *Score = nullptr;
5614 if (D.Score.isUsable()) {
5615 Score = D.Score.get();
5616 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5617 !Score->isInstantiationDependent() &&
5618 !Score->containsUnexpandedParameterPack()) {
5619 Score =
5620 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5621 .get();
5622 if (Score)
5623 Score = VerifyIntegerConstantExpression(Score).get();
5624 }
5625 } else {
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005626 // OpenMP 5.0, 2.3.3 Matching and Scoring Context Selectors.
5627 // The kind, arch, and isa selectors are given the values 2^l, 2^(l+1) and
5628 // 2^(l+2), respectively, where l is the number of traits in the construct
5629 // set.
5630 // TODO: implement correct logic for isa and arch traits.
5631 // TODO: take the construct context set into account when it is
5632 // implemented.
5633 int L = 0; // Currently set the number of traits in construct set to 0,
5634 // since the construct trait set in not supported yet.
5635 if (CtxSet == OMP_CTX_SET_device && Ctx == OMP_CTX_kind)
5636 Score = ActOnIntegerConstant(SourceLocation(), std::pow(2, L)).get();
5637 else
5638 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005639 }
Alexey Bataev5459a902019-11-22 11:42:08 -05005640 switch (Ctx) {
5641 case OMP_CTX_vendor:
5642 assert(CtxSet == OMP_CTX_SET_implementation &&
5643 "Expected implementation context selector set.");
5644 ImplVendors.append(D.Names.begin(), D.Names.end());
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005645 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005646 case OMP_CTX_kind:
5647 assert(CtxSet == OMP_CTX_SET_device &&
5648 "Expected device context selector set.");
5649 DeviceKinds.append(D.Names.begin(), D.Names.end());
Alexey Bataevfde11e92019-11-07 11:03:10 -05005650 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005651 case OMP_CTX_unknown:
5652 llvm_unreachable("Unknown context selector kind.");
Alexey Bataevfde11e92019-11-07 11:03:10 -05005653 }
5654 IsError = IsError || !Score;
5655 CtxSets.push_back(CtxSet);
5656 Ctxs.push_back(Ctx);
5657 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005658 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005659 if (!IsError) {
5660 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5661 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5662 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005663 ImplVendors.begin(), ImplVendors.size(), DeviceKinds.begin(),
5664 DeviceKinds.size(), SR);
Alexey Bataevfde11e92019-11-07 11:03:10 -05005665 FD->addAttr(NewAttr);
5666 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005667}
5668
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005669void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5670 FunctionDecl *Func,
5671 bool MightBeOdrUse) {
5672 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5673
5674 if (!Func->isDependentContext() && Func->hasAttrs()) {
5675 for (OMPDeclareVariantAttr *A :
5676 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5677 // TODO: add checks for active OpenMP context where possible.
5678 Expr *VariantRef = A->getVariantFuncRef();
Alexey Bataevf17a1d82019-12-02 14:15:38 -05005679 auto *DRE = cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005680 auto *F = cast<FunctionDecl>(DRE->getDecl());
5681 if (!F->isDefined() && F->isTemplateInstantiation())
5682 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5683 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5684 }
5685 }
5686}
5687
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005688StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5689 Stmt *AStmt,
5690 SourceLocation StartLoc,
5691 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005692 if (!AStmt)
5693 return StmtError();
5694
Alexey Bataeve3727102018-04-18 15:57:46 +00005695 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005696 // 1.2.2 OpenMP Language Terminology
5697 // Structured block - An executable statement with a single entry at the
5698 // top and a single exit at the bottom.
5699 // The point of exit cannot be a branch out of the structured block.
5700 // longjmp() and throw() must not violate the entry/exit criteria.
5701 CS->getCapturedDecl()->setNothrow();
5702
Reid Kleckner87a31802018-03-12 21:43:02 +00005703 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005704
Alexey Bataev25e5b442015-09-15 12:52:43 +00005705 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5706 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005707}
5708
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005709namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005710/// Iteration space of a single for loop.
5711struct LoopIterationSpace final {
5712 /// True if the condition operator is the strict compare operator (<, > or
5713 /// !=).
5714 bool IsStrictCompare = false;
5715 /// Condition of the loop.
5716 Expr *PreCond = nullptr;
5717 /// This expression calculates the number of iterations in the loop.
5718 /// It is always possible to calculate it before starting the loop.
5719 Expr *NumIterations = nullptr;
5720 /// The loop counter variable.
5721 Expr *CounterVar = nullptr;
5722 /// Private loop counter variable.
5723 Expr *PrivateCounterVar = nullptr;
5724 /// This is initializer for the initial value of #CounterVar.
5725 Expr *CounterInit = nullptr;
5726 /// This is step for the #CounterVar used to generate its update:
5727 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5728 Expr *CounterStep = nullptr;
5729 /// Should step be subtracted?
5730 bool Subtract = false;
5731 /// Source range of the loop init.
5732 SourceRange InitSrcRange;
5733 /// Source range of the loop condition.
5734 SourceRange CondSrcRange;
5735 /// Source range of the loop increment.
5736 SourceRange IncSrcRange;
5737 /// Minimum value that can have the loop control variable. Used to support
5738 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5739 /// since only such variables can be used in non-loop invariant expressions.
5740 Expr *MinValue = nullptr;
5741 /// Maximum value that can have the loop control variable. Used to support
5742 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5743 /// since only such variables can be used in non-loop invariant expressions.
5744 Expr *MaxValue = nullptr;
5745 /// true, if the lower bound depends on the outer loop control var.
5746 bool IsNonRectangularLB = false;
5747 /// true, if the upper bound depends on the outer loop control var.
5748 bool IsNonRectangularUB = false;
5749 /// Index of the loop this loop depends on and forms non-rectangular loop
5750 /// nest.
5751 unsigned LoopDependentIdx = 0;
5752 /// Final condition for the non-rectangular loop nest support. It is used to
5753 /// check that the number of iterations for this particular counter must be
5754 /// finished.
5755 Expr *FinalCondition = nullptr;
5756};
5757
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005758/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005759/// extracting iteration space of each loop in the loop nest, that will be used
5760/// for IR generation.
5761class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005762 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005763 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005764 /// Data-sharing stack.
5765 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005766 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005767 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005768 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005769 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005770 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005771 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005772 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005773 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005774 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005775 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005776 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005777 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005778 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005779 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005780 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005781 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005782 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005783 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005784 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005785 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005786 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005787 /// Var < UB
5788 /// Var <= UB
5789 /// UB > Var
5790 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005791 /// This will have no value when the condition is !=
5792 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005793 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005794 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005795 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005796 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005797 /// The outer loop counter this loop depends on (if any).
5798 const ValueDecl *DepDecl = nullptr;
5799 /// Contains number of loop (starts from 1) on which loop counter init
5800 /// expression of this loop depends on.
5801 Optional<unsigned> InitDependOnLC;
5802 /// Contains number of loop (starts from 1) on which loop counter condition
5803 /// expression of this loop depends on.
5804 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005805 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005806 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005807 /// Original condition required for checking of the exit condition for
5808 /// non-rectangular loop.
5809 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005810
5811public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005812 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5813 SourceLocation DefaultLoc)
5814 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5815 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005816 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005817 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005818 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005819 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005820 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005821 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005822 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005823 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005824 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005825 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005826 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005827 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005828 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005829 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005830 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005831 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005832 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005833 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005834 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005835 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005836 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005837 /// True, if the compare operator is strict (<, > or !=).
5838 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005839 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005840 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005841 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005842 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005843 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005844 Expr *
5845 buildPreCond(Scope *S, Expr *Cond,
5846 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005847 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005848 DeclRefExpr *
5849 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5850 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005851 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005852 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005853 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005854 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005855 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005856 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005857 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005858 /// Build loop data with counter value for depend clauses in ordered
5859 /// directives.
5860 Expr *
5861 buildOrderedLoopData(Scope *S, Expr *Counter,
5862 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5863 SourceLocation Loc, Expr *Inc = nullptr,
5864 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005865 /// Builds the minimum value for the loop counter.
5866 std::pair<Expr *, Expr *> buildMinMaxValues(
5867 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5868 /// Builds final condition for the non-rectangular loops.
5869 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005870 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005871 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005872 /// Returns true if the initializer forms non-rectangular loop.
5873 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5874 /// Returns true if the condition forms non-rectangular loop.
5875 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5876 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5877 unsigned getLoopDependentIdx() const {
5878 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5879 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005880
5881private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005882 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005883 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005884 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005885 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005886 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5887 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005888 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005889 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5890 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005891 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005892 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005893};
5894
Alexey Bataeve3727102018-04-18 15:57:46 +00005895bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005896 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005897 assert(!LB && !UB && !Step);
5898 return false;
5899 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005900 return LCDecl->getType()->isDependentType() ||
5901 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5902 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005903}
5904
Alexey Bataeve3727102018-04-18 15:57:46 +00005905bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005906 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005907 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005908 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005909 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005910 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005911 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005912 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005913 LCDecl = getCanonicalDecl(NewLCDecl);
5914 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005915 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5916 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005917 if ((Ctor->isCopyOrMoveConstructor() ||
5918 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5919 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005920 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005921 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005922 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005923 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005924 return false;
5925}
5926
Alexey Bataev316ccf62019-01-29 18:51:58 +00005927bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5928 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005929 bool StrictOp, SourceRange SR,
5930 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005931 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005932 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5933 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005934 if (!NewUB)
5935 return true;
5936 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005937 if (LessOp)
5938 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005939 TestIsStrictOp = StrictOp;
5940 ConditionSrcRange = SR;
5941 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005942 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005943 return false;
5944}
5945
Alexey Bataeve3727102018-04-18 15:57:46 +00005946bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005947 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005948 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005949 if (!NewStep)
5950 return true;
5951 if (!NewStep->isValueDependent()) {
5952 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005953 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005954 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5955 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005956 if (Val.isInvalid())
5957 return true;
5958 NewStep = Val.get();
5959
5960 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5961 // If test-expr is of form var relational-op b and relational-op is < or
5962 // <= then incr-expr must cause var to increase on each iteration of the
5963 // loop. If test-expr is of form var relational-op b and relational-op is
5964 // > or >= then incr-expr must cause var to decrease on each iteration of
5965 // the loop.
5966 // If test-expr is of form b relational-op var and relational-op is < or
5967 // <= then incr-expr must cause var to decrease on each iteration of the
5968 // loop. If test-expr is of form b relational-op var and relational-op is
5969 // > or >= then incr-expr must cause var to increase on each iteration of
5970 // the loop.
5971 llvm::APSInt Result;
5972 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5973 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5974 bool IsConstNeg =
5975 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005976 bool IsConstPos =
5977 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005978 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005979
5980 // != with increment is treated as <; != with decrement is treated as >
5981 if (!TestIsLessOp.hasValue())
5982 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005983 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005984 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005985 (IsConstNeg || (IsUnsigned && Subtract)) :
5986 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005987 SemaRef.Diag(NewStep->getExprLoc(),
5988 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005989 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005990 SemaRef.Diag(ConditionLoc,
5991 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005992 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005993 return true;
5994 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005995 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005996 NewStep =
5997 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5998 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005999 Subtract = !Subtract;
6000 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006001 }
6002
6003 Step = NewStep;
6004 SubtractStep = Subtract;
6005 return false;
6006}
6007
Alexey Bataev622af1d2019-04-24 19:58:30 +00006008namespace {
6009/// Checker for the non-rectangular loops. Checks if the initializer or
6010/// condition expression references loop counter variable.
6011class LoopCounterRefChecker final
6012 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
6013 Sema &SemaRef;
6014 DSAStackTy &Stack;
6015 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006016 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006017 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006018 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006019 unsigned BaseLoopId = 0;
6020 bool checkDecl(const Expr *E, const ValueDecl *VD) {
6021 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
6022 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
6023 << (IsInitializer ? 0 : 1);
6024 return false;
6025 }
6026 const auto &&Data = Stack.isLoopControlVariable(VD);
6027 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
6028 // The type of the loop iterator on which we depend may not have a random
6029 // access iterator type.
6030 if (Data.first && VD->getType()->isRecordType()) {
6031 SmallString<128> Name;
6032 llvm::raw_svector_ostream OS(Name);
6033 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6034 /*Qualified=*/true);
6035 SemaRef.Diag(E->getExprLoc(),
6036 diag::err_omp_wrong_dependency_iterator_type)
6037 << OS.str();
6038 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
6039 return false;
6040 }
6041 if (Data.first &&
6042 (DepDecl || (PrevDepDecl &&
6043 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
6044 if (!DepDecl && PrevDepDecl)
6045 DepDecl = PrevDepDecl;
6046 SmallString<128> Name;
6047 llvm::raw_svector_ostream OS(Name);
6048 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6049 /*Qualified=*/true);
6050 SemaRef.Diag(E->getExprLoc(),
6051 diag::err_omp_invariant_or_linear_dependency)
6052 << OS.str();
6053 return false;
6054 }
6055 if (Data.first) {
6056 DepDecl = VD;
6057 BaseLoopId = Data.first;
6058 }
6059 return Data.first;
6060 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00006061
6062public:
6063 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6064 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006065 if (isa<VarDecl>(VD))
6066 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00006067 return false;
6068 }
6069 bool VisitMemberExpr(const MemberExpr *E) {
6070 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
6071 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00006072 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
6073 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00006074 }
6075 return false;
6076 }
6077 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006078 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006079 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00006080 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006081 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006082 }
6083 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006084 const ValueDecl *CurLCDecl, bool IsInitializer,
6085 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00006086 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006087 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
6088 unsigned getBaseLoopId() const {
6089 assert(CurLCDecl && "Expected loop dependency.");
6090 return BaseLoopId;
6091 }
6092 const ValueDecl *getDepDecl() const {
6093 assert(CurLCDecl && "Expected loop dependency.");
6094 return DepDecl;
6095 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00006096};
6097} // namespace
6098
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006099Optional<unsigned>
6100OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6101 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00006102 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006103 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6104 DepDecl);
6105 if (LoopStmtChecker.Visit(S)) {
6106 DepDecl = LoopStmtChecker.getDepDecl();
6107 return LoopStmtChecker.getBaseLoopId();
6108 }
6109 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006110}
6111
Alexey Bataeve3727102018-04-18 15:57:46 +00006112bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006113 // Check init-expr for canonical loop form and save loop counter
6114 // variable - #Var and its initialization value - #LB.
6115 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6116 // var = lb
6117 // integer-type var = lb
6118 // random-access-iterator-type var = lb
6119 // pointer-type var = lb
6120 //
6121 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00006122 if (EmitDiags) {
6123 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6124 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006125 return true;
6126 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006127 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6128 if (!ExprTemp->cleanupsHaveSideEffects())
6129 S = ExprTemp->getSubExpr();
6130
Alexander Musmana5f070a2014-10-01 06:03:56 +00006131 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006132 if (Expr *E = dyn_cast<Expr>(S))
6133 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006134 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006135 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006136 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006137 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6138 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6139 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006140 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6141 EmitDiags);
6142 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006143 }
6144 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6145 if (ME->isArrow() &&
6146 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006147 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6148 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006149 }
6150 }
David Majnemer9d168222016-08-05 17:44:54 +00006151 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006152 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00006153 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00006154 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006155 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00006156 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006157 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006158 diag::ext_omp_loop_not_canonical_init)
6159 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00006160 return setLCDeclAndLB(
6161 Var,
6162 buildDeclRefExpr(SemaRef, Var,
6163 Var->getType().getNonReferenceType(),
6164 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00006165 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006166 }
6167 }
6168 }
David Majnemer9d168222016-08-05 17:44:54 +00006169 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006170 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006171 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00006172 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006173 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6174 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006175 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6176 EmitDiags);
6177 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006178 }
6179 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6180 if (ME->isArrow() &&
6181 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006182 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6183 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006184 }
6185 }
6186 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006187
Alexey Bataeve3727102018-04-18 15:57:46 +00006188 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006189 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00006190 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006191 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00006192 << S->getSourceRange();
6193 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006194 return true;
6195}
6196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006197/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006198/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00006199static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006200 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00006201 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006202 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00006203 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006204 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00006205 if ((Ctor->isCopyOrMoveConstructor() ||
6206 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6207 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006208 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00006209 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6210 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006211 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006212 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006213 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006214 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6215 return getCanonicalDecl(ME->getMemberDecl());
6216 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006217}
6218
Alexey Bataeve3727102018-04-18 15:57:46 +00006219bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006220 // Check test-expr for canonical form, save upper-bound UB, flags for
6221 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00006222 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006223 // var relational-op b
6224 // b relational-op var
6225 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006226 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006227 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006228 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6229 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006230 return true;
6231 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006232 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006233 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006234 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006235 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006236 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006237 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6238 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006239 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6240 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6241 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006242 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6243 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006244 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6245 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6246 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006247 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6248 return setUB(
6249 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6250 /*LessOp=*/llvm::None,
6251 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006252 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006253 if (CE->getNumArgs() == 2) {
6254 auto Op = CE->getOperator();
6255 switch (Op) {
6256 case OO_Greater:
6257 case OO_GreaterEqual:
6258 case OO_Less:
6259 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006260 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6261 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006262 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6263 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006264 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6265 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006266 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6267 CE->getOperatorLoc());
6268 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006269 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006270 if (IneqCondIsCanonical)
6271 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6272 : CE->getArg(0),
6273 /*LessOp=*/llvm::None,
6274 /*StrictOp=*/true, CE->getSourceRange(),
6275 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006276 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006277 default:
6278 break;
6279 }
6280 }
6281 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006282 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006283 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006284 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006285 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006286 return true;
6287}
6288
Alexey Bataeve3727102018-04-18 15:57:46 +00006289bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006290 // RHS of canonical loop form increment can be:
6291 // var + incr
6292 // incr + var
6293 // var - incr
6294 //
6295 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006296 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006297 if (BO->isAdditiveOp()) {
6298 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006299 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6300 return setStep(BO->getRHS(), !IsAdd);
6301 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6302 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006303 }
David Majnemer9d168222016-08-05 17:44:54 +00006304 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006305 bool IsAdd = CE->getOperator() == OO_Plus;
6306 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006307 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6308 return setStep(CE->getArg(1), !IsAdd);
6309 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6310 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006311 }
6312 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006313 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006314 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006315 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006316 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006317 return true;
6318}
6319
Alexey Bataeve3727102018-04-18 15:57:46 +00006320bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006321 // Check incr-expr for canonical loop form and return true if it
6322 // does not conform.
6323 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6324 // ++var
6325 // var++
6326 // --var
6327 // var--
6328 // var += incr
6329 // var -= incr
6330 // var = var + incr
6331 // var = incr + var
6332 // var = var - incr
6333 //
6334 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006335 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006336 return true;
6337 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006338 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6339 if (!ExprTemp->cleanupsHaveSideEffects())
6340 S = ExprTemp->getSubExpr();
6341
Alexander Musmana5f070a2014-10-01 06:03:56 +00006342 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006343 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006344 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006345 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006346 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6347 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006348 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006349 (UO->isDecrementOp() ? -1 : 1))
6350 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006351 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006352 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006353 switch (BO->getOpcode()) {
6354 case BO_AddAssign:
6355 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006356 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6357 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006358 break;
6359 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006360 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6361 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006362 break;
6363 default:
6364 break;
6365 }
David Majnemer9d168222016-08-05 17:44:54 +00006366 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006367 switch (CE->getOperator()) {
6368 case OO_PlusPlus:
6369 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006370 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6371 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006372 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006373 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006374 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6375 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006376 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006377 break;
6378 case OO_PlusEqual:
6379 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006380 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6381 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006382 break;
6383 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006384 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6385 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006386 break;
6387 default:
6388 break;
6389 }
6390 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006391 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006392 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006393 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006394 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006395 return true;
6396}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006397
Alexey Bataev5a3af132016-03-29 08:58:54 +00006398static ExprResult
6399tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006400 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006401 if (SemaRef.CurContext->isDependentContext())
6402 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006403 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6404 return SemaRef.PerformImplicitConversion(
6405 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6406 /*AllowExplicit=*/true);
6407 auto I = Captures.find(Capture);
6408 if (I != Captures.end())
6409 return buildCapture(SemaRef, Capture, I->second);
6410 DeclRefExpr *Ref = nullptr;
6411 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6412 Captures[Capture] = Ref;
6413 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006414}
6415
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006416/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006417Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006418 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006419 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006420 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006421 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006422 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006423 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006424 Expr *LBVal = LB;
6425 Expr *UBVal = UB;
6426 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6427 // max(LB(MinVal), LB(MaxVal))
6428 if (InitDependOnLC) {
6429 const LoopIterationSpace &IS =
6430 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6431 InitDependOnLC.getValueOr(
6432 CondDependOnLC.getValueOr(0))];
6433 if (!IS.MinValue || !IS.MaxValue)
6434 return nullptr;
6435 // OuterVar = Min
6436 ExprResult MinValue =
6437 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6438 if (!MinValue.isUsable())
6439 return nullptr;
6440
6441 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6442 IS.CounterVar, MinValue.get());
6443 if (!LBMinVal.isUsable())
6444 return nullptr;
6445 // OuterVar = Min, LBVal
6446 LBMinVal =
6447 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6448 if (!LBMinVal.isUsable())
6449 return nullptr;
6450 // (OuterVar = Min, LBVal)
6451 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6452 if (!LBMinVal.isUsable())
6453 return nullptr;
6454
6455 // OuterVar = Max
6456 ExprResult MaxValue =
6457 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6458 if (!MaxValue.isUsable())
6459 return nullptr;
6460
6461 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6462 IS.CounterVar, MaxValue.get());
6463 if (!LBMaxVal.isUsable())
6464 return nullptr;
6465 // OuterVar = Max, LBVal
6466 LBMaxVal =
6467 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6468 if (!LBMaxVal.isUsable())
6469 return nullptr;
6470 // (OuterVar = Max, LBVal)
6471 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6472 if (!LBMaxVal.isUsable())
6473 return nullptr;
6474
6475 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6476 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6477 if (!LBMin || !LBMax)
6478 return nullptr;
6479 // LB(MinVal) < LB(MaxVal)
6480 ExprResult MinLessMaxRes =
6481 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6482 if (!MinLessMaxRes.isUsable())
6483 return nullptr;
6484 Expr *MinLessMax =
6485 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6486 if (!MinLessMax)
6487 return nullptr;
6488 if (TestIsLessOp.getValue()) {
6489 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6490 // LB(MaxVal))
6491 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6492 MinLessMax, LBMin, LBMax);
6493 if (!MinLB.isUsable())
6494 return nullptr;
6495 LBVal = MinLB.get();
6496 } else {
6497 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6498 // LB(MaxVal))
6499 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6500 MinLessMax, LBMax, LBMin);
6501 if (!MaxLB.isUsable())
6502 return nullptr;
6503 LBVal = MaxLB.get();
6504 }
6505 }
6506 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6507 // min(UB(MinVal), UB(MaxVal))
6508 if (CondDependOnLC) {
6509 const LoopIterationSpace &IS =
6510 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6511 InitDependOnLC.getValueOr(
6512 CondDependOnLC.getValueOr(0))];
6513 if (!IS.MinValue || !IS.MaxValue)
6514 return nullptr;
6515 // OuterVar = Min
6516 ExprResult MinValue =
6517 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6518 if (!MinValue.isUsable())
6519 return nullptr;
6520
6521 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6522 IS.CounterVar, MinValue.get());
6523 if (!UBMinVal.isUsable())
6524 return nullptr;
6525 // OuterVar = Min, UBVal
6526 UBMinVal =
6527 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6528 if (!UBMinVal.isUsable())
6529 return nullptr;
6530 // (OuterVar = Min, UBVal)
6531 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6532 if (!UBMinVal.isUsable())
6533 return nullptr;
6534
6535 // OuterVar = Max
6536 ExprResult MaxValue =
6537 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6538 if (!MaxValue.isUsable())
6539 return nullptr;
6540
6541 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6542 IS.CounterVar, MaxValue.get());
6543 if (!UBMaxVal.isUsable())
6544 return nullptr;
6545 // OuterVar = Max, UBVal
6546 UBMaxVal =
6547 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6548 if (!UBMaxVal.isUsable())
6549 return nullptr;
6550 // (OuterVar = Max, UBVal)
6551 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6552 if (!UBMaxVal.isUsable())
6553 return nullptr;
6554
6555 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6556 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6557 if (!UBMin || !UBMax)
6558 return nullptr;
6559 // UB(MinVal) > UB(MaxVal)
6560 ExprResult MinGreaterMaxRes =
6561 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6562 if (!MinGreaterMaxRes.isUsable())
6563 return nullptr;
6564 Expr *MinGreaterMax =
6565 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6566 if (!MinGreaterMax)
6567 return nullptr;
6568 if (TestIsLessOp.getValue()) {
6569 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6570 // UB(MaxVal))
6571 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6572 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6573 if (!MaxUB.isUsable())
6574 return nullptr;
6575 UBVal = MaxUB.get();
6576 } else {
6577 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6578 // UB(MaxVal))
6579 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6580 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6581 if (!MinUB.isUsable())
6582 return nullptr;
6583 UBVal = MinUB.get();
6584 }
6585 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006586 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006587 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6588 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006589 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6590 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006591 if (!Upper || !Lower)
6592 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006593
6594 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6595
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006596 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006597 // BuildBinOp already emitted error, this one is to point user to upper
6598 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006599 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006600 << Upper->getSourceRange() << Lower->getSourceRange();
6601 return nullptr;
6602 }
6603 }
6604
6605 if (!Diff.isUsable())
6606 return nullptr;
6607
6608 // Upper - Lower [- 1]
6609 if (TestIsStrictOp)
6610 Diff = SemaRef.BuildBinOp(
6611 S, DefaultLoc, BO_Sub, Diff.get(),
6612 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6613 if (!Diff.isUsable())
6614 return nullptr;
6615
6616 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006617 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006618 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006619 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006620 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006621 if (!Diff.isUsable())
6622 return nullptr;
6623
6624 // Parentheses (for dumping/debugging purposes only).
6625 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6626 if (!Diff.isUsable())
6627 return nullptr;
6628
6629 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006630 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006631 if (!Diff.isUsable())
6632 return nullptr;
6633
Alexander Musman174b3ca2014-10-06 11:16:29 +00006634 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006635 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006636 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006637 bool UseVarType = VarType->hasIntegerRepresentation() &&
6638 C.getTypeSize(Type) > C.getTypeSize(VarType);
6639 if (!Type->isIntegerType() || UseVarType) {
6640 unsigned NewSize =
6641 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6642 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6643 : Type->hasSignedIntegerRepresentation();
6644 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006645 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6646 Diff = SemaRef.PerformImplicitConversion(
6647 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6648 if (!Diff.isUsable())
6649 return nullptr;
6650 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006651 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006652 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006653 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6654 if (NewSize != C.getTypeSize(Type)) {
6655 if (NewSize < C.getTypeSize(Type)) {
6656 assert(NewSize == 64 && "incorrect loop var size");
6657 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6658 << InitSrcRange << ConditionSrcRange;
6659 }
6660 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006661 NewSize, Type->hasSignedIntegerRepresentation() ||
6662 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006663 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6664 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6665 Sema::AA_Converting, true);
6666 if (!Diff.isUsable())
6667 return nullptr;
6668 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006669 }
6670 }
6671
Alexander Musmana5f070a2014-10-01 06:03:56 +00006672 return Diff.get();
6673}
6674
Alexey Bataevf8be4762019-08-14 19:30:06 +00006675std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6676 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6677 // Do not build for iterators, they cannot be used in non-rectangular loop
6678 // nests.
6679 if (LCDecl->getType()->isRecordType())
6680 return std::make_pair(nullptr, nullptr);
6681 // If we subtract, the min is in the condition, otherwise the min is in the
6682 // init value.
6683 Expr *MinExpr = nullptr;
6684 Expr *MaxExpr = nullptr;
6685 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6686 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6687 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6688 : CondDependOnLC.hasValue();
6689 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6690 : InitDependOnLC.hasValue();
6691 Expr *Lower =
6692 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6693 Expr *Upper =
6694 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6695 if (!Upper || !Lower)
6696 return std::make_pair(nullptr, nullptr);
6697
6698 if (TestIsLessOp.getValue())
6699 MinExpr = Lower;
6700 else
6701 MaxExpr = Upper;
6702
6703 // Build minimum/maximum value based on number of iterations.
6704 ExprResult Diff;
6705 QualType VarType = LCDecl->getType().getNonReferenceType();
6706
6707 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6708 if (!Diff.isUsable())
6709 return std::make_pair(nullptr, nullptr);
6710
6711 // Upper - Lower [- 1]
6712 if (TestIsStrictOp)
6713 Diff = SemaRef.BuildBinOp(
6714 S, DefaultLoc, BO_Sub, Diff.get(),
6715 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6716 if (!Diff.isUsable())
6717 return std::make_pair(nullptr, nullptr);
6718
6719 // Upper - Lower [- 1] + Step
6720 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6721 if (!NewStep.isUsable())
6722 return std::make_pair(nullptr, nullptr);
6723
6724 // Parentheses (for dumping/debugging purposes only).
6725 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6726 if (!Diff.isUsable())
6727 return std::make_pair(nullptr, nullptr);
6728
6729 // (Upper - Lower [- 1]) / Step
6730 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6731 if (!Diff.isUsable())
6732 return std::make_pair(nullptr, nullptr);
6733
6734 // ((Upper - Lower [- 1]) / Step) * Step
6735 // Parentheses (for dumping/debugging purposes only).
6736 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6737 if (!Diff.isUsable())
6738 return std::make_pair(nullptr, nullptr);
6739
6740 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6741 if (!Diff.isUsable())
6742 return std::make_pair(nullptr, nullptr);
6743
6744 // Convert to the original type or ptrdiff_t, if original type is pointer.
6745 if (!VarType->isAnyPointerType() &&
6746 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6747 Diff = SemaRef.PerformImplicitConversion(
6748 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6749 } else if (VarType->isAnyPointerType() &&
6750 !SemaRef.Context.hasSameType(
6751 Diff.get()->getType(),
6752 SemaRef.Context.getUnsignedPointerDiffType())) {
6753 Diff = SemaRef.PerformImplicitConversion(
6754 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6755 Sema::AA_Converting, /*AllowExplicit=*/true);
6756 }
6757 if (!Diff.isUsable())
6758 return std::make_pair(nullptr, nullptr);
6759
6760 // Parentheses (for dumping/debugging purposes only).
6761 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6762 if (!Diff.isUsable())
6763 return std::make_pair(nullptr, nullptr);
6764
6765 if (TestIsLessOp.getValue()) {
6766 // MinExpr = Lower;
6767 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6768 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6769 if (!Diff.isUsable())
6770 return std::make_pair(nullptr, nullptr);
6771 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6772 if (!Diff.isUsable())
6773 return std::make_pair(nullptr, nullptr);
6774 MaxExpr = Diff.get();
6775 } else {
6776 // MaxExpr = Upper;
6777 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6778 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6779 if (!Diff.isUsable())
6780 return std::make_pair(nullptr, nullptr);
6781 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6782 if (!Diff.isUsable())
6783 return std::make_pair(nullptr, nullptr);
6784 MinExpr = Diff.get();
6785 }
6786
6787 return std::make_pair(MinExpr, MaxExpr);
6788}
6789
6790Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6791 if (InitDependOnLC || CondDependOnLC)
6792 return Condition;
6793 return nullptr;
6794}
6795
Alexey Bataeve3727102018-04-18 15:57:46 +00006796Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006797 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006798 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006799 // Do not build a precondition when the condition/initialization is dependent
6800 // to prevent pessimistic early loop exit.
6801 // TODO: this can be improved by calculating min/max values but not sure that
6802 // it will be very effective.
6803 if (CondDependOnLC || InitDependOnLC)
6804 return SemaRef.PerformImplicitConversion(
6805 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6806 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6807 /*AllowExplicit=*/true).get();
6808
Alexey Bataev62dbb972015-04-22 11:59:37 +00006809 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006810 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006811
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006812 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6813 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006814 if (!NewLB.isUsable() || !NewUB.isUsable())
6815 return nullptr;
6816
Alexey Bataeve3727102018-04-18 15:57:46 +00006817 ExprResult CondExpr =
6818 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006819 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006820 (TestIsStrictOp ? BO_LT : BO_LE) :
6821 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006822 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006823 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006824 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6825 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006826 CondExpr = SemaRef.PerformImplicitConversion(
6827 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6828 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006829 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006830
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006831 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006832 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6833}
6834
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006835/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006836DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006837 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6838 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006839 auto *VD = dyn_cast<VarDecl>(LCDecl);
6840 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006841 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6842 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006843 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006844 const DSAStackTy::DSAVarData Data =
6845 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006846 // If the loop control decl is explicitly marked as private, do not mark it
6847 // as captured again.
6848 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6849 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006850 return Ref;
6851 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006852 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006853}
6854
Alexey Bataeve3727102018-04-18 15:57:46 +00006855Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006856 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006857 QualType Type = LCDecl->getType().getNonReferenceType();
6858 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006859 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6860 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6861 isa<VarDecl>(LCDecl)
6862 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6863 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006864 if (PrivateVar->isInvalidDecl())
6865 return nullptr;
6866 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6867 }
6868 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006869}
6870
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006871/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006872Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006873
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006874/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006875Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006876
Alexey Bataevf138fda2018-08-13 19:04:24 +00006877Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6878 Scope *S, Expr *Counter,
6879 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6880 Expr *Inc, OverloadedOperatorKind OOK) {
6881 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6882 if (!Cnt)
6883 return nullptr;
6884 if (Inc) {
6885 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6886 "Expected only + or - operations for depend clauses.");
6887 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6888 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6889 if (!Cnt)
6890 return nullptr;
6891 }
6892 ExprResult Diff;
6893 QualType VarType = LCDecl->getType().getNonReferenceType();
6894 if (VarType->isIntegerType() || VarType->isPointerType() ||
6895 SemaRef.getLangOpts().CPlusPlus) {
6896 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006897 Expr *Upper = TestIsLessOp.getValue()
6898 ? Cnt
6899 : tryBuildCapture(SemaRef, UB, Captures).get();
6900 Expr *Lower = TestIsLessOp.getValue()
6901 ? tryBuildCapture(SemaRef, LB, Captures).get()
6902 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006903 if (!Upper || !Lower)
6904 return nullptr;
6905
6906 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6907
6908 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6909 // BuildBinOp already emitted error, this one is to point user to upper
6910 // and lower bound, and to tell what is passed to 'operator-'.
6911 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6912 << Upper->getSourceRange() << Lower->getSourceRange();
6913 return nullptr;
6914 }
6915 }
6916
6917 if (!Diff.isUsable())
6918 return nullptr;
6919
6920 // Parentheses (for dumping/debugging purposes only).
6921 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6922 if (!Diff.isUsable())
6923 return nullptr;
6924
6925 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6926 if (!NewStep.isUsable())
6927 return nullptr;
6928 // (Upper - Lower) / Step
6929 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6930 if (!Diff.isUsable())
6931 return nullptr;
6932
6933 return Diff.get();
6934}
Alexey Bataev23b69422014-06-18 07:08:49 +00006935} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006936
Alexey Bataev9c821032015-04-30 04:23:23 +00006937void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6938 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6939 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006940 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6941 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006942 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006943 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006944 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006945 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6946 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006947 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006948 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006949 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006950 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006951 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006952 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006953 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6954 /*WithInit=*/false);
6955 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006956 }
6957 }
6958 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006959 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6960 if (LD != D->getCanonicalDecl()) {
6961 DSAStack->resetPossibleLoopCounter();
6962 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6963 MarkDeclarationsReferencedInExpr(
6964 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6965 Var->getType().getNonLValueExprType(Context),
6966 ForLoc, /*RefersToCapture=*/true));
6967 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006968 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6969 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6970 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6971 // associated for-loop of a simd construct with just one associated
6972 // for-loop may be listed in a linear clause with a constant-linear-step
6973 // that is the increment of the associated for-loop. The loop iteration
6974 // variable(s) in the associated for-loop(s) of a for or parallel for
6975 // construct may be listed in a private or lastprivate clause.
6976 DSAStackTy::DSAVarData DVar =
6977 DSAStack->getTopDSA(D, /*FromParent=*/false);
6978 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6979 // is declared in the loop and it is predetermined as a private.
6980 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6981 OpenMPClauseKind PredeterminedCKind =
6982 isOpenMPSimdDirective(DKind)
6983 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6984 : OMPC_private;
6985 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6986 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6987 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6988 DVar.CKind != OMPC_private))) ||
6989 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006990 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006991 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006992 isOpenMPDistributeDirective(DKind)) &&
6993 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6994 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6995 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6996 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6997 << getOpenMPClauseName(DVar.CKind)
6998 << getOpenMPDirectiveName(DKind)
6999 << getOpenMPClauseName(PredeterminedCKind);
7000 if (DVar.RefExpr == nullptr)
7001 DVar.CKind = PredeterminedCKind;
7002 reportOriginalDsa(*this, DSAStack, D, DVar,
7003 /*IsLoopIterVar=*/true);
7004 } else if (LoopDeclRefExpr) {
7005 // Make the loop iteration variable private (for worksharing
7006 // constructs), linear (for simd directives with the only one
7007 // associated loop) or lastprivate (for simd directives with several
7008 // collapsed or ordered loops).
7009 if (DVar.CKind == OMPC_unknown)
7010 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
7011 PrivateRef);
7012 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007013 }
7014 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007015 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00007016 }
7017}
7018
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007019/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007020/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00007021static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00007022 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
7023 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007024 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
7025 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00007026 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007027 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00007028 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00007029 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007030 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00007031 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00007032 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00007033 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
7034 // Ranged for is supported only in OpenMP 5.0.
7035 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007036 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007037 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00007038 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00007039 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00007040 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007041 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
7042 SemaRef.Diag(DSA.getConstructLoc(),
7043 diag::note_omp_collapse_ordered_expr)
7044 << 2 << CollapseLoopCountExpr->getSourceRange()
7045 << OrderedLoopCountExpr->getSourceRange();
7046 else if (CollapseLoopCountExpr)
7047 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7048 diag::note_omp_collapse_ordered_expr)
7049 << 0 << CollapseLoopCountExpr->getSourceRange();
7050 else
7051 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7052 diag::note_omp_collapse_ordered_expr)
7053 << 1 << OrderedLoopCountExpr->getSourceRange();
7054 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007055 return true;
7056 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00007057 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
7058 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007059
Alexey Bataevbef93a92019-10-07 18:54:57 +00007060 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
7061 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007062
7063 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007064 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00007065 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007066 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007067
7068 bool HasErrors = false;
7069
7070 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00007071 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007072 // OpenMP [2.6, Canonical Loop Form]
7073 // Var is one of the following:
7074 // A variable of signed or unsigned integer type.
7075 // For C++, a variable of a random access iterator type.
7076 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00007077 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007078 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
7079 !VarType->isPointerType() &&
7080 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007081 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007082 << SemaRef.getLangOpts().CPlusPlus;
7083 HasErrors = true;
7084 }
7085
7086 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
7087 // a Construct
7088 // The loop iteration variable(s) in the associated for-loop(s) of a for or
7089 // parallel for construct is (are) private.
7090 // The loop iteration variable in the associated for-loop of a simd
7091 // construct with just one associated for-loop is linear with a
7092 // constant-linear-step that is the increment of the associated for-loop.
7093 // Exclude loop var from the list of variables with implicitly defined data
7094 // sharing attributes.
7095 VarsWithImplicitDSA.erase(LCDecl);
7096
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007097 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
7098
7099 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007100 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007101
7102 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007103 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007104 }
7105
Alexey Bataeve3727102018-04-18 15:57:46 +00007106 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007107 return HasErrors;
7108
Alexander Musmana5f070a2014-10-01 06:03:56 +00007109 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007110 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
7111 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007112 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
7113 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
7114 (isOpenMPWorksharingDirective(DKind) ||
7115 isOpenMPTaskLoopDirective(DKind) ||
7116 isOpenMPDistributeDirective(DKind)),
7117 Captures);
7118 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
7119 ISC.buildCounterVar(Captures, DSA);
7120 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
7121 ISC.buildPrivateCounterVar();
7122 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
7123 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
7124 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
7125 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
7126 ISC.getConditionSrcRange();
7127 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
7128 ISC.getIncrementSrcRange();
7129 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
7130 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
7131 ISC.isStrictTestOp();
7132 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
7133 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
7134 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
7135 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
7136 ISC.buildFinalCondition(DSA.getCurScope());
7137 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
7138 ISC.doesInitDependOnLC();
7139 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
7140 ISC.doesCondDependOnLC();
7141 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
7142 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007143
Alexey Bataevf8be4762019-08-14 19:30:06 +00007144 HasErrors |=
7145 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
7146 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
7147 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
7148 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
7149 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
7150 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007151 if (!HasErrors && DSA.isOrderedRegion()) {
7152 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7153 if (CurrentNestedLoopCount <
7154 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7155 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007156 CurrentNestedLoopCount,
7157 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007158 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007159 CurrentNestedLoopCount,
7160 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007161 }
7162 }
7163 for (auto &Pair : DSA.getDoacrossDependClauses()) {
7164 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7165 // Erroneous case - clause has some problems.
7166 continue;
7167 }
7168 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7169 Pair.second.size() <= CurrentNestedLoopCount) {
7170 // Erroneous case - clause has some problems.
7171 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7172 continue;
7173 }
7174 Expr *CntValue;
7175 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7176 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007177 DSA.getCurScope(),
7178 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007179 Pair.first->getDependencyLoc());
7180 else
7181 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007182 DSA.getCurScope(),
7183 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007184 Pair.first->getDependencyLoc(),
7185 Pair.second[CurrentNestedLoopCount].first,
7186 Pair.second[CurrentNestedLoopCount].second);
7187 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7188 }
7189 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007190
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007191 return HasErrors;
7192}
7193
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007194/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00007195static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00007196buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007197 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007198 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007199 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007200 ExprResult NewStart = IsNonRectangularLB
7201 ? Start.get()
7202 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00007203 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007204 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00007205 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00007206 VarRef.get()->getType())) {
7207 NewStart = SemaRef.PerformImplicitConversion(
7208 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7209 /*AllowExplicit=*/true);
7210 if (!NewStart.isUsable())
7211 return ExprError();
7212 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007213
Alexey Bataeve3727102018-04-18 15:57:46 +00007214 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007215 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7216 return Init;
7217}
7218
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007219/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00007220static ExprResult buildCounterUpdate(
7221 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7222 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007223 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007224 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007225 // Add parentheses (for debugging purposes only).
7226 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7227 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7228 !Step.isUsable())
7229 return ExprError();
7230
Alexey Bataev5a3af132016-03-29 08:58:54 +00007231 ExprResult NewStep = Step;
7232 if (Captures)
7233 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007234 if (NewStep.isInvalid())
7235 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007236 ExprResult Update =
7237 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007238 if (!Update.isUsable())
7239 return ExprError();
7240
Alexey Bataevc0214e02016-02-16 12:13:49 +00007241 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7242 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007243 if (!Start.isUsable())
7244 return ExprError();
7245 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7246 if (!NewStart.isUsable())
7247 return ExprError();
7248 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007249 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007250 if (NewStart.isInvalid())
7251 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007252
Alexey Bataevc0214e02016-02-16 12:13:49 +00007253 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7254 ExprResult SavedUpdate = Update;
7255 ExprResult UpdateVal;
7256 if (VarRef.get()->getType()->isOverloadableType() ||
7257 NewStart.get()->getType()->isOverloadableType() ||
7258 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007259 Sema::TentativeAnalysisScope Trap(SemaRef);
7260
Alexey Bataevc0214e02016-02-16 12:13:49 +00007261 Update =
7262 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7263 if (Update.isUsable()) {
7264 UpdateVal =
7265 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7266 VarRef.get(), SavedUpdate.get());
7267 if (UpdateVal.isUsable()) {
7268 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7269 UpdateVal.get());
7270 }
7271 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007272 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007273
Alexey Bataevc0214e02016-02-16 12:13:49 +00007274 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7275 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7276 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7277 NewStart.get(), SavedUpdate.get());
7278 if (!Update.isUsable())
7279 return ExprError();
7280
Alexey Bataev11481f52016-02-17 10:29:05 +00007281 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7282 VarRef.get()->getType())) {
7283 Update = SemaRef.PerformImplicitConversion(
7284 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7285 if (!Update.isUsable())
7286 return ExprError();
7287 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007288
7289 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7290 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007291 return Update;
7292}
7293
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007294/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007295/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007296static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007297 if (E == nullptr)
7298 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007299 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007300 QualType OldType = E->getType();
7301 unsigned HasBits = C.getTypeSize(OldType);
7302 if (HasBits >= Bits)
7303 return ExprResult(E);
7304 // OK to convert to signed, because new type has more bits than old.
7305 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7306 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7307 true);
7308}
7309
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007310/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007311/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007312static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007313 if (E == nullptr)
7314 return false;
7315 llvm::APSInt Result;
7316 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7317 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7318 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007319}
7320
Alexey Bataev5a3af132016-03-29 08:58:54 +00007321/// Build preinits statement for the given declarations.
7322static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007323 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007324 if (!PreInits.empty()) {
7325 return new (Context) DeclStmt(
7326 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7327 SourceLocation(), SourceLocation());
7328 }
7329 return nullptr;
7330}
7331
7332/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007333static Stmt *
7334buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007335 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007336 if (!Captures.empty()) {
7337 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007338 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007339 PreInits.push_back(Pair.second->getDecl());
7340 return buildPreInits(Context, PreInits);
7341 }
7342 return nullptr;
7343}
7344
7345/// Build postupdate expression for the given list of postupdates expressions.
7346static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7347 Expr *PostUpdate = nullptr;
7348 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007349 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007350 Expr *ConvE = S.BuildCStyleCastExpr(
7351 E->getExprLoc(),
7352 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7353 E->getExprLoc(), E)
7354 .get();
7355 PostUpdate = PostUpdate
7356 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7357 PostUpdate, ConvE)
7358 .get()
7359 : ConvE;
7360 }
7361 }
7362 return PostUpdate;
7363}
7364
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007365/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007366/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7367/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007368static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007369checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007370 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7371 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007372 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007373 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007374 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007375 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007376 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007377 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007378 if (!CollapseLoopCountExpr->isValueDependent() &&
7379 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007380 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007381 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007382 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007383 return 1;
7384 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007385 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007386 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007387 if (OrderedLoopCountExpr) {
7388 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007389 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007390 if (!OrderedLoopCountExpr->isValueDependent() &&
7391 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7392 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007393 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007394 if (Result.getLimitedValue() < NestedLoopCount) {
7395 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7396 diag::err_omp_wrong_ordered_loop_count)
7397 << OrderedLoopCountExpr->getSourceRange();
7398 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7399 diag::note_collapse_loop_count)
7400 << CollapseLoopCountExpr->getSourceRange();
7401 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007402 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007403 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007404 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007405 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007406 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007407 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007408 // This is helper routine for loop directives (e.g., 'for', 'simd',
7409 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007410 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007411 SmallVector<LoopIterationSpace, 4> IterSpaces(
7412 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007413 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007414 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007415 if (checkOpenMPIterationSpace(
7416 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7417 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007418 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007419 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007420 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007421 // OpenMP [2.8.1, simd construct, Restrictions]
7422 // All loops associated with the construct must be perfectly nested; that
7423 // is, there must be no intervening code nor any OpenMP directive between
7424 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007425 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7426 CurStmt = For->getBody();
7427 } else {
7428 assert(isa<CXXForRangeStmt>(CurStmt) &&
7429 "Expected canonical for or range-based for loops.");
7430 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7431 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007432 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7433 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007434 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007435 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7436 if (checkOpenMPIterationSpace(
7437 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7438 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007439 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007440 return 0;
7441 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7442 // Handle initialization of captured loop iterator variables.
7443 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7444 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7445 Captures[DRE] = DRE;
7446 }
7447 }
7448 // Move on to the next nested for loop, or to the loop body.
7449 // OpenMP [2.8.1, simd construct, Restrictions]
7450 // All loops associated with the construct must be perfectly nested; that
7451 // is, there must be no intervening code nor any OpenMP directive between
7452 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007453 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7454 CurStmt = For->getBody();
7455 } else {
7456 assert(isa<CXXForRangeStmt>(CurStmt) &&
7457 "Expected canonical for or range-based for loops.");
7458 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7459 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007460 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7461 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007462 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007463
Alexander Musmana5f070a2014-10-01 06:03:56 +00007464 Built.clear(/* size */ NestedLoopCount);
7465
7466 if (SemaRef.CurContext->isDependentContext())
7467 return NestedLoopCount;
7468
7469 // An example of what is generated for the following code:
7470 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007471 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007472 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007473 // for (k = 0; k < NK; ++k)
7474 // for (j = J0; j < NJ; j+=2) {
7475 // <loop body>
7476 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007477 //
7478 // We generate the code below.
7479 // Note: the loop body may be outlined in CodeGen.
7480 // Note: some counters may be C++ classes, operator- is used to find number of
7481 // iterations and operator+= to calculate counter value.
7482 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7483 // or i64 is currently supported).
7484 //
7485 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7486 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7487 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7488 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7489 // // similar updates for vars in clauses (e.g. 'linear')
7490 // <loop body (using local i and j)>
7491 // }
7492 // i = NI; // assign final values of counters
7493 // j = NJ;
7494 //
7495
7496 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7497 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007498 // Precondition tests if there is at least one iteration (all conditions are
7499 // true).
7500 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007501 Expr *N0 = IterSpaces[0].NumIterations;
7502 ExprResult LastIteration32 =
7503 widenIterationCount(/*Bits=*/32,
7504 SemaRef
7505 .PerformImplicitConversion(
7506 N0->IgnoreImpCasts(), N0->getType(),
7507 Sema::AA_Converting, /*AllowExplicit=*/true)
7508 .get(),
7509 SemaRef);
7510 ExprResult LastIteration64 = widenIterationCount(
7511 /*Bits=*/64,
7512 SemaRef
7513 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7514 Sema::AA_Converting,
7515 /*AllowExplicit=*/true)
7516 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007517 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007518
7519 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7520 return NestedLoopCount;
7521
Alexey Bataeve3727102018-04-18 15:57:46 +00007522 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007523 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7524
7525 Scope *CurScope = DSA.getCurScope();
7526 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007527 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007528 PreCond =
7529 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7530 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007531 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007532 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007533 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007534 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7535 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007536 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007537 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007538 SemaRef
7539 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7540 Sema::AA_Converting,
7541 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007542 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007543 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007544 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007545 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007546 SemaRef
7547 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7548 Sema::AA_Converting,
7549 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007550 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007551 }
7552
7553 // Choose either the 32-bit or 64-bit version.
7554 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007555 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7556 (LastIteration32.isUsable() &&
7557 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7558 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7559 fitsInto(
7560 /*Bits=*/32,
7561 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7562 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007563 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007564 QualType VType = LastIteration.get()->getType();
7565 QualType RealVType = VType;
7566 QualType StrideVType = VType;
7567 if (isOpenMPTaskLoopDirective(DKind)) {
7568 VType =
7569 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7570 StrideVType =
7571 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7572 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007573
7574 if (!LastIteration.isUsable())
7575 return 0;
7576
7577 // Save the number of iterations.
7578 ExprResult NumIterations = LastIteration;
7579 {
7580 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007581 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7582 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007583 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7584 if (!LastIteration.isUsable())
7585 return 0;
7586 }
7587
7588 // Calculate the last iteration number beforehand instead of doing this on
7589 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7590 llvm::APSInt Result;
7591 bool IsConstant =
7592 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7593 ExprResult CalcLastIteration;
7594 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007595 ExprResult SaveRef =
7596 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007597 LastIteration = SaveRef;
7598
7599 // Prepare SaveRef + 1.
7600 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007601 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007602 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7603 if (!NumIterations.isUsable())
7604 return 0;
7605 }
7606
7607 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7608
David Majnemer9d168222016-08-05 17:44:54 +00007609 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007610 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007611 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7612 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007613 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007614 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7615 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007616 SemaRef.AddInitializerToDecl(LBDecl,
7617 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7618 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007619
7620 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007621 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7622 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007623 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007624 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007625
7626 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7627 // This will be used to implement clause 'lastprivate'.
7628 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007629 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7630 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007631 SemaRef.AddInitializerToDecl(ILDecl,
7632 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7633 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007634
7635 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007636 VarDecl *STDecl =
7637 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7638 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007639 SemaRef.AddInitializerToDecl(STDecl,
7640 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7641 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007642
7643 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007644 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007645 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7646 UB.get(), LastIteration.get());
7647 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007648 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7649 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007650 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7651 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007652 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007653
7654 // If we have a combined directive that combines 'distribute', 'for' or
7655 // 'simd' we need to be able to access the bounds of the schedule of the
7656 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7657 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7658 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007659 // Lower bound variable, initialized with zero.
7660 VarDecl *CombLBDecl =
7661 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7662 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7663 SemaRef.AddInitializerToDecl(
7664 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7665 /*DirectInit*/ false);
7666
7667 // Upper bound variable, initialized with last iteration number.
7668 VarDecl *CombUBDecl =
7669 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7670 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7671 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7672 /*DirectInit*/ false);
7673
7674 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7675 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7676 ExprResult CombCondOp =
7677 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7678 LastIteration.get(), CombUB.get());
7679 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7680 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007681 CombEUB =
7682 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007683
Alexey Bataeve3727102018-04-18 15:57:46 +00007684 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007685 // We expect to have at least 2 more parameters than the 'parallel'
7686 // directive does - the lower and upper bounds of the previous schedule.
7687 assert(CD->getNumParams() >= 4 &&
7688 "Unexpected number of parameters in loop combined directive");
7689
7690 // Set the proper type for the bounds given what we learned from the
7691 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007692 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7693 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007694
7695 // Previous lower and upper bounds are obtained from the region
7696 // parameters.
7697 PrevLB =
7698 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7699 PrevUB =
7700 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7701 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007702 }
7703
7704 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007705 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007706 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007707 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007708 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7709 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007710 Expr *RHS =
7711 (isOpenMPWorksharingDirective(DKind) ||
7712 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7713 ? LB.get()
7714 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007715 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007716 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007717
7718 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7719 Expr *CombRHS =
7720 (isOpenMPWorksharingDirective(DKind) ||
7721 isOpenMPTaskLoopDirective(DKind) ||
7722 isOpenMPDistributeDirective(DKind))
7723 ? CombLB.get()
7724 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7725 CombInit =
7726 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007727 CombInit =
7728 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007729 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007730 }
7731
Alexey Bataev316ccf62019-01-29 18:51:58 +00007732 bool UseStrictCompare =
7733 RealVType->hasUnsignedIntegerRepresentation() &&
7734 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7735 return LIS.IsStrictCompare;
7736 });
7737 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7738 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007739 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007740 Expr *BoundUB = UB.get();
7741 if (UseStrictCompare) {
7742 BoundUB =
7743 SemaRef
7744 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7745 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7746 .get();
7747 BoundUB =
7748 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7749 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007750 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007751 (isOpenMPWorksharingDirective(DKind) ||
7752 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007753 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7754 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7755 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007756 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7757 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007758 ExprResult CombDistCond;
7759 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007760 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7761 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007762 }
7763
Carlo Bertolliffafe102017-04-20 00:39:39 +00007764 ExprResult CombCond;
7765 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007766 Expr *BoundCombUB = CombUB.get();
7767 if (UseStrictCompare) {
7768 BoundCombUB =
7769 SemaRef
7770 .BuildBinOp(
7771 CurScope, CondLoc, BO_Add, BoundCombUB,
7772 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7773 .get();
7774 BoundCombUB =
7775 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7776 .get();
7777 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007778 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007779 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7780 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007781 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007782 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007783 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007784 ExprResult Inc =
7785 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7786 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7787 if (!Inc.isUsable())
7788 return 0;
7789 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007790 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007791 if (!Inc.isUsable())
7792 return 0;
7793
7794 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7795 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007796 // In combined construct, add combined version that use CombLB and CombUB
7797 // base variables for the update
7798 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007799 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7800 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007801 // LB + ST
7802 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7803 if (!NextLB.isUsable())
7804 return 0;
7805 // LB = LB + ST
7806 NextLB =
7807 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007808 NextLB =
7809 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007810 if (!NextLB.isUsable())
7811 return 0;
7812 // UB + ST
7813 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7814 if (!NextUB.isUsable())
7815 return 0;
7816 // UB = UB + ST
7817 NextUB =
7818 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007819 NextUB =
7820 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007821 if (!NextUB.isUsable())
7822 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007823 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7824 CombNextLB =
7825 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7826 if (!NextLB.isUsable())
7827 return 0;
7828 // LB = LB + ST
7829 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7830 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007831 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7832 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007833 if (!CombNextLB.isUsable())
7834 return 0;
7835 // UB + ST
7836 CombNextUB =
7837 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7838 if (!CombNextUB.isUsable())
7839 return 0;
7840 // UB = UB + ST
7841 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7842 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007843 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7844 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007845 if (!CombNextUB.isUsable())
7846 return 0;
7847 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007848 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007849
Carlo Bertolliffafe102017-04-20 00:39:39 +00007850 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007851 // directive with for as IV = IV + ST; ensure upper bound expression based
7852 // on PrevUB instead of NumIterations - used to implement 'for' when found
7853 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007854 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007855 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007856 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007857 DistCond = SemaRef.BuildBinOp(
7858 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007859 assert(DistCond.isUsable() && "distribute cond expr was not built");
7860
7861 DistInc =
7862 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7863 assert(DistInc.isUsable() && "distribute inc expr was not built");
7864 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7865 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007866 DistInc =
7867 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007868 assert(DistInc.isUsable() && "distribute inc expr was not built");
7869
7870 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7871 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007872 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007873 ExprResult IsUBGreater =
7874 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7875 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7876 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7877 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7878 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007879 PrevEUB =
7880 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007881
Alexey Bataev316ccf62019-01-29 18:51:58 +00007882 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7883 // parallel for is in combination with a distribute directive with
7884 // schedule(static, 1)
7885 Expr *BoundPrevUB = PrevUB.get();
7886 if (UseStrictCompare) {
7887 BoundPrevUB =
7888 SemaRef
7889 .BuildBinOp(
7890 CurScope, CondLoc, BO_Add, BoundPrevUB,
7891 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7892 .get();
7893 BoundPrevUB =
7894 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7895 .get();
7896 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007897 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007898 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7899 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007900 }
7901
Alexander Musmana5f070a2014-10-01 06:03:56 +00007902 // Build updates and final values of the loop counters.
7903 bool HasErrors = false;
7904 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007905 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007906 Built.Updates.resize(NestedLoopCount);
7907 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007908 Built.DependentCounters.resize(NestedLoopCount);
7909 Built.DependentInits.resize(NestedLoopCount);
7910 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007911 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007912 // We implement the following algorithm for obtaining the
7913 // original loop iteration variable values based on the
7914 // value of the collapsed loop iteration variable IV.
7915 //
7916 // Let n+1 be the number of collapsed loops in the nest.
7917 // Iteration variables (I0, I1, .... In)
7918 // Iteration counts (N0, N1, ... Nn)
7919 //
7920 // Acc = IV;
7921 //
7922 // To compute Ik for loop k, 0 <= k <= n, generate:
7923 // Prod = N(k+1) * N(k+2) * ... * Nn;
7924 // Ik = Acc / Prod;
7925 // Acc -= Ik * Prod;
7926 //
7927 ExprResult Acc = IV;
7928 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007929 LoopIterationSpace &IS = IterSpaces[Cnt];
7930 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007931 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007932
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007933 // Compute prod
7934 ExprResult Prod =
7935 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7936 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7937 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7938 IterSpaces[K].NumIterations);
7939
7940 // Iter = Acc / Prod
7941 // If there is at least one more inner loop to avoid
7942 // multiplication by 1.
7943 if (Cnt + 1 < NestedLoopCount)
7944 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7945 Acc.get(), Prod.get());
7946 else
7947 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007948 if (!Iter.isUsable()) {
7949 HasErrors = true;
7950 break;
7951 }
7952
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007953 // Update Acc:
7954 // Acc -= Iter * Prod
7955 // Check if there is at least one more inner loop to avoid
7956 // multiplication by 1.
7957 if (Cnt + 1 < NestedLoopCount)
7958 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7959 Iter.get(), Prod.get());
7960 else
7961 Prod = Iter;
7962 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7963 Acc.get(), Prod.get());
7964
Alexey Bataev39f915b82015-05-08 10:41:21 +00007965 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007966 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007967 DeclRefExpr *CounterVar = buildDeclRefExpr(
7968 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7969 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007970 ExprResult Init =
7971 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7972 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007973 if (!Init.isUsable()) {
7974 HasErrors = true;
7975 break;
7976 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007977 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007978 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007979 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007980 if (!Update.isUsable()) {
7981 HasErrors = true;
7982 break;
7983 }
7984
7985 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007986 ExprResult Final =
7987 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7988 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7989 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007990 if (!Final.isUsable()) {
7991 HasErrors = true;
7992 break;
7993 }
7994
Alexander Musmana5f070a2014-10-01 06:03:56 +00007995 if (!Update.isUsable() || !Final.isUsable()) {
7996 HasErrors = true;
7997 break;
7998 }
7999 // Save results
8000 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00008001 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00008002 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008003 Built.Updates[Cnt] = Update.get();
8004 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00008005 Built.DependentCounters[Cnt] = nullptr;
8006 Built.DependentInits[Cnt] = nullptr;
8007 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00008008 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00008009 Built.DependentCounters[Cnt] =
8010 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
8011 Built.DependentInits[Cnt] =
8012 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
8013 Built.FinalsConditions[Cnt] = IS.FinalCondition;
8014 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00008015 }
8016 }
8017
8018 if (HasErrors)
8019 return 0;
8020
8021 // Save results
8022 Built.IterationVarRef = IV.get();
8023 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00008024 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00008025 Built.CalcLastIteration = SemaRef
8026 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00008027 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00008028 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008029 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008030 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00008031 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008032 Built.Init = Init.get();
8033 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00008034 Built.LB = LB.get();
8035 Built.UB = UB.get();
8036 Built.IL = IL.get();
8037 Built.ST = ST.get();
8038 Built.EUB = EUB.get();
8039 Built.NLB = NextLB.get();
8040 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00008041 Built.PrevLB = PrevLB.get();
8042 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00008043 Built.DistInc = DistInc.get();
8044 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00008045 Built.DistCombinedFields.LB = CombLB.get();
8046 Built.DistCombinedFields.UB = CombUB.get();
8047 Built.DistCombinedFields.EUB = CombEUB.get();
8048 Built.DistCombinedFields.Init = CombInit.get();
8049 Built.DistCombinedFields.Cond = CombCond.get();
8050 Built.DistCombinedFields.NLB = CombNextLB.get();
8051 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00008052 Built.DistCombinedFields.DistCond = CombDistCond.get();
8053 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008054
Alexey Bataevabfc0692014-06-25 06:52:00 +00008055 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008056}
8057
Alexey Bataev10e775f2015-07-30 11:36:16 +00008058static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00008059 auto CollapseClauses =
8060 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
8061 if (CollapseClauses.begin() != CollapseClauses.end())
8062 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00008063 return nullptr;
8064}
8065
Alexey Bataev10e775f2015-07-30 11:36:16 +00008066static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00008067 auto OrderedClauses =
8068 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
8069 if (OrderedClauses.begin() != OrderedClauses.end())
8070 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00008071 return nullptr;
8072}
8073
Kelvin Lic5609492016-07-15 04:39:07 +00008074static bool checkSimdlenSafelenSpecified(Sema &S,
8075 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008076 const OMPSafelenClause *Safelen = nullptr;
8077 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00008078
Alexey Bataeve3727102018-04-18 15:57:46 +00008079 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00008080 if (Clause->getClauseKind() == OMPC_safelen)
8081 Safelen = cast<OMPSafelenClause>(Clause);
8082 else if (Clause->getClauseKind() == OMPC_simdlen)
8083 Simdlen = cast<OMPSimdlenClause>(Clause);
8084 if (Safelen && Simdlen)
8085 break;
8086 }
8087
8088 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008089 const Expr *SimdlenLength = Simdlen->getSimdlen();
8090 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00008091 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
8092 SimdlenLength->isInstantiationDependent() ||
8093 SimdlenLength->containsUnexpandedParameterPack())
8094 return false;
8095 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
8096 SafelenLength->isInstantiationDependent() ||
8097 SafelenLength->containsUnexpandedParameterPack())
8098 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008099 Expr::EvalResult SimdlenResult, SafelenResult;
8100 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
8101 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
8102 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
8103 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00008104 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
8105 // If both simdlen and safelen clauses are specified, the value of the
8106 // simdlen parameter must be less than or equal to the value of the safelen
8107 // parameter.
8108 if (SimdlenRes > SafelenRes) {
8109 S.Diag(SimdlenLength->getExprLoc(),
8110 diag::err_omp_wrong_simdlen_safelen_values)
8111 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
8112 return true;
8113 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00008114 }
8115 return false;
8116}
8117
Alexey Bataeve3727102018-04-18 15:57:46 +00008118StmtResult
8119Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8120 SourceLocation StartLoc, SourceLocation EndLoc,
8121 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008122 if (!AStmt)
8123 return StmtError();
8124
8125 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008126 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008127 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8128 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008129 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008130 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8131 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008132 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008133 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008134
Alexander Musmana5f070a2014-10-01 06:03:56 +00008135 assert((CurContext->isDependentContext() || B.builtAll()) &&
8136 "omp simd loop exprs were not built");
8137
Alexander Musman3276a272015-03-21 10:12:56 +00008138 if (!CurContext->isDependentContext()) {
8139 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008140 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008141 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00008142 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008143 B.NumIterations, *this, CurScope,
8144 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00008145 return StmtError();
8146 }
8147 }
8148
Kelvin Lic5609492016-07-15 04:39:07 +00008149 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008150 return StmtError();
8151
Reid Kleckner87a31802018-03-12 21:43:02 +00008152 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008153 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8154 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008155}
8156
Alexey Bataeve3727102018-04-18 15:57:46 +00008157StmtResult
8158Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8159 SourceLocation StartLoc, SourceLocation EndLoc,
8160 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008161 if (!AStmt)
8162 return StmtError();
8163
8164 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008165 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008166 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8167 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008168 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008169 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8170 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008171 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00008172 return StmtError();
8173
Alexander Musmana5f070a2014-10-01 06:03:56 +00008174 assert((CurContext->isDependentContext() || B.builtAll()) &&
8175 "omp for loop exprs were not built");
8176
Alexey Bataev54acd402015-08-04 11:18:19 +00008177 if (!CurContext->isDependentContext()) {
8178 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008179 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008180 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008181 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008182 B.NumIterations, *this, CurScope,
8183 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008184 return StmtError();
8185 }
8186 }
8187
Reid Kleckner87a31802018-03-12 21:43:02 +00008188 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008189 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008190 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00008191}
8192
Alexander Musmanf82886e2014-09-18 05:12:34 +00008193StmtResult Sema::ActOnOpenMPForSimdDirective(
8194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008195 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008196 if (!AStmt)
8197 return StmtError();
8198
8199 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008200 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008201 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8202 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00008203 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008204 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008205 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8206 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008207 if (NestedLoopCount == 0)
8208 return StmtError();
8209
Alexander Musmanc6388682014-12-15 07:07:06 +00008210 assert((CurContext->isDependentContext() || B.builtAll()) &&
8211 "omp for simd loop exprs were not built");
8212
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008213 if (!CurContext->isDependentContext()) {
8214 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008215 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008216 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008217 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008218 B.NumIterations, *this, CurScope,
8219 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008220 return StmtError();
8221 }
8222 }
8223
Kelvin Lic5609492016-07-15 04:39:07 +00008224 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008225 return StmtError();
8226
Reid Kleckner87a31802018-03-12 21:43:02 +00008227 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008228 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8229 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008230}
8231
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008232StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8233 Stmt *AStmt,
8234 SourceLocation StartLoc,
8235 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008236 if (!AStmt)
8237 return StmtError();
8238
8239 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008240 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008241 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008242 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008243 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008244 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008245 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008246 return StmtError();
8247 // All associated statements must be '#pragma omp section' except for
8248 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008249 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008250 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8251 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008252 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008253 diag::err_omp_sections_substmt_not_section);
8254 return StmtError();
8255 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008256 cast<OMPSectionDirective>(SectionStmt)
8257 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008258 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008259 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008260 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008261 return StmtError();
8262 }
8263
Reid Kleckner87a31802018-03-12 21:43:02 +00008264 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008265
Alexey Bataev25e5b442015-09-15 12:52:43 +00008266 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8267 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008268}
8269
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008270StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8271 SourceLocation StartLoc,
8272 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008273 if (!AStmt)
8274 return StmtError();
8275
8276 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008277
Reid Kleckner87a31802018-03-12 21:43:02 +00008278 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008279 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008280
Alexey Bataev25e5b442015-09-15 12:52:43 +00008281 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8282 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008283}
8284
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008285StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8286 Stmt *AStmt,
8287 SourceLocation StartLoc,
8288 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008289 if (!AStmt)
8290 return StmtError();
8291
8292 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008293
Reid Kleckner87a31802018-03-12 21:43:02 +00008294 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008295
Alexey Bataev3255bf32015-01-19 05:20:46 +00008296 // OpenMP [2.7.3, single Construct, Restrictions]
8297 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008298 const OMPClause *Nowait = nullptr;
8299 const OMPClause *Copyprivate = nullptr;
8300 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008301 if (Clause->getClauseKind() == OMPC_nowait)
8302 Nowait = Clause;
8303 else if (Clause->getClauseKind() == OMPC_copyprivate)
8304 Copyprivate = Clause;
8305 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008306 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008307 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008308 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008309 return StmtError();
8310 }
8311 }
8312
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008313 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8314}
8315
Alexander Musman80c22892014-07-17 08:54:58 +00008316StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8317 SourceLocation StartLoc,
8318 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008319 if (!AStmt)
8320 return StmtError();
8321
8322 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008323
Reid Kleckner87a31802018-03-12 21:43:02 +00008324 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008325
8326 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8327}
8328
Alexey Bataev28c75412015-12-15 08:19:24 +00008329StmtResult Sema::ActOnOpenMPCriticalDirective(
8330 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8331 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008332 if (!AStmt)
8333 return StmtError();
8334
8335 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008336
Alexey Bataev28c75412015-12-15 08:19:24 +00008337 bool ErrorFound = false;
8338 llvm::APSInt Hint;
8339 SourceLocation HintLoc;
8340 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008341 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008342 if (C->getClauseKind() == OMPC_hint) {
8343 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008344 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008345 ErrorFound = true;
8346 }
8347 Expr *E = cast<OMPHintClause>(C)->getHint();
8348 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008349 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008350 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008351 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008352 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008353 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008354 }
8355 }
8356 }
8357 if (ErrorFound)
8358 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008359 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008360 if (Pair.first && DirName.getName() && !DependentHint) {
8361 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8362 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008363 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008364 Diag(HintLoc, diag::note_omp_critical_hint_here)
8365 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008366 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008367 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008368 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008369 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008370 << 1
8371 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8372 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008373 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008374 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008375 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008376 }
8377 }
8378
Reid Kleckner87a31802018-03-12 21:43:02 +00008379 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008380
Alexey Bataev28c75412015-12-15 08:19:24 +00008381 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8382 Clauses, AStmt);
8383 if (!Pair.first && DirName.getName() && !DependentHint)
8384 DSAStack->addCriticalWithHint(Dir, Hint);
8385 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008386}
8387
Alexey Bataev4acb8592014-07-07 13:01:15 +00008388StmtResult Sema::ActOnOpenMPParallelForDirective(
8389 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008390 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008391 if (!AStmt)
8392 return StmtError();
8393
Alexey Bataeve3727102018-04-18 15:57:46 +00008394 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008395 // 1.2.2 OpenMP Language Terminology
8396 // Structured block - An executable statement with a single entry at the
8397 // top and a single exit at the bottom.
8398 // The point of exit cannot be a branch out of the structured block.
8399 // longjmp() and throw() must not violate the entry/exit criteria.
8400 CS->getCapturedDecl()->setNothrow();
8401
Alexander Musmanc6388682014-12-15 07:07:06 +00008402 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008403 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8404 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008405 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008406 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008407 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8408 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008409 if (NestedLoopCount == 0)
8410 return StmtError();
8411
Alexander Musmana5f070a2014-10-01 06:03:56 +00008412 assert((CurContext->isDependentContext() || B.builtAll()) &&
8413 "omp parallel for loop exprs were not built");
8414
Alexey Bataev54acd402015-08-04 11:18:19 +00008415 if (!CurContext->isDependentContext()) {
8416 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008417 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008418 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008419 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008420 B.NumIterations, *this, CurScope,
8421 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008422 return StmtError();
8423 }
8424 }
8425
Reid Kleckner87a31802018-03-12 21:43:02 +00008426 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008427 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008428 NestedLoopCount, Clauses, AStmt, B,
8429 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008430}
8431
Alexander Musmane4e893b2014-09-23 09:33:00 +00008432StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8433 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008434 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008435 if (!AStmt)
8436 return StmtError();
8437
Alexey Bataeve3727102018-04-18 15:57:46 +00008438 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008439 // 1.2.2 OpenMP Language Terminology
8440 // Structured block - An executable statement with a single entry at the
8441 // top and a single exit at the bottom.
8442 // The point of exit cannot be a branch out of the structured block.
8443 // longjmp() and throw() must not violate the entry/exit criteria.
8444 CS->getCapturedDecl()->setNothrow();
8445
Alexander Musmanc6388682014-12-15 07:07:06 +00008446 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008447 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8448 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008449 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008450 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008451 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8452 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008453 if (NestedLoopCount == 0)
8454 return StmtError();
8455
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008456 if (!CurContext->isDependentContext()) {
8457 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008458 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008459 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008460 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008461 B.NumIterations, *this, CurScope,
8462 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008463 return StmtError();
8464 }
8465 }
8466
Kelvin Lic5609492016-07-15 04:39:07 +00008467 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008468 return StmtError();
8469
Reid Kleckner87a31802018-03-12 21:43:02 +00008470 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008471 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008472 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008473}
8474
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008475StmtResult
cchen47d60942019-12-05 13:43:48 -05008476Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
8477 Stmt *AStmt, SourceLocation StartLoc,
8478 SourceLocation EndLoc) {
8479 if (!AStmt)
8480 return StmtError();
8481
8482 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8483 auto *CS = cast<CapturedStmt>(AStmt);
8484 // 1.2.2 OpenMP Language Terminology
8485 // Structured block - An executable statement with a single entry at the
8486 // top and a single exit at the bottom.
8487 // The point of exit cannot be a branch out of the structured block.
8488 // longjmp() and throw() must not violate the entry/exit criteria.
8489 CS->getCapturedDecl()->setNothrow();
8490
8491 setFunctionHasBranchProtectedScope();
8492
8493 return OMPParallelMasterDirective::Create(Context, StartLoc, EndLoc, Clauses,
8494 AStmt);
8495}
8496
8497StmtResult
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008498Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8499 Stmt *AStmt, SourceLocation StartLoc,
8500 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008501 if (!AStmt)
8502 return StmtError();
8503
8504 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008505 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008506 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008507 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008508 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008509 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008510 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008511 return StmtError();
8512 // All associated statements must be '#pragma omp section' except for
8513 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008514 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008515 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8516 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008517 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008518 diag::err_omp_parallel_sections_substmt_not_section);
8519 return StmtError();
8520 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008521 cast<OMPSectionDirective>(SectionStmt)
8522 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008523 }
8524 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008525 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008526 diag::err_omp_parallel_sections_not_compound_stmt);
8527 return StmtError();
8528 }
8529
Reid Kleckner87a31802018-03-12 21:43:02 +00008530 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008531
Alexey Bataev25e5b442015-09-15 12:52:43 +00008532 return OMPParallelSectionsDirective::Create(
8533 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008534}
8535
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008536StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8537 Stmt *AStmt, SourceLocation StartLoc,
8538 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008539 if (!AStmt)
8540 return StmtError();
8541
David Majnemer9d168222016-08-05 17:44:54 +00008542 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008543 // 1.2.2 OpenMP Language Terminology
8544 // Structured block - An executable statement with a single entry at the
8545 // top and a single exit at the bottom.
8546 // The point of exit cannot be a branch out of the structured block.
8547 // longjmp() and throw() must not violate the entry/exit criteria.
8548 CS->getCapturedDecl()->setNothrow();
8549
Reid Kleckner87a31802018-03-12 21:43:02 +00008550 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008551
Alexey Bataev25e5b442015-09-15 12:52:43 +00008552 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8553 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008554}
8555
Alexey Bataev68446b72014-07-18 07:47:19 +00008556StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8557 SourceLocation EndLoc) {
8558 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8559}
8560
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008561StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8562 SourceLocation EndLoc) {
8563 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8564}
8565
Alexey Bataev2df347a2014-07-18 10:17:07 +00008566StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8567 SourceLocation EndLoc) {
8568 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8569}
8570
Alexey Bataev169d96a2017-07-18 20:17:46 +00008571StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8572 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008573 SourceLocation StartLoc,
8574 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008575 if (!AStmt)
8576 return StmtError();
8577
8578 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008579
Reid Kleckner87a31802018-03-12 21:43:02 +00008580 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008581
Alexey Bataev169d96a2017-07-18 20:17:46 +00008582 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008583 AStmt,
8584 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008585}
8586
Alexey Bataev6125da92014-07-21 11:26:11 +00008587StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8588 SourceLocation StartLoc,
8589 SourceLocation EndLoc) {
Alexey Bataevea9166b2020-02-06 16:30:23 -05008590 OMPFlushClause *FC = nullptr;
8591 OMPClause *OrderClause = nullptr;
8592 for (OMPClause *C : Clauses) {
8593 if (C->getClauseKind() == OMPC_flush)
8594 FC = cast<OMPFlushClause>(C);
8595 else
8596 OrderClause = C;
8597 }
Alexey Bataev04a830f2020-02-10 14:30:39 -05008598 OpenMPClauseKind MemOrderKind = OMPC_unknown;
8599 SourceLocation MemOrderLoc;
8600 for (const OMPClause *C : Clauses) {
Alexey Bataev95598342020-02-10 15:49:05 -05008601 if (C->getClauseKind() == OMPC_acq_rel ||
8602 C->getClauseKind() == OMPC_acquire ||
8603 C->getClauseKind() == OMPC_release) {
Alexey Bataev04a830f2020-02-10 14:30:39 -05008604 if (MemOrderKind != OMPC_unknown) {
8605 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
8606 << getOpenMPDirectiveName(OMPD_flush) << 1
8607 << SourceRange(C->getBeginLoc(), C->getEndLoc());
8608 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
8609 << getOpenMPClauseName(MemOrderKind);
8610 } else {
8611 MemOrderKind = C->getClauseKind();
8612 MemOrderLoc = C->getBeginLoc();
8613 }
8614 }
8615 }
Alexey Bataevea9166b2020-02-06 16:30:23 -05008616 if (FC && OrderClause) {
8617 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
8618 << getOpenMPClauseName(OrderClause->getClauseKind());
8619 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
8620 << getOpenMPClauseName(OrderClause->getClauseKind());
8621 return StmtError();
8622 }
Alexey Bataev6125da92014-07-21 11:26:11 +00008623 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8624}
8625
Alexey Bataev346265e2015-09-25 10:37:12 +00008626StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8627 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008628 SourceLocation StartLoc,
8629 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008630 const OMPClause *DependFound = nullptr;
8631 const OMPClause *DependSourceClause = nullptr;
8632 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008633 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008634 const OMPThreadsClause *TC = nullptr;
8635 const OMPSIMDClause *SC = nullptr;
8636 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008637 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8638 DependFound = C;
8639 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8640 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008641 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008642 << getOpenMPDirectiveName(OMPD_ordered)
8643 << getOpenMPClauseName(OMPC_depend) << 2;
8644 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008645 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008646 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008647 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008648 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008649 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008650 << 0;
8651 ErrorFound = true;
8652 }
8653 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8654 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008655 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008656 << 1;
8657 ErrorFound = true;
8658 }
8659 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008660 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008661 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008662 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008663 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008664 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008665 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008666 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008667 if (!ErrorFound && !SC &&
8668 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008669 // OpenMP [2.8.1,simd Construct, Restrictions]
8670 // An ordered construct with the simd clause is the only OpenMP construct
8671 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008672 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8673 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008674 ErrorFound = true;
8675 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008676 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008677 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8678 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008679 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008680 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008681 diag::err_omp_ordered_directive_without_param);
8682 ErrorFound = true;
8683 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008684 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008685 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008686 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8687 << (TC != nullptr);
Alexey Bataevcb8e6912020-01-31 16:09:26 -05008688 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
Alexey Bataeveb482352015-12-18 05:05:56 +00008689 ErrorFound = true;
8690 }
8691 }
8692 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008693 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008694
8695 if (AStmt) {
8696 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8697
Reid Kleckner87a31802018-03-12 21:43:02 +00008698 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008699 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008700
8701 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008702}
8703
Alexey Bataev1d160b12015-03-13 12:27:31 +00008704namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008705/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008706/// construct.
8707class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008708 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008709 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008710 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008711 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008712 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008713 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008714 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008715 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008716 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008717 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008718 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008719 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008720 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008721 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008722 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008723 /// expression.
8724 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008725 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008726 /// part.
8727 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008728 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008729 NoError
8730 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008731 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008732 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008733 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008734 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008735 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008736 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008737 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008738 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008739 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008740 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8741 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8742 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008743 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008744 /// important for non-associative operations.
8745 bool IsXLHSInRHSPart;
8746 BinaryOperatorKind Op;
8747 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008748 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008749 /// if it is a prefix unary operation.
8750 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008751
8752public:
8753 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008754 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008755 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008756 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008757 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008758 /// expression. If DiagId and NoteId == 0, then only check is performed
8759 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008760 /// \param DiagId Diagnostic which should be emitted if error is found.
8761 /// \param NoteId Diagnostic note for the main error message.
8762 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008763 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008764 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008765 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008766 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008767 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008768 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008769 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8770 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8771 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008772 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008773 /// false otherwise.
8774 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8775
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008776 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008777 /// if it is a prefix unary operation.
8778 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8779
Alexey Bataev1d160b12015-03-13 12:27:31 +00008780private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008781 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8782 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008783};
8784} // namespace
8785
8786bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8787 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8788 ExprAnalysisErrorCode ErrorFound = NoError;
8789 SourceLocation ErrorLoc, NoteLoc;
8790 SourceRange ErrorRange, NoteRange;
8791 // Allowed constructs are:
8792 // x = x binop expr;
8793 // x = expr binop x;
8794 if (AtomicBinOp->getOpcode() == BO_Assign) {
8795 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008796 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008797 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8798 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8799 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8800 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008801 Op = AtomicInnerBinOp->getOpcode();
8802 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008803 Expr *LHS = AtomicInnerBinOp->getLHS();
8804 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008805 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8806 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8807 /*Canonical=*/true);
8808 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8809 /*Canonical=*/true);
8810 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8811 /*Canonical=*/true);
8812 if (XId == LHSId) {
8813 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008814 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008815 } else if (XId == RHSId) {
8816 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008817 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008818 } else {
8819 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8820 ErrorRange = AtomicInnerBinOp->getSourceRange();
8821 NoteLoc = X->getExprLoc();
8822 NoteRange = X->getSourceRange();
8823 ErrorFound = NotAnUpdateExpression;
8824 }
8825 } else {
8826 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8827 ErrorRange = AtomicInnerBinOp->getSourceRange();
8828 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8829 NoteRange = SourceRange(NoteLoc, NoteLoc);
8830 ErrorFound = NotABinaryOperator;
8831 }
8832 } else {
8833 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8834 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8835 ErrorFound = NotABinaryExpression;
8836 }
8837 } else {
8838 ErrorLoc = AtomicBinOp->getExprLoc();
8839 ErrorRange = AtomicBinOp->getSourceRange();
8840 NoteLoc = AtomicBinOp->getOperatorLoc();
8841 NoteRange = SourceRange(NoteLoc, NoteLoc);
8842 ErrorFound = NotAnAssignmentOp;
8843 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008844 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008845 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8846 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8847 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008848 }
8849 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008850 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008851 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008852}
8853
8854bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8855 unsigned NoteId) {
8856 ExprAnalysisErrorCode ErrorFound = NoError;
8857 SourceLocation ErrorLoc, NoteLoc;
8858 SourceRange ErrorRange, NoteRange;
8859 // Allowed constructs are:
8860 // x++;
8861 // x--;
8862 // ++x;
8863 // --x;
8864 // x binop= expr;
8865 // x = x binop expr;
8866 // x = expr binop x;
8867 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8868 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8869 if (AtomicBody->getType()->isScalarType() ||
8870 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008871 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008872 AtomicBody->IgnoreParenImpCasts())) {
8873 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008874 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008875 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008876 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008877 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008878 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008879 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008880 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8881 AtomicBody->IgnoreParenImpCasts())) {
8882 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008883 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008884 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008885 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008886 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008887 // Check for Unary Operation
8888 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008889 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008890 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8891 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008892 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008893 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8894 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008895 } else {
8896 ErrorFound = NotAnUnaryIncDecExpression;
8897 ErrorLoc = AtomicUnaryOp->getExprLoc();
8898 ErrorRange = AtomicUnaryOp->getSourceRange();
8899 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8900 NoteRange = SourceRange(NoteLoc, NoteLoc);
8901 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008902 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008903 ErrorFound = NotABinaryOrUnaryExpression;
8904 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8905 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8906 }
8907 } else {
8908 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008909 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008910 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8911 }
8912 } else {
8913 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008914 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008915 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8916 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008917 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008918 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8919 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8920 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008921 }
8922 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008923 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008924 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008925 // Build an update expression of form 'OpaqueValueExpr(x) binop
8926 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8927 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8928 auto *OVEX = new (SemaRef.getASTContext())
8929 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8930 auto *OVEExpr = new (SemaRef.getASTContext())
8931 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008932 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008933 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8934 IsXLHSInRHSPart ? OVEExpr : OVEX);
8935 if (Update.isInvalid())
8936 return true;
8937 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8938 Sema::AA_Casting);
8939 if (Update.isInvalid())
8940 return true;
8941 UpdateExpr = Update.get();
8942 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008943 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008944}
8945
Alexey Bataev0162e452014-07-22 10:10:35 +00008946StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8947 Stmt *AStmt,
8948 SourceLocation StartLoc,
8949 SourceLocation EndLoc) {
Alexey Bataev2d4f80f2020-02-11 15:15:21 -05008950 // Register location of the first atomic directive.
8951 DSAStack->addAtomicDirectiveLoc(StartLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008952 if (!AStmt)
8953 return StmtError();
8954
David Majnemer9d168222016-08-05 17:44:54 +00008955 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008956 // 1.2.2 OpenMP Language Terminology
8957 // Structured block - An executable statement with a single entry at the
8958 // top and a single exit at the bottom.
8959 // The point of exit cannot be a branch out of the structured block.
8960 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008961 OpenMPClauseKind AtomicKind = OMPC_unknown;
8962 SourceLocation AtomicKindLoc;
Alexey Bataevea9166b2020-02-06 16:30:23 -05008963 OpenMPClauseKind MemOrderKind = OMPC_unknown;
8964 SourceLocation MemOrderLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008965 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008966 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008967 C->getClauseKind() == OMPC_update ||
8968 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008969 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008970 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008971 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataev04a830f2020-02-10 14:30:39 -05008972 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
Alexey Bataevdea47612014-07-23 07:46:59 +00008973 << getOpenMPClauseName(AtomicKind);
8974 } else {
8975 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008976 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008977 }
8978 }
Alexey Bataevea9166b2020-02-06 16:30:23 -05008979 if (C->getClauseKind() == OMPC_seq_cst ||
Alexey Bataev04a830f2020-02-10 14:30:39 -05008980 C->getClauseKind() == OMPC_acq_rel ||
Alexey Bataev95598342020-02-10 15:49:05 -05008981 C->getClauseKind() == OMPC_acquire ||
Alexey Bataev9a8defc2020-02-11 11:10:43 -05008982 C->getClauseKind() == OMPC_release ||
8983 C->getClauseKind() == OMPC_relaxed) {
Alexey Bataevea9166b2020-02-06 16:30:23 -05008984 if (MemOrderKind != OMPC_unknown) {
Alexey Bataev04a830f2020-02-10 14:30:39 -05008985 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
8986 << getOpenMPDirectiveName(OMPD_atomic) << 0
Alexey Bataevea9166b2020-02-06 16:30:23 -05008987 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataev04a830f2020-02-10 14:30:39 -05008988 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
Alexey Bataevea9166b2020-02-06 16:30:23 -05008989 << getOpenMPClauseName(MemOrderKind);
8990 } else {
8991 MemOrderKind = C->getClauseKind();
8992 MemOrderLoc = C->getBeginLoc();
8993 }
8994 }
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008995 }
Alexey Bataev9a3740c2020-02-11 09:35:52 -05008996 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
8997 // If atomic-clause is read then memory-order-clause must not be acq_rel or
8998 // release.
8999 // If atomic-clause is write then memory-order-clause must not be acq_rel or
9000 // acquire.
9001 // If atomic-clause is update or not present then memory-order-clause must not
9002 // be acq_rel or acquire.
9003 if ((AtomicKind == OMPC_read &&
9004 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
9005 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
9006 AtomicKind == OMPC_unknown) &&
9007 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
9008 SourceLocation Loc = AtomicKindLoc;
9009 if (AtomicKind == OMPC_unknown)
9010 Loc = StartLoc;
9011 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
9012 << getOpenMPClauseName(AtomicKind)
9013 << (AtomicKind == OMPC_unknown ? 1 : 0)
9014 << getOpenMPClauseName(MemOrderKind);
9015 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
9016 << getOpenMPClauseName(MemOrderKind);
9017 }
Alexey Bataev62cec442014-11-18 10:14:22 +00009018
Alexey Bataeve3727102018-04-18 15:57:46 +00009019 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00009020 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
9021 Body = EWC->getSubExpr();
9022
Alexey Bataev62cec442014-11-18 10:14:22 +00009023 Expr *X = nullptr;
9024 Expr *V = nullptr;
9025 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00009026 Expr *UE = nullptr;
9027 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009028 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00009029 // OpenMP [2.12.6, atomic Construct]
9030 // In the next expressions:
9031 // * x and v (as applicable) are both l-value expressions with scalar type.
9032 // * During the execution of an atomic region, multiple syntactic
9033 // occurrences of x must designate the same storage location.
9034 // * Neither of v and expr (as applicable) may access the storage location
9035 // designated by x.
9036 // * Neither of x and expr (as applicable) may access the storage location
9037 // designated by v.
9038 // * expr is an expression with scalar type.
9039 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
9040 // * binop, binop=, ++, and -- are not overloaded operators.
9041 // * The expression x binop expr must be numerically equivalent to x binop
9042 // (expr). This requirement is satisfied if the operators in expr have
9043 // precedence greater than binop, or by using parentheses around expr or
9044 // subexpressions of expr.
9045 // * The expression expr binop x must be numerically equivalent to (expr)
9046 // binop x. This requirement is satisfied if the operators in expr have
9047 // precedence equal to or greater than binop, or by using parentheses around
9048 // expr or subexpressions of expr.
9049 // * For forms that allow multiple occurrences of x, the number of times
9050 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00009051 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009052 enum {
9053 NotAnExpression,
9054 NotAnAssignmentOp,
9055 NotAScalarType,
9056 NotAnLValue,
9057 NoError
9058 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00009059 SourceLocation ErrorLoc, NoteLoc;
9060 SourceRange ErrorRange, NoteRange;
9061 // If clause is read:
9062 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00009063 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9064 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00009065 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9066 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9067 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9068 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
9069 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9070 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
9071 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009072 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00009073 ErrorFound = NotAnLValue;
9074 ErrorLoc = AtomicBinOp->getExprLoc();
9075 ErrorRange = AtomicBinOp->getSourceRange();
9076 NoteLoc = NotLValueExpr->getExprLoc();
9077 NoteRange = NotLValueExpr->getSourceRange();
9078 }
9079 } else if (!X->isInstantiationDependent() ||
9080 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009081 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00009082 (X->isInstantiationDependent() || X->getType()->isScalarType())
9083 ? V
9084 : X;
9085 ErrorFound = NotAScalarType;
9086 ErrorLoc = AtomicBinOp->getExprLoc();
9087 ErrorRange = AtomicBinOp->getSourceRange();
9088 NoteLoc = NotScalarExpr->getExprLoc();
9089 NoteRange = NotScalarExpr->getSourceRange();
9090 }
Alexey Bataev5a195472015-09-04 12:55:50 +00009091 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00009092 ErrorFound = NotAnAssignmentOp;
9093 ErrorLoc = AtomicBody->getExprLoc();
9094 ErrorRange = AtomicBody->getSourceRange();
9095 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9096 : AtomicBody->getExprLoc();
9097 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9098 : AtomicBody->getSourceRange();
9099 }
9100 } else {
9101 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009102 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00009103 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00009104 }
Alexey Bataev62cec442014-11-18 10:14:22 +00009105 if (ErrorFound != NoError) {
9106 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
9107 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00009108 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9109 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00009110 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00009111 }
9112 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00009113 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00009114 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009115 enum {
9116 NotAnExpression,
9117 NotAnAssignmentOp,
9118 NotAScalarType,
9119 NotAnLValue,
9120 NoError
9121 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00009122 SourceLocation ErrorLoc, NoteLoc;
9123 SourceRange ErrorRange, NoteRange;
9124 // If clause is write:
9125 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009126 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9127 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00009128 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9129 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00009130 X = AtomicBinOp->getLHS();
9131 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00009132 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9133 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
9134 if (!X->isLValue()) {
9135 ErrorFound = NotAnLValue;
9136 ErrorLoc = AtomicBinOp->getExprLoc();
9137 ErrorRange = AtomicBinOp->getSourceRange();
9138 NoteLoc = X->getExprLoc();
9139 NoteRange = X->getSourceRange();
9140 }
9141 } else if (!X->isInstantiationDependent() ||
9142 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009143 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00009144 (X->isInstantiationDependent() || X->getType()->isScalarType())
9145 ? E
9146 : X;
9147 ErrorFound = NotAScalarType;
9148 ErrorLoc = AtomicBinOp->getExprLoc();
9149 ErrorRange = AtomicBinOp->getSourceRange();
9150 NoteLoc = NotScalarExpr->getExprLoc();
9151 NoteRange = NotScalarExpr->getSourceRange();
9152 }
Alexey Bataev5a195472015-09-04 12:55:50 +00009153 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00009154 ErrorFound = NotAnAssignmentOp;
9155 ErrorLoc = AtomicBody->getExprLoc();
9156 ErrorRange = AtomicBody->getSourceRange();
9157 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9158 : AtomicBody->getExprLoc();
9159 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9160 : AtomicBody->getSourceRange();
9161 }
9162 } else {
9163 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009164 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00009165 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00009166 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00009167 if (ErrorFound != NoError) {
9168 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
9169 << ErrorRange;
9170 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9171 << NoteRange;
9172 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00009173 }
9174 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00009175 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009176 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00009177 // If clause is update:
9178 // x++;
9179 // x--;
9180 // ++x;
9181 // --x;
9182 // x binop= expr;
9183 // x = x binop expr;
9184 // x = expr binop x;
9185 OpenMPAtomicUpdateChecker Checker(*this);
9186 if (Checker.checkStatement(
9187 Body, (AtomicKind == OMPC_update)
9188 ? diag::err_omp_atomic_update_not_expression_statement
9189 : diag::err_omp_atomic_not_expression_statement,
9190 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00009191 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00009192 if (!CurContext->isDependentContext()) {
9193 E = Checker.getExpr();
9194 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00009195 UE = Checker.getUpdateExpr();
9196 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00009197 }
Alexey Bataev459dec02014-07-24 06:46:57 +00009198 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009199 enum {
9200 NotAnAssignmentOp,
9201 NotACompoundStatement,
9202 NotTwoSubstatements,
9203 NotASpecificExpression,
9204 NoError
9205 } ErrorFound = NoError;
9206 SourceLocation ErrorLoc, NoteLoc;
9207 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009208 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009209 // If clause is a capture:
9210 // v = x++;
9211 // v = x--;
9212 // v = ++x;
9213 // v = --x;
9214 // v = x binop= expr;
9215 // v = x = x binop expr;
9216 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00009217 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00009218 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9219 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9220 V = AtomicBinOp->getLHS();
9221 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9222 OpenMPAtomicUpdateChecker Checker(*this);
9223 if (Checker.checkStatement(
9224 Body, diag::err_omp_atomic_capture_not_expression_statement,
9225 diag::note_omp_atomic_update))
9226 return StmtError();
9227 E = Checker.getExpr();
9228 X = Checker.getX();
9229 UE = Checker.getUpdateExpr();
9230 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9231 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00009232 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009233 ErrorLoc = AtomicBody->getExprLoc();
9234 ErrorRange = AtomicBody->getSourceRange();
9235 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9236 : AtomicBody->getExprLoc();
9237 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9238 : AtomicBody->getSourceRange();
9239 ErrorFound = NotAnAssignmentOp;
9240 }
9241 if (ErrorFound != NoError) {
9242 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9243 << ErrorRange;
9244 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9245 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009246 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009247 if (CurContext->isDependentContext())
9248 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009249 } else {
9250 // If clause is a capture:
9251 // { v = x; x = expr; }
9252 // { v = x; x++; }
9253 // { v = x; x--; }
9254 // { v = x; ++x; }
9255 // { v = x; --x; }
9256 // { v = x; x binop= expr; }
9257 // { v = x; x = x binop expr; }
9258 // { v = x; x = expr binop x; }
9259 // { x++; v = x; }
9260 // { x--; v = x; }
9261 // { ++x; v = x; }
9262 // { --x; v = x; }
9263 // { x binop= expr; v = x; }
9264 // { x = x binop expr; v = x; }
9265 // { x = expr binop x; v = x; }
9266 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9267 // Check that this is { expr1; expr2; }
9268 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009269 Stmt *First = CS->body_front();
9270 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009271 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9272 First = EWC->getSubExpr()->IgnoreParenImpCasts();
9273 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9274 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9275 // Need to find what subexpression is 'v' and what is 'x'.
9276 OpenMPAtomicUpdateChecker Checker(*this);
9277 bool IsUpdateExprFound = !Checker.checkStatement(Second);
9278 BinaryOperator *BinOp = nullptr;
9279 if (IsUpdateExprFound) {
9280 BinOp = dyn_cast<BinaryOperator>(First);
9281 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9282 }
9283 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9284 // { v = x; x++; }
9285 // { v = x; x--; }
9286 // { v = x; ++x; }
9287 // { v = x; --x; }
9288 // { v = x; x binop= expr; }
9289 // { v = x; x = x binop expr; }
9290 // { v = x; x = expr binop x; }
9291 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009292 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009293 llvm::FoldingSetNodeID XId, PossibleXId;
9294 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9295 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9296 IsUpdateExprFound = XId == PossibleXId;
9297 if (IsUpdateExprFound) {
9298 V = BinOp->getLHS();
9299 X = Checker.getX();
9300 E = Checker.getExpr();
9301 UE = Checker.getUpdateExpr();
9302 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009303 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009304 }
9305 }
9306 if (!IsUpdateExprFound) {
9307 IsUpdateExprFound = !Checker.checkStatement(First);
9308 BinOp = nullptr;
9309 if (IsUpdateExprFound) {
9310 BinOp = dyn_cast<BinaryOperator>(Second);
9311 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9312 }
9313 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9314 // { x++; v = x; }
9315 // { x--; v = x; }
9316 // { ++x; v = x; }
9317 // { --x; v = x; }
9318 // { x binop= expr; v = x; }
9319 // { x = x binop expr; v = x; }
9320 // { x = expr binop x; v = x; }
9321 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009322 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009323 llvm::FoldingSetNodeID XId, PossibleXId;
9324 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9325 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9326 IsUpdateExprFound = XId == PossibleXId;
9327 if (IsUpdateExprFound) {
9328 V = BinOp->getLHS();
9329 X = Checker.getX();
9330 E = Checker.getExpr();
9331 UE = Checker.getUpdateExpr();
9332 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009333 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009334 }
9335 }
9336 }
9337 if (!IsUpdateExprFound) {
9338 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009339 auto *FirstExpr = dyn_cast<Expr>(First);
9340 auto *SecondExpr = dyn_cast<Expr>(Second);
9341 if (!FirstExpr || !SecondExpr ||
9342 !(FirstExpr->isInstantiationDependent() ||
9343 SecondExpr->isInstantiationDependent())) {
9344 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9345 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009346 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009347 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009348 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009349 NoteRange = ErrorRange = FirstBinOp
9350 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009351 : SourceRange(ErrorLoc, ErrorLoc);
9352 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009353 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9354 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9355 ErrorFound = NotAnAssignmentOp;
9356 NoteLoc = ErrorLoc = SecondBinOp
9357 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009358 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009359 NoteRange = ErrorRange =
9360 SecondBinOp ? SecondBinOp->getSourceRange()
9361 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009362 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009363 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009364 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009365 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009366 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9367 llvm::FoldingSetNodeID X1Id, X2Id;
9368 PossibleXRHSInFirst->Profile(X1Id, Context,
9369 /*Canonical=*/true);
9370 PossibleXLHSInSecond->Profile(X2Id, Context,
9371 /*Canonical=*/true);
9372 IsUpdateExprFound = X1Id == X2Id;
9373 if (IsUpdateExprFound) {
9374 V = FirstBinOp->getLHS();
9375 X = SecondBinOp->getLHS();
9376 E = SecondBinOp->getRHS();
9377 UE = nullptr;
9378 IsXLHSInRHSPart = false;
9379 IsPostfixUpdate = true;
9380 } else {
9381 ErrorFound = NotASpecificExpression;
9382 ErrorLoc = FirstBinOp->getExprLoc();
9383 ErrorRange = FirstBinOp->getSourceRange();
9384 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9385 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9386 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009387 }
9388 }
9389 }
9390 }
9391 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009392 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009393 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009394 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009395 ErrorFound = NotTwoSubstatements;
9396 }
9397 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009398 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009399 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009400 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009401 ErrorFound = NotACompoundStatement;
9402 }
9403 if (ErrorFound != NoError) {
9404 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9405 << ErrorRange;
9406 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9407 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009408 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009409 if (CurContext->isDependentContext())
9410 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009411 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009412 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009413
Reid Kleckner87a31802018-03-12 21:43:02 +00009414 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009415
Alexey Bataev62cec442014-11-18 10:14:22 +00009416 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009417 X, V, E, UE, IsXLHSInRHSPart,
9418 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009419}
9420
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009421StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9422 Stmt *AStmt,
9423 SourceLocation StartLoc,
9424 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009425 if (!AStmt)
9426 return StmtError();
9427
Alexey Bataeve3727102018-04-18 15:57:46 +00009428 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009429 // 1.2.2 OpenMP Language Terminology
9430 // Structured block - An executable statement with a single entry at the
9431 // top and a single exit at the bottom.
9432 // The point of exit cannot be a branch out of the structured block.
9433 // longjmp() and throw() must not violate the entry/exit criteria.
9434 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009435 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9436 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9437 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9438 // 1.2.2 OpenMP Language Terminology
9439 // Structured block - An executable statement with a single entry at the
9440 // top and a single exit at the bottom.
9441 // The point of exit cannot be a branch out of the structured block.
9442 // longjmp() and throw() must not violate the entry/exit criteria.
9443 CS->getCapturedDecl()->setNothrow();
9444 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009445
Alexey Bataev13314bf2014-10-09 04:18:56 +00009446 // OpenMP [2.16, Nesting of Regions]
9447 // If specified, a teams construct must be contained within a target
9448 // construct. That target construct must contain no statements or directives
9449 // outside of the teams construct.
9450 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009451 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009452 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009453 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009454 auto I = CS->body_begin();
9455 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009456 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009457 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9458 OMPTeamsFound) {
9459
Alexey Bataev13314bf2014-10-09 04:18:56 +00009460 OMPTeamsFound = false;
9461 break;
9462 }
9463 ++I;
9464 }
9465 assert(I != CS->body_end() && "Not found statement");
9466 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009467 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009468 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009469 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009470 }
9471 if (!OMPTeamsFound) {
9472 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9473 Diag(DSAStack->getInnerTeamsRegionLoc(),
9474 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009475 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009476 << isa<OMPExecutableDirective>(S);
9477 return StmtError();
9478 }
9479 }
9480
Reid Kleckner87a31802018-03-12 21:43:02 +00009481 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009482
9483 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9484}
9485
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009486StmtResult
9487Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9488 Stmt *AStmt, SourceLocation StartLoc,
9489 SourceLocation EndLoc) {
9490 if (!AStmt)
9491 return StmtError();
9492
Alexey Bataeve3727102018-04-18 15:57:46 +00009493 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009494 // 1.2.2 OpenMP Language Terminology
9495 // Structured block - An executable statement with a single entry at the
9496 // top and a single exit at the bottom.
9497 // The point of exit cannot be a branch out of the structured block.
9498 // longjmp() and throw() must not violate the entry/exit criteria.
9499 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009500 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9501 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9502 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9503 // 1.2.2 OpenMP Language Terminology
9504 // Structured block - An executable statement with a single entry at the
9505 // top and a single exit at the bottom.
9506 // The point of exit cannot be a branch out of the structured block.
9507 // longjmp() and throw() must not violate the entry/exit criteria.
9508 CS->getCapturedDecl()->setNothrow();
9509 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009510
Reid Kleckner87a31802018-03-12 21:43:02 +00009511 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009512
9513 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9514 AStmt);
9515}
9516
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009517StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9518 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009519 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009520 if (!AStmt)
9521 return StmtError();
9522
Alexey Bataeve3727102018-04-18 15:57:46 +00009523 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009524 // 1.2.2 OpenMP Language Terminology
9525 // Structured block - An executable statement with a single entry at the
9526 // top and a single exit at the bottom.
9527 // The point of exit cannot be a branch out of the structured block.
9528 // longjmp() and throw() must not violate the entry/exit criteria.
9529 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009530 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9531 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9532 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9533 // 1.2.2 OpenMP Language Terminology
9534 // Structured block - An executable statement with a single entry at the
9535 // top and a single exit at the bottom.
9536 // The point of exit cannot be a branch out of the structured block.
9537 // longjmp() and throw() must not violate the entry/exit criteria.
9538 CS->getCapturedDecl()->setNothrow();
9539 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009540
9541 OMPLoopDirective::HelperExprs B;
9542 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9543 // define the nested loops number.
9544 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009545 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009546 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009547 VarsWithImplicitDSA, B);
9548 if (NestedLoopCount == 0)
9549 return StmtError();
9550
9551 assert((CurContext->isDependentContext() || B.builtAll()) &&
9552 "omp target parallel for loop exprs were not built");
9553
9554 if (!CurContext->isDependentContext()) {
9555 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009556 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009557 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009558 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009559 B.NumIterations, *this, CurScope,
9560 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009561 return StmtError();
9562 }
9563 }
9564
Reid Kleckner87a31802018-03-12 21:43:02 +00009565 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009566 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9567 NestedLoopCount, Clauses, AStmt,
9568 B, DSAStack->isCancelRegion());
9569}
9570
Alexey Bataev95b64a92017-05-30 16:00:04 +00009571/// Check for existence of a map clause in the list of clauses.
9572static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9573 const OpenMPClauseKind K) {
9574 return llvm::any_of(
9575 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9576}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009577
Alexey Bataev95b64a92017-05-30 16:00:04 +00009578template <typename... Params>
9579static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9580 const Params... ClauseTypes) {
9581 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009582}
9583
Michael Wong65f367f2015-07-21 13:44:28 +00009584StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9585 Stmt *AStmt,
9586 SourceLocation StartLoc,
9587 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009588 if (!AStmt)
9589 return StmtError();
9590
9591 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9592
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009593 // OpenMP [2.10.1, Restrictions, p. 97]
9594 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009595 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9596 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9597 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009598 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009599 return StmtError();
9600 }
9601
Reid Kleckner87a31802018-03-12 21:43:02 +00009602 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009603
9604 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9605 AStmt);
9606}
9607
Samuel Antaodf67fc42016-01-19 19:15:56 +00009608StmtResult
9609Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9610 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009611 SourceLocation EndLoc, Stmt *AStmt) {
9612 if (!AStmt)
9613 return StmtError();
9614
Alexey Bataeve3727102018-04-18 15:57:46 +00009615 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009616 // 1.2.2 OpenMP Language Terminology
9617 // Structured block - An executable statement with a single entry at the
9618 // top and a single exit at the bottom.
9619 // The point of exit cannot be a branch out of the structured block.
9620 // longjmp() and throw() must not violate the entry/exit criteria.
9621 CS->getCapturedDecl()->setNothrow();
9622 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9623 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9624 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9625 // 1.2.2 OpenMP Language Terminology
9626 // Structured block - An executable statement with a single entry at the
9627 // top and a single exit at the bottom.
9628 // The point of exit cannot be a branch out of the structured block.
9629 // longjmp() and throw() must not violate the entry/exit criteria.
9630 CS->getCapturedDecl()->setNothrow();
9631 }
9632
Samuel Antaodf67fc42016-01-19 19:15:56 +00009633 // OpenMP [2.10.2, Restrictions, p. 99]
9634 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009635 if (!hasClauses(Clauses, OMPC_map)) {
9636 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9637 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009638 return StmtError();
9639 }
9640
Alexey Bataev7828b252017-11-21 17:08:48 +00009641 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9642 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009643}
9644
Samuel Antao72590762016-01-19 20:04:50 +00009645StmtResult
9646Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9647 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009648 SourceLocation EndLoc, Stmt *AStmt) {
9649 if (!AStmt)
9650 return StmtError();
9651
Alexey Bataeve3727102018-04-18 15:57:46 +00009652 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009653 // 1.2.2 OpenMP Language Terminology
9654 // Structured block - An executable statement with a single entry at the
9655 // top and a single exit at the bottom.
9656 // The point of exit cannot be a branch out of the structured block.
9657 // longjmp() and throw() must not violate the entry/exit criteria.
9658 CS->getCapturedDecl()->setNothrow();
9659 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9660 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9661 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9662 // 1.2.2 OpenMP Language Terminology
9663 // Structured block - An executable statement with a single entry at the
9664 // top and a single exit at the bottom.
9665 // The point of exit cannot be a branch out of the structured block.
9666 // longjmp() and throw() must not violate the entry/exit criteria.
9667 CS->getCapturedDecl()->setNothrow();
9668 }
9669
Samuel Antao72590762016-01-19 20:04:50 +00009670 // OpenMP [2.10.3, Restrictions, p. 102]
9671 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009672 if (!hasClauses(Clauses, OMPC_map)) {
9673 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9674 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009675 return StmtError();
9676 }
9677
Alexey Bataev7828b252017-11-21 17:08:48 +00009678 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9679 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009680}
9681
Samuel Antao686c70c2016-05-26 17:30:50 +00009682StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9683 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009684 SourceLocation EndLoc,
9685 Stmt *AStmt) {
9686 if (!AStmt)
9687 return StmtError();
9688
Alexey Bataeve3727102018-04-18 15:57:46 +00009689 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009690 // 1.2.2 OpenMP Language Terminology
9691 // Structured block - An executable statement with a single entry at the
9692 // top and a single exit at the bottom.
9693 // The point of exit cannot be a branch out of the structured block.
9694 // longjmp() and throw() must not violate the entry/exit criteria.
9695 CS->getCapturedDecl()->setNothrow();
9696 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9697 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9698 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9699 // 1.2.2 OpenMP Language Terminology
9700 // Structured block - An executable statement with a single entry at the
9701 // top and a single exit at the bottom.
9702 // The point of exit cannot be a branch out of the structured block.
9703 // longjmp() and throw() must not violate the entry/exit criteria.
9704 CS->getCapturedDecl()->setNothrow();
9705 }
9706
Alexey Bataev95b64a92017-05-30 16:00:04 +00009707 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009708 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9709 return StmtError();
9710 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009711 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9712 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009713}
9714
Alexey Bataev13314bf2014-10-09 04:18:56 +00009715StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9716 Stmt *AStmt, SourceLocation StartLoc,
9717 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009718 if (!AStmt)
9719 return StmtError();
9720
Alexey Bataeve3727102018-04-18 15:57:46 +00009721 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009722 // 1.2.2 OpenMP Language Terminology
9723 // Structured block - An executable statement with a single entry at the
9724 // top and a single exit at the bottom.
9725 // The point of exit cannot be a branch out of the structured block.
9726 // longjmp() and throw() must not violate the entry/exit criteria.
9727 CS->getCapturedDecl()->setNothrow();
9728
Reid Kleckner87a31802018-03-12 21:43:02 +00009729 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009730
Alexey Bataevceabd412017-11-30 18:01:54 +00009731 DSAStack->setParentTeamsRegionLoc(StartLoc);
9732
Alexey Bataev13314bf2014-10-09 04:18:56 +00009733 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9734}
9735
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009736StmtResult
9737Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9738 SourceLocation EndLoc,
9739 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009740 if (DSAStack->isParentNowaitRegion()) {
9741 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9742 return StmtError();
9743 }
9744 if (DSAStack->isParentOrderedRegion()) {
9745 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9746 return StmtError();
9747 }
9748 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9749 CancelRegion);
9750}
9751
Alexey Bataev87933c72015-09-18 08:07:34 +00009752StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9753 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009754 SourceLocation EndLoc,
9755 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009756 if (DSAStack->isParentNowaitRegion()) {
9757 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9758 return StmtError();
9759 }
9760 if (DSAStack->isParentOrderedRegion()) {
9761 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9762 return StmtError();
9763 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009764 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009765 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9766 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009767}
9768
Alexey Bataev382967a2015-12-08 12:06:20 +00009769static bool checkGrainsizeNumTasksClauses(Sema &S,
9770 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009771 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009772 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009773 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009774 if (C->getClauseKind() == OMPC_grainsize ||
9775 C->getClauseKind() == OMPC_num_tasks) {
9776 if (!PrevClause)
9777 PrevClause = C;
9778 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009779 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009780 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9781 << getOpenMPClauseName(C->getClauseKind())
9782 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009783 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009784 diag::note_omp_previous_grainsize_num_tasks)
9785 << getOpenMPClauseName(PrevClause->getClauseKind());
9786 ErrorFound = true;
9787 }
9788 }
9789 }
9790 return ErrorFound;
9791}
9792
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009793static bool checkReductionClauseWithNogroup(Sema &S,
9794 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009795 const OMPClause *ReductionClause = nullptr;
9796 const OMPClause *NogroupClause = nullptr;
9797 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009798 if (C->getClauseKind() == OMPC_reduction) {
9799 ReductionClause = C;
9800 if (NogroupClause)
9801 break;
9802 continue;
9803 }
9804 if (C->getClauseKind() == OMPC_nogroup) {
9805 NogroupClause = C;
9806 if (ReductionClause)
9807 break;
9808 continue;
9809 }
9810 }
9811 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009812 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9813 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009814 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009815 return true;
9816 }
9817 return false;
9818}
9819
Alexey Bataev49f6e782015-12-01 04:18:41 +00009820StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9821 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009822 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009823 if (!AStmt)
9824 return StmtError();
9825
9826 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9827 OMPLoopDirective::HelperExprs B;
9828 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9829 // define the nested loops number.
9830 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009831 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009832 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009833 VarsWithImplicitDSA, B);
9834 if (NestedLoopCount == 0)
9835 return StmtError();
9836
9837 assert((CurContext->isDependentContext() || B.builtAll()) &&
9838 "omp for loop exprs were not built");
9839
Alexey Bataev382967a2015-12-08 12:06:20 +00009840 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9841 // The grainsize clause and num_tasks clause are mutually exclusive and may
9842 // not appear on the same taskloop directive.
9843 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9844 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009845 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9846 // If a reduction clause is present on the taskloop directive, the nogroup
9847 // clause must not be specified.
9848 if (checkReductionClauseWithNogroup(*this, Clauses))
9849 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009850
Reid Kleckner87a31802018-03-12 21:43:02 +00009851 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009852 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9853 NestedLoopCount, Clauses, AStmt, B);
9854}
9855
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009856StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9857 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009858 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009859 if (!AStmt)
9860 return StmtError();
9861
9862 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9863 OMPLoopDirective::HelperExprs B;
9864 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9865 // define the nested loops number.
9866 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009867 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009868 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9869 VarsWithImplicitDSA, B);
9870 if (NestedLoopCount == 0)
9871 return StmtError();
9872
9873 assert((CurContext->isDependentContext() || B.builtAll()) &&
9874 "omp for loop exprs were not built");
9875
Alexey Bataev5a3af132016-03-29 08:58:54 +00009876 if (!CurContext->isDependentContext()) {
9877 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009878 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009879 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009880 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009881 B.NumIterations, *this, CurScope,
9882 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009883 return StmtError();
9884 }
9885 }
9886
Alexey Bataev382967a2015-12-08 12:06:20 +00009887 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9888 // The grainsize clause and num_tasks clause are mutually exclusive and may
9889 // not appear on the same taskloop directive.
9890 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9891 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009892 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9893 // If a reduction clause is present on the taskloop directive, the nogroup
9894 // clause must not be specified.
9895 if (checkReductionClauseWithNogroup(*this, Clauses))
9896 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009897 if (checkSimdlenSafelenSpecified(*this, Clauses))
9898 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009899
Reid Kleckner87a31802018-03-12 21:43:02 +00009900 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009901 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9902 NestedLoopCount, Clauses, AStmt, B);
9903}
9904
Alexey Bataev60e51c42019-10-10 20:13:02 +00009905StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9906 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9907 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9908 if (!AStmt)
9909 return StmtError();
9910
9911 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9912 OMPLoopDirective::HelperExprs B;
9913 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9914 // define the nested loops number.
9915 unsigned NestedLoopCount =
9916 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9917 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9918 VarsWithImplicitDSA, B);
9919 if (NestedLoopCount == 0)
9920 return StmtError();
9921
9922 assert((CurContext->isDependentContext() || B.builtAll()) &&
9923 "omp for loop exprs were not built");
9924
9925 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9926 // The grainsize clause and num_tasks clause are mutually exclusive and may
9927 // not appear on the same taskloop directive.
9928 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9929 return StmtError();
9930 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9931 // If a reduction clause is present on the taskloop directive, the nogroup
9932 // clause must not be specified.
9933 if (checkReductionClauseWithNogroup(*this, Clauses))
9934 return StmtError();
9935
9936 setFunctionHasBranchProtectedScope();
9937 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9938 NestedLoopCount, Clauses, AStmt, B);
9939}
9940
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009941StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9942 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9943 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9944 if (!AStmt)
9945 return StmtError();
9946
9947 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9948 OMPLoopDirective::HelperExprs B;
9949 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9950 // define the nested loops number.
9951 unsigned NestedLoopCount =
9952 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9953 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9954 VarsWithImplicitDSA, B);
9955 if (NestedLoopCount == 0)
9956 return StmtError();
9957
9958 assert((CurContext->isDependentContext() || B.builtAll()) &&
9959 "omp for loop exprs were not built");
9960
9961 if (!CurContext->isDependentContext()) {
9962 // Finalize the clauses that need pre-built expressions for CodeGen.
9963 for (OMPClause *C : Clauses) {
9964 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9965 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9966 B.NumIterations, *this, CurScope,
9967 DSAStack))
9968 return StmtError();
9969 }
9970 }
9971
9972 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9973 // The grainsize clause and num_tasks clause are mutually exclusive and may
9974 // not appear on the same taskloop directive.
9975 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9976 return StmtError();
9977 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9978 // If a reduction clause is present on the taskloop directive, the nogroup
9979 // clause must not be specified.
9980 if (checkReductionClauseWithNogroup(*this, Clauses))
9981 return StmtError();
9982 if (checkSimdlenSafelenSpecified(*this, Clauses))
9983 return StmtError();
9984
9985 setFunctionHasBranchProtectedScope();
9986 return OMPMasterTaskLoopSimdDirective::Create(
9987 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9988}
9989
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009990StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9991 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9992 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9993 if (!AStmt)
9994 return StmtError();
9995
9996 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9997 auto *CS = cast<CapturedStmt>(AStmt);
9998 // 1.2.2 OpenMP Language Terminology
9999 // Structured block - An executable statement with a single entry at the
10000 // top and a single exit at the bottom.
10001 // The point of exit cannot be a branch out of the structured block.
10002 // longjmp() and throw() must not violate the entry/exit criteria.
10003 CS->getCapturedDecl()->setNothrow();
10004 for (int ThisCaptureLevel =
10005 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
10006 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10007 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10008 // 1.2.2 OpenMP Language Terminology
10009 // Structured block - An executable statement with a single entry at the
10010 // top and a single exit at the bottom.
10011 // The point of exit cannot be a branch out of the structured block.
10012 // longjmp() and throw() must not violate the entry/exit criteria.
10013 CS->getCapturedDecl()->setNothrow();
10014 }
10015
10016 OMPLoopDirective::HelperExprs B;
10017 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10018 // define the nested loops number.
10019 unsigned NestedLoopCount = checkOpenMPLoop(
10020 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
10021 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10022 VarsWithImplicitDSA, B);
10023 if (NestedLoopCount == 0)
10024 return StmtError();
10025
10026 assert((CurContext->isDependentContext() || B.builtAll()) &&
10027 "omp for loop exprs were not built");
10028
10029 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10030 // The grainsize clause and num_tasks clause are mutually exclusive and may
10031 // not appear on the same taskloop directive.
10032 if (checkGrainsizeNumTasksClauses(*this, Clauses))
10033 return StmtError();
10034 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10035 // If a reduction clause is present on the taskloop directive, the nogroup
10036 // clause must not be specified.
10037 if (checkReductionClauseWithNogroup(*this, Clauses))
10038 return StmtError();
10039
10040 setFunctionHasBranchProtectedScope();
10041 return OMPParallelMasterTaskLoopDirective::Create(
10042 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10043}
10044
Alexey Bataev14a388f2019-10-25 10:27:13 -040010045StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
10046 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10047 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10048 if (!AStmt)
10049 return StmtError();
10050
10051 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10052 auto *CS = cast<CapturedStmt>(AStmt);
10053 // 1.2.2 OpenMP Language Terminology
10054 // Structured block - An executable statement with a single entry at the
10055 // top and a single exit at the bottom.
10056 // The point of exit cannot be a branch out of the structured block.
10057 // longjmp() and throw() must not violate the entry/exit criteria.
10058 CS->getCapturedDecl()->setNothrow();
10059 for (int ThisCaptureLevel =
10060 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
10061 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10062 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10063 // 1.2.2 OpenMP Language Terminology
10064 // Structured block - An executable statement with a single entry at the
10065 // top and a single exit at the bottom.
10066 // The point of exit cannot be a branch out of the structured block.
10067 // longjmp() and throw() must not violate the entry/exit criteria.
10068 CS->getCapturedDecl()->setNothrow();
10069 }
10070
10071 OMPLoopDirective::HelperExprs B;
10072 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10073 // define the nested loops number.
10074 unsigned NestedLoopCount = checkOpenMPLoop(
10075 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
10076 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
10077 VarsWithImplicitDSA, B);
10078 if (NestedLoopCount == 0)
10079 return StmtError();
10080
10081 assert((CurContext->isDependentContext() || B.builtAll()) &&
10082 "omp for loop exprs were not built");
10083
10084 if (!CurContext->isDependentContext()) {
10085 // Finalize the clauses that need pre-built expressions for CodeGen.
10086 for (OMPClause *C : Clauses) {
10087 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10088 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10089 B.NumIterations, *this, CurScope,
10090 DSAStack))
10091 return StmtError();
10092 }
10093 }
10094
10095 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10096 // The grainsize clause and num_tasks clause are mutually exclusive and may
10097 // not appear on the same taskloop directive.
10098 if (checkGrainsizeNumTasksClauses(*this, Clauses))
10099 return StmtError();
10100 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10101 // If a reduction clause is present on the taskloop directive, the nogroup
10102 // clause must not be specified.
10103 if (checkReductionClauseWithNogroup(*this, Clauses))
10104 return StmtError();
10105 if (checkSimdlenSafelenSpecified(*this, Clauses))
10106 return StmtError();
10107
10108 setFunctionHasBranchProtectedScope();
10109 return OMPParallelMasterTaskLoopSimdDirective::Create(
10110 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10111}
10112
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010113StmtResult Sema::ActOnOpenMPDistributeDirective(
10114 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010115 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010116 if (!AStmt)
10117 return StmtError();
10118
10119 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10120 OMPLoopDirective::HelperExprs B;
10121 // In presence of clause 'collapse' with number of loops, it will
10122 // define the nested loops number.
10123 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010124 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010125 nullptr /*ordered not a clause on distribute*/, AStmt,
10126 *this, *DSAStack, VarsWithImplicitDSA, B);
10127 if (NestedLoopCount == 0)
10128 return StmtError();
10129
10130 assert((CurContext->isDependentContext() || B.builtAll()) &&
10131 "omp for loop exprs were not built");
10132
Reid Kleckner87a31802018-03-12 21:43:02 +000010133 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010134 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
10135 NestedLoopCount, Clauses, AStmt, B);
10136}
10137
Carlo Bertolli9925f152016-06-27 14:55:37 +000010138StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
10139 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010140 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +000010141 if (!AStmt)
10142 return StmtError();
10143
Alexey Bataeve3727102018-04-18 15:57:46 +000010144 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +000010145 // 1.2.2 OpenMP Language Terminology
10146 // Structured block - An executable statement with a single entry at the
10147 // top and a single exit at the bottom.
10148 // The point of exit cannot be a branch out of the structured block.
10149 // longjmp() and throw() must not violate the entry/exit criteria.
10150 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +000010151 for (int ThisCaptureLevel =
10152 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
10153 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10154 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10155 // 1.2.2 OpenMP Language Terminology
10156 // Structured block - An executable statement with a single entry at the
10157 // top and a single exit at the bottom.
10158 // The point of exit cannot be a branch out of the structured block.
10159 // longjmp() and throw() must not violate the entry/exit criteria.
10160 CS->getCapturedDecl()->setNothrow();
10161 }
Carlo Bertolli9925f152016-06-27 14:55:37 +000010162
10163 OMPLoopDirective::HelperExprs B;
10164 // In presence of clause 'collapse' with number of loops, it will
10165 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010166 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +000010167 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +000010168 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +000010169 VarsWithImplicitDSA, B);
10170 if (NestedLoopCount == 0)
10171 return StmtError();
10172
10173 assert((CurContext->isDependentContext() || B.builtAll()) &&
10174 "omp for loop exprs were not built");
10175
Reid Kleckner87a31802018-03-12 21:43:02 +000010176 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +000010177 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010178 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10179 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +000010180}
10181
Kelvin Li4a39add2016-07-05 05:00:15 +000010182StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
10183 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010184 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +000010185 if (!AStmt)
10186 return StmtError();
10187
Alexey Bataeve3727102018-04-18 15:57:46 +000010188 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +000010189 // 1.2.2 OpenMP Language Terminology
10190 // Structured block - An executable statement with a single entry at the
10191 // top and a single exit at the bottom.
10192 // The point of exit cannot be a branch out of the structured block.
10193 // longjmp() and throw() must not violate the entry/exit criteria.
10194 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +000010195 for (int ThisCaptureLevel =
10196 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
10197 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10198 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10199 // 1.2.2 OpenMP Language Terminology
10200 // Structured block - An executable statement with a single entry at the
10201 // top and a single exit at the bottom.
10202 // The point of exit cannot be a branch out of the structured block.
10203 // longjmp() and throw() must not violate the entry/exit criteria.
10204 CS->getCapturedDecl()->setNothrow();
10205 }
Kelvin Li4a39add2016-07-05 05:00:15 +000010206
10207 OMPLoopDirective::HelperExprs B;
10208 // In presence of clause 'collapse' with number of loops, it will
10209 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010210 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +000010211 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +000010212 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +000010213 VarsWithImplicitDSA, B);
10214 if (NestedLoopCount == 0)
10215 return StmtError();
10216
10217 assert((CurContext->isDependentContext() || B.builtAll()) &&
10218 "omp for loop exprs were not built");
10219
Alexey Bataev438388c2017-11-22 18:34:02 +000010220 if (!CurContext->isDependentContext()) {
10221 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010222 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010223 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10224 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10225 B.NumIterations, *this, CurScope,
10226 DSAStack))
10227 return StmtError();
10228 }
10229 }
10230
Kelvin Lic5609492016-07-15 04:39:07 +000010231 if (checkSimdlenSafelenSpecified(*this, Clauses))
10232 return StmtError();
10233
Reid Kleckner87a31802018-03-12 21:43:02 +000010234 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +000010235 return OMPDistributeParallelForSimdDirective::Create(
10236 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10237}
10238
Kelvin Li787f3fc2016-07-06 04:45:38 +000010239StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10240 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010241 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +000010242 if (!AStmt)
10243 return StmtError();
10244
Alexey Bataeve3727102018-04-18 15:57:46 +000010245 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010246 // 1.2.2 OpenMP Language Terminology
10247 // Structured block - An executable statement with a single entry at the
10248 // top and a single exit at the bottom.
10249 // The point of exit cannot be a branch out of the structured block.
10250 // longjmp() and throw() must not violate the entry/exit criteria.
10251 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +000010252 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10253 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10254 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10255 // 1.2.2 OpenMP Language Terminology
10256 // Structured block - An executable statement with a single entry at the
10257 // top and a single exit at the bottom.
10258 // The point of exit cannot be a branch out of the structured block.
10259 // longjmp() and throw() must not violate the entry/exit criteria.
10260 CS->getCapturedDecl()->setNothrow();
10261 }
Kelvin Li787f3fc2016-07-06 04:45:38 +000010262
10263 OMPLoopDirective::HelperExprs B;
10264 // In presence of clause 'collapse' with number of loops, it will
10265 // define the nested loops number.
10266 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010267 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +000010268 nullptr /*ordered not a clause on distribute*/, CS, *this,
10269 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010270 if (NestedLoopCount == 0)
10271 return StmtError();
10272
10273 assert((CurContext->isDependentContext() || B.builtAll()) &&
10274 "omp for loop exprs were not built");
10275
Alexey Bataev438388c2017-11-22 18:34:02 +000010276 if (!CurContext->isDependentContext()) {
10277 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010278 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010279 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10280 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10281 B.NumIterations, *this, CurScope,
10282 DSAStack))
10283 return StmtError();
10284 }
10285 }
10286
Kelvin Lic5609492016-07-15 04:39:07 +000010287 if (checkSimdlenSafelenSpecified(*this, Clauses))
10288 return StmtError();
10289
Reid Kleckner87a31802018-03-12 21:43:02 +000010290 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +000010291 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
10292 NestedLoopCount, Clauses, AStmt, B);
10293}
10294
Kelvin Lia579b912016-07-14 02:54:56 +000010295StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
10296 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010297 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +000010298 if (!AStmt)
10299 return StmtError();
10300
Alexey Bataeve3727102018-04-18 15:57:46 +000010301 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +000010302 // 1.2.2 OpenMP Language Terminology
10303 // Structured block - An executable statement with a single entry at the
10304 // top and a single exit at the bottom.
10305 // The point of exit cannot be a branch out of the structured block.
10306 // longjmp() and throw() must not violate the entry/exit criteria.
10307 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010308 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10309 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10310 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10311 // 1.2.2 OpenMP Language Terminology
10312 // Structured block - An executable statement with a single entry at the
10313 // top and a single exit at the bottom.
10314 // The point of exit cannot be a branch out of the structured block.
10315 // longjmp() and throw() must not violate the entry/exit criteria.
10316 CS->getCapturedDecl()->setNothrow();
10317 }
Kelvin Lia579b912016-07-14 02:54:56 +000010318
10319 OMPLoopDirective::HelperExprs B;
10320 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10321 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010322 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010323 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010324 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010325 VarsWithImplicitDSA, B);
10326 if (NestedLoopCount == 0)
10327 return StmtError();
10328
10329 assert((CurContext->isDependentContext() || B.builtAll()) &&
10330 "omp target parallel for simd loop exprs were not built");
10331
10332 if (!CurContext->isDependentContext()) {
10333 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010334 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010335 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010336 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10337 B.NumIterations, *this, CurScope,
10338 DSAStack))
10339 return StmtError();
10340 }
10341 }
Kelvin Lic5609492016-07-15 04:39:07 +000010342 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010343 return StmtError();
10344
Reid Kleckner87a31802018-03-12 21:43:02 +000010345 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010346 return OMPTargetParallelForSimdDirective::Create(
10347 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10348}
10349
Kelvin Li986330c2016-07-20 22:57:10 +000010350StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10351 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010352 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010353 if (!AStmt)
10354 return StmtError();
10355
Alexey Bataeve3727102018-04-18 15:57:46 +000010356 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010357 // 1.2.2 OpenMP Language Terminology
10358 // Structured block - An executable statement with a single entry at the
10359 // top and a single exit at the bottom.
10360 // The point of exit cannot be a branch out of the structured block.
10361 // longjmp() and throw() must not violate the entry/exit criteria.
10362 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010363 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10364 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10365 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10366 // 1.2.2 OpenMP Language Terminology
10367 // Structured block - An executable statement with a single entry at the
10368 // top and a single exit at the bottom.
10369 // The point of exit cannot be a branch out of the structured block.
10370 // longjmp() and throw() must not violate the entry/exit criteria.
10371 CS->getCapturedDecl()->setNothrow();
10372 }
10373
Kelvin Li986330c2016-07-20 22:57:10 +000010374 OMPLoopDirective::HelperExprs B;
10375 // In presence of clause 'collapse' with number of loops, it will define the
10376 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010377 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010378 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010379 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010380 VarsWithImplicitDSA, B);
10381 if (NestedLoopCount == 0)
10382 return StmtError();
10383
10384 assert((CurContext->isDependentContext() || B.builtAll()) &&
10385 "omp target simd loop exprs were not built");
10386
10387 if (!CurContext->isDependentContext()) {
10388 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010389 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010390 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010391 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10392 B.NumIterations, *this, CurScope,
10393 DSAStack))
10394 return StmtError();
10395 }
10396 }
10397
10398 if (checkSimdlenSafelenSpecified(*this, Clauses))
10399 return StmtError();
10400
Reid Kleckner87a31802018-03-12 21:43:02 +000010401 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010402 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10403 NestedLoopCount, Clauses, AStmt, B);
10404}
10405
Kelvin Li02532872016-08-05 14:37:37 +000010406StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10407 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010408 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010409 if (!AStmt)
10410 return StmtError();
10411
Alexey Bataeve3727102018-04-18 15:57:46 +000010412 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +000010413 // 1.2.2 OpenMP Language Terminology
10414 // Structured block - An executable statement with a single entry at the
10415 // top and a single exit at the bottom.
10416 // The point of exit cannot be a branch out of the structured block.
10417 // longjmp() and throw() must not violate the entry/exit criteria.
10418 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010419 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10420 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10421 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10422 // 1.2.2 OpenMP Language Terminology
10423 // Structured block - An executable statement with a single entry at the
10424 // top and a single exit at the bottom.
10425 // The point of exit cannot be a branch out of the structured block.
10426 // longjmp() and throw() must not violate the entry/exit criteria.
10427 CS->getCapturedDecl()->setNothrow();
10428 }
Kelvin Li02532872016-08-05 14:37:37 +000010429
10430 OMPLoopDirective::HelperExprs B;
10431 // In presence of clause 'collapse' with number of loops, it will
10432 // define the nested loops number.
10433 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010434 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010435 nullptr /*ordered not a clause on distribute*/, CS, *this,
10436 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010437 if (NestedLoopCount == 0)
10438 return StmtError();
10439
10440 assert((CurContext->isDependentContext() || B.builtAll()) &&
10441 "omp teams distribute loop exprs were not built");
10442
Reid Kleckner87a31802018-03-12 21:43:02 +000010443 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010444
10445 DSAStack->setParentTeamsRegionLoc(StartLoc);
10446
David Majnemer9d168222016-08-05 17:44:54 +000010447 return OMPTeamsDistributeDirective::Create(
10448 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010449}
10450
Kelvin Li4e325f72016-10-25 12:50:55 +000010451StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10452 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010453 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010454 if (!AStmt)
10455 return StmtError();
10456
Alexey Bataeve3727102018-04-18 15:57:46 +000010457 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010458 // 1.2.2 OpenMP Language Terminology
10459 // Structured block - An executable statement with a single entry at the
10460 // top and a single exit at the bottom.
10461 // The point of exit cannot be a branch out of the structured block.
10462 // longjmp() and throw() must not violate the entry/exit criteria.
10463 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010464 for (int ThisCaptureLevel =
10465 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10466 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10467 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10468 // 1.2.2 OpenMP Language Terminology
10469 // Structured block - An executable statement with a single entry at the
10470 // top and a single exit at the bottom.
10471 // The point of exit cannot be a branch out of the structured block.
10472 // longjmp() and throw() must not violate the entry/exit criteria.
10473 CS->getCapturedDecl()->setNothrow();
10474 }
10475
Kelvin Li4e325f72016-10-25 12:50:55 +000010476
10477 OMPLoopDirective::HelperExprs B;
10478 // In presence of clause 'collapse' with number of loops, it will
10479 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010480 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010481 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010482 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010483 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010484
10485 if (NestedLoopCount == 0)
10486 return StmtError();
10487
10488 assert((CurContext->isDependentContext() || B.builtAll()) &&
10489 "omp teams distribute simd loop exprs were not built");
10490
10491 if (!CurContext->isDependentContext()) {
10492 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010493 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010494 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10495 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10496 B.NumIterations, *this, CurScope,
10497 DSAStack))
10498 return StmtError();
10499 }
10500 }
10501
10502 if (checkSimdlenSafelenSpecified(*this, Clauses))
10503 return StmtError();
10504
Reid Kleckner87a31802018-03-12 21:43:02 +000010505 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010506
10507 DSAStack->setParentTeamsRegionLoc(StartLoc);
10508
Kelvin Li4e325f72016-10-25 12:50:55 +000010509 return OMPTeamsDistributeSimdDirective::Create(
10510 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10511}
10512
Kelvin Li579e41c2016-11-30 23:51:03 +000010513StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10514 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010515 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010516 if (!AStmt)
10517 return StmtError();
10518
Alexey Bataeve3727102018-04-18 15:57:46 +000010519 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010520 // 1.2.2 OpenMP Language Terminology
10521 // Structured block - An executable statement with a single entry at the
10522 // top and a single exit at the bottom.
10523 // The point of exit cannot be a branch out of the structured block.
10524 // longjmp() and throw() must not violate the entry/exit criteria.
10525 CS->getCapturedDecl()->setNothrow();
10526
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010527 for (int ThisCaptureLevel =
10528 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10529 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10530 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10531 // 1.2.2 OpenMP Language Terminology
10532 // Structured block - An executable statement with a single entry at the
10533 // top and a single exit at the bottom.
10534 // The point of exit cannot be a branch out of the structured block.
10535 // longjmp() and throw() must not violate the entry/exit criteria.
10536 CS->getCapturedDecl()->setNothrow();
10537 }
10538
Kelvin Li579e41c2016-11-30 23:51:03 +000010539 OMPLoopDirective::HelperExprs B;
10540 // In presence of clause 'collapse' with number of loops, it will
10541 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010542 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010543 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010544 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010545 VarsWithImplicitDSA, B);
10546
10547 if (NestedLoopCount == 0)
10548 return StmtError();
10549
10550 assert((CurContext->isDependentContext() || B.builtAll()) &&
10551 "omp for loop exprs were not built");
10552
10553 if (!CurContext->isDependentContext()) {
10554 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010555 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010556 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10557 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10558 B.NumIterations, *this, CurScope,
10559 DSAStack))
10560 return StmtError();
10561 }
10562 }
10563
10564 if (checkSimdlenSafelenSpecified(*this, Clauses))
10565 return StmtError();
10566
Reid Kleckner87a31802018-03-12 21:43:02 +000010567 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010568
10569 DSAStack->setParentTeamsRegionLoc(StartLoc);
10570
Kelvin Li579e41c2016-11-30 23:51:03 +000010571 return OMPTeamsDistributeParallelForSimdDirective::Create(
10572 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10573}
10574
Kelvin Li7ade93f2016-12-09 03:24:30 +000010575StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10576 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010577 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010578 if (!AStmt)
10579 return StmtError();
10580
Alexey Bataeve3727102018-04-18 15:57:46 +000010581 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010582 // 1.2.2 OpenMP Language Terminology
10583 // Structured block - An executable statement with a single entry at the
10584 // top and a single exit at the bottom.
10585 // The point of exit cannot be a branch out of the structured block.
10586 // longjmp() and throw() must not violate the entry/exit criteria.
10587 CS->getCapturedDecl()->setNothrow();
10588
Carlo Bertolli62fae152017-11-20 20:46:39 +000010589 for (int ThisCaptureLevel =
10590 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10591 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10592 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10593 // 1.2.2 OpenMP Language Terminology
10594 // Structured block - An executable statement with a single entry at the
10595 // top and a single exit at the bottom.
10596 // The point of exit cannot be a branch out of the structured block.
10597 // longjmp() and throw() must not violate the entry/exit criteria.
10598 CS->getCapturedDecl()->setNothrow();
10599 }
10600
Kelvin Li7ade93f2016-12-09 03:24:30 +000010601 OMPLoopDirective::HelperExprs B;
10602 // In presence of clause 'collapse' with number of loops, it will
10603 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010604 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010605 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010606 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010607 VarsWithImplicitDSA, B);
10608
10609 if (NestedLoopCount == 0)
10610 return StmtError();
10611
10612 assert((CurContext->isDependentContext() || B.builtAll()) &&
10613 "omp for loop exprs were not built");
10614
Reid Kleckner87a31802018-03-12 21:43:02 +000010615 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010616
10617 DSAStack->setParentTeamsRegionLoc(StartLoc);
10618
Kelvin Li7ade93f2016-12-09 03:24:30 +000010619 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010620 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10621 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010622}
10623
Kelvin Libf594a52016-12-17 05:48:59 +000010624StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10625 Stmt *AStmt,
10626 SourceLocation StartLoc,
10627 SourceLocation EndLoc) {
10628 if (!AStmt)
10629 return StmtError();
10630
Alexey Bataeve3727102018-04-18 15:57:46 +000010631 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010632 // 1.2.2 OpenMP Language Terminology
10633 // Structured block - An executable statement with a single entry at the
10634 // top and a single exit at the bottom.
10635 // The point of exit cannot be a branch out of the structured block.
10636 // longjmp() and throw() must not violate the entry/exit criteria.
10637 CS->getCapturedDecl()->setNothrow();
10638
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010639 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10640 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10641 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10642 // 1.2.2 OpenMP Language Terminology
10643 // Structured block - An executable statement with a single entry at the
10644 // top and a single exit at the bottom.
10645 // The point of exit cannot be a branch out of the structured block.
10646 // longjmp() and throw() must not violate the entry/exit criteria.
10647 CS->getCapturedDecl()->setNothrow();
10648 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010649 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010650
10651 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10652 AStmt);
10653}
10654
Kelvin Li83c451e2016-12-25 04:52:54 +000010655StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10656 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010657 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010658 if (!AStmt)
10659 return StmtError();
10660
Alexey Bataeve3727102018-04-18 15:57:46 +000010661 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010662 // 1.2.2 OpenMP Language Terminology
10663 // Structured block - An executable statement with a single entry at the
10664 // top and a single exit at the bottom.
10665 // The point of exit cannot be a branch out of the structured block.
10666 // longjmp() and throw() must not violate the entry/exit criteria.
10667 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010668 for (int ThisCaptureLevel =
10669 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10670 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10671 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10672 // 1.2.2 OpenMP Language Terminology
10673 // Structured block - An executable statement with a single entry at the
10674 // top and a single exit at the bottom.
10675 // The point of exit cannot be a branch out of the structured block.
10676 // longjmp() and throw() must not violate the entry/exit criteria.
10677 CS->getCapturedDecl()->setNothrow();
10678 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010679
10680 OMPLoopDirective::HelperExprs B;
10681 // In presence of clause 'collapse' with number of loops, it will
10682 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010683 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010684 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10685 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010686 VarsWithImplicitDSA, B);
10687 if (NestedLoopCount == 0)
10688 return StmtError();
10689
10690 assert((CurContext->isDependentContext() || B.builtAll()) &&
10691 "omp target teams distribute loop exprs were not built");
10692
Reid Kleckner87a31802018-03-12 21:43:02 +000010693 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010694 return OMPTargetTeamsDistributeDirective::Create(
10695 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10696}
10697
Kelvin Li80e8f562016-12-29 22:16:30 +000010698StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10699 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010700 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010701 if (!AStmt)
10702 return StmtError();
10703
Alexey Bataeve3727102018-04-18 15:57:46 +000010704 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010705 // 1.2.2 OpenMP Language Terminology
10706 // Structured block - An executable statement with a single entry at the
10707 // top and a single exit at the bottom.
10708 // The point of exit cannot be a branch out of the structured block.
10709 // longjmp() and throw() must not violate the entry/exit criteria.
10710 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010711 for (int ThisCaptureLevel =
10712 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10713 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10714 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10715 // 1.2.2 OpenMP Language Terminology
10716 // Structured block - An executable statement with a single entry at the
10717 // top and a single exit at the bottom.
10718 // The point of exit cannot be a branch out of the structured block.
10719 // longjmp() and throw() must not violate the entry/exit criteria.
10720 CS->getCapturedDecl()->setNothrow();
10721 }
10722
Kelvin Li80e8f562016-12-29 22:16:30 +000010723 OMPLoopDirective::HelperExprs B;
10724 // In presence of clause 'collapse' with number of loops, it will
10725 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010726 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010727 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10728 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010729 VarsWithImplicitDSA, B);
10730 if (NestedLoopCount == 0)
10731 return StmtError();
10732
10733 assert((CurContext->isDependentContext() || B.builtAll()) &&
10734 "omp target teams distribute parallel for loop exprs were not built");
10735
Alexey Bataev647dd842018-01-15 20:59:40 +000010736 if (!CurContext->isDependentContext()) {
10737 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010738 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010739 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10740 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10741 B.NumIterations, *this, CurScope,
10742 DSAStack))
10743 return StmtError();
10744 }
10745 }
10746
Reid Kleckner87a31802018-03-12 21:43:02 +000010747 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010748 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010749 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10750 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010751}
10752
Kelvin Li1851df52017-01-03 05:23:48 +000010753StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10754 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010755 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010756 if (!AStmt)
10757 return StmtError();
10758
Alexey Bataeve3727102018-04-18 15:57:46 +000010759 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010760 // 1.2.2 OpenMP Language Terminology
10761 // Structured block - An executable statement with a single entry at the
10762 // top and a single exit at the bottom.
10763 // The point of exit cannot be a branch out of the structured block.
10764 // longjmp() and throw() must not violate the entry/exit criteria.
10765 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010766 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10767 OMPD_target_teams_distribute_parallel_for_simd);
10768 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10769 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10770 // 1.2.2 OpenMP Language Terminology
10771 // Structured block - An executable statement with a single entry at the
10772 // top and a single exit at the bottom.
10773 // The point of exit cannot be a branch out of the structured block.
10774 // longjmp() and throw() must not violate the entry/exit criteria.
10775 CS->getCapturedDecl()->setNothrow();
10776 }
Kelvin Li1851df52017-01-03 05:23:48 +000010777
10778 OMPLoopDirective::HelperExprs B;
10779 // In presence of clause 'collapse' with number of loops, it will
10780 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010781 unsigned NestedLoopCount =
10782 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010783 getCollapseNumberExpr(Clauses),
10784 nullptr /*ordered not a clause on distribute*/, CS, *this,
10785 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010786 if (NestedLoopCount == 0)
10787 return StmtError();
10788
10789 assert((CurContext->isDependentContext() || B.builtAll()) &&
10790 "omp target teams distribute parallel for simd loop exprs were not "
10791 "built");
10792
10793 if (!CurContext->isDependentContext()) {
10794 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010795 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010796 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10797 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10798 B.NumIterations, *this, CurScope,
10799 DSAStack))
10800 return StmtError();
10801 }
10802 }
10803
Alexey Bataev438388c2017-11-22 18:34:02 +000010804 if (checkSimdlenSafelenSpecified(*this, Clauses))
10805 return StmtError();
10806
Reid Kleckner87a31802018-03-12 21:43:02 +000010807 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010808 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10809 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10810}
10811
Kelvin Lida681182017-01-10 18:08:18 +000010812StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10813 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010814 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010815 if (!AStmt)
10816 return StmtError();
10817
10818 auto *CS = cast<CapturedStmt>(AStmt);
10819 // 1.2.2 OpenMP Language Terminology
10820 // Structured block - An executable statement with a single entry at the
10821 // top and a single exit at the bottom.
10822 // The point of exit cannot be a branch out of the structured block.
10823 // longjmp() and throw() must not violate the entry/exit criteria.
10824 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010825 for (int ThisCaptureLevel =
10826 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10827 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10828 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10829 // 1.2.2 OpenMP Language Terminology
10830 // Structured block - An executable statement with a single entry at the
10831 // top and a single exit at the bottom.
10832 // The point of exit cannot be a branch out of the structured block.
10833 // longjmp() and throw() must not violate the entry/exit criteria.
10834 CS->getCapturedDecl()->setNothrow();
10835 }
Kelvin Lida681182017-01-10 18:08:18 +000010836
10837 OMPLoopDirective::HelperExprs B;
10838 // In presence of clause 'collapse' with number of loops, it will
10839 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010840 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010841 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010842 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010843 VarsWithImplicitDSA, B);
10844 if (NestedLoopCount == 0)
10845 return StmtError();
10846
10847 assert((CurContext->isDependentContext() || B.builtAll()) &&
10848 "omp target teams distribute simd loop exprs were not built");
10849
Alexey Bataev438388c2017-11-22 18:34:02 +000010850 if (!CurContext->isDependentContext()) {
10851 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010852 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010853 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10854 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10855 B.NumIterations, *this, CurScope,
10856 DSAStack))
10857 return StmtError();
10858 }
10859 }
10860
10861 if (checkSimdlenSafelenSpecified(*this, Clauses))
10862 return StmtError();
10863
Reid Kleckner87a31802018-03-12 21:43:02 +000010864 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010865 return OMPTargetTeamsDistributeSimdDirective::Create(
10866 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10867}
10868
Alexey Bataeved09d242014-05-28 05:53:51 +000010869OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010870 SourceLocation StartLoc,
10871 SourceLocation LParenLoc,
10872 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010873 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010874 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010875 case OMPC_final:
10876 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10877 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010878 case OMPC_num_threads:
10879 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10880 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010881 case OMPC_safelen:
10882 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10883 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010884 case OMPC_simdlen:
10885 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10886 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010887 case OMPC_allocator:
10888 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10889 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010890 case OMPC_collapse:
10891 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10892 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010893 case OMPC_ordered:
10894 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10895 break;
Michael Wonge710d542015-08-07 16:16:36 +000010896 case OMPC_device:
10897 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10898 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010899 case OMPC_num_teams:
10900 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10901 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010902 case OMPC_thread_limit:
10903 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10904 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010905 case OMPC_priority:
10906 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10907 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010908 case OMPC_grainsize:
10909 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10910 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010911 case OMPC_num_tasks:
10912 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10913 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010914 case OMPC_hint:
10915 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10916 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010917 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010918 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010919 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010920 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010921 case OMPC_private:
10922 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010923 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010924 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010925 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010926 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010927 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010928 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010929 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010930 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010931 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010932 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010933 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010934 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010935 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010936 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010937 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010938 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010939 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010940 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010941 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010942 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050010943 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050010944 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050010945 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050010946 case OMPC_relaxed:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010947 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010948 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010949 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010950 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010951 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010952 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010953 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010954 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010955 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010956 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010957 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010958 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010959 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010960 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010961 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010962 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010963 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010964 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010965 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010966 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050010967 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050010968 case OMPC_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010969 llvm_unreachable("Clause is not allowed.");
10970 }
10971 return Res;
10972}
10973
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010974// An OpenMP directive such as 'target parallel' has two captured regions:
10975// for the 'target' and 'parallel' respectively. This function returns
10976// the region in which to capture expressions associated with a clause.
10977// A return value of OMPD_unknown signifies that the expression should not
10978// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010979static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050010980 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010981 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010982 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010983 switch (CKind) {
10984 case OMPC_if:
10985 switch (DKind) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010986 case OMPD_target_parallel_for_simd:
10987 if (OpenMPVersion >= 50 &&
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010988 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010989 CaptureRegion = OMPD_parallel;
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010990 break;
10991 }
Alexey Bataevda17a532019-12-10 11:37:03 -050010992 LLVM_FALLTHROUGH;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010993 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010994 case OMPD_target_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010995 // If this clause applies to the nested 'parallel' region, capture within
10996 // the 'target' region, otherwise do not capture.
10997 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10998 CaptureRegion = OMPD_target;
10999 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000011000 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfd0c91b2019-12-16 10:27:39 -050011001 if (OpenMPVersion >= 50 &&
11002 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11003 CaptureRegion = OMPD_parallel;
11004 break;
11005 }
11006 LLVM_FALLTHROUGH;
11007 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +000011008 // If this clause applies to the nested 'parallel' region, capture within
11009 // the 'teams' region, otherwise do not capture.
11010 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
11011 CaptureRegion = OMPD_teams;
11012 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011013 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataev0b978942019-12-11 15:26:38 -050011014 if (OpenMPVersion >= 50 &&
11015 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
11016 CaptureRegion = OMPD_parallel;
11017 break;
11018 }
11019 LLVM_FALLTHROUGH;
11020 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011021 CaptureRegion = OMPD_teams;
11022 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011023 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011024 case OMPD_target_enter_data:
11025 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011026 CaptureRegion = OMPD_task;
11027 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011028 case OMPD_parallel_master_taskloop:
11029 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
11030 CaptureRegion = OMPD_parallel;
11031 break;
Alexey Bataev5c517a62019-12-05 11:31:45 -050011032 case OMPD_parallel_master_taskloop_simd:
11033 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
11034 NameModifier == OMPD_taskloop) {
11035 CaptureRegion = OMPD_parallel;
11036 break;
11037 }
11038 if (OpenMPVersion <= 45)
11039 break;
11040 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11041 CaptureRegion = OMPD_taskloop;
11042 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050011043 case OMPD_parallel_for_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050011044 if (OpenMPVersion <= 45)
11045 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050011046 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11047 CaptureRegion = OMPD_parallel;
11048 break;
Alexey Bataev61205822019-12-04 09:50:21 -050011049 case OMPD_taskloop_simd:
Alexey Bataev853961f2019-12-05 09:50:18 -050011050 case OMPD_master_taskloop_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050011051 if (OpenMPVersion <= 45)
11052 break;
11053 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11054 CaptureRegion = OMPD_taskloop;
11055 break;
Alexey Bataev52812f22019-12-05 13:22:15 -050011056 case OMPD_distribute_parallel_for_simd:
11057 if (OpenMPVersion <= 45)
11058 break;
11059 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
11060 CaptureRegion = OMPD_parallel;
11061 break;
Alexey Bataevef94cd12019-12-10 12:44:45 -050011062 case OMPD_target_simd:
11063 if (OpenMPVersion >= 50 &&
11064 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11065 CaptureRegion = OMPD_target;
11066 break;
Alexey Bataev7b774b72019-12-11 11:20:47 -050011067 case OMPD_teams_distribute_simd:
Alexey Bataev411e81a2019-12-16 11:16:46 -050011068 case OMPD_target_teams_distribute_simd:
Alexey Bataev7b774b72019-12-11 11:20:47 -050011069 if (OpenMPVersion >= 50 &&
11070 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
11071 CaptureRegion = OMPD_teams;
11072 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011073 case OMPD_cancel:
11074 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011075 case OMPD_parallel_master:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011076 case OMPD_parallel_sections:
11077 case OMPD_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011078 case OMPD_target:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011079 case OMPD_target_teams:
11080 case OMPD_target_teams_distribute:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011081 case OMPD_distribute_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011082 case OMPD_task:
11083 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011084 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011085 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050011086 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050011087 case OMPD_for_simd:
Alexey Bataev779a1802019-12-06 12:21:31 -050011088 case OMPD_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011089 // Do not capture if-clause expressions.
11090 break;
11091 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011092 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011093 case OMPD_taskyield:
11094 case OMPD_barrier:
11095 case OMPD_taskwait:
11096 case OMPD_cancellation_point:
11097 case OMPD_flush:
11098 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011099 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011100 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011101 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011102 case OMPD_declare_target:
11103 case OMPD_end_declare_target:
11104 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011105 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011106 case OMPD_sections:
11107 case OMPD_section:
11108 case OMPD_single:
11109 case OMPD_master:
11110 case OMPD_critical:
11111 case OMPD_taskgroup:
11112 case OMPD_distribute:
11113 case OMPD_ordered:
11114 case OMPD_atomic:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011115 case OMPD_teams_distribute:
Kelvin Li1408f912018-09-26 04:28:39 +000011116 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011117 llvm_unreachable("Unexpected OpenMP directive with if-clause");
11118 case OMPD_unknown:
11119 llvm_unreachable("Unknown OpenMP directive");
11120 }
11121 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011122 case OMPC_num_threads:
11123 switch (DKind) {
11124 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011125 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000011126 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011127 CaptureRegion = OMPD_target;
11128 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000011129 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011130 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011131 case OMPD_target_teams_distribute_parallel_for:
11132 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011133 CaptureRegion = OMPD_teams;
11134 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011135 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011136 case OMPD_parallel_master:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011137 case OMPD_parallel_sections:
11138 case OMPD_parallel_for:
11139 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011140 case OMPD_distribute_parallel_for:
11141 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011142 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011143 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011144 // Do not capture num_threads-clause expressions.
11145 break;
11146 case OMPD_target_data:
11147 case OMPD_target_enter_data:
11148 case OMPD_target_exit_data:
11149 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011150 case OMPD_target:
11151 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011152 case OMPD_target_teams:
11153 case OMPD_target_teams_distribute:
11154 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011155 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011156 case OMPD_task:
11157 case OMPD_taskloop:
11158 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011159 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011160 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011161 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011162 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011163 case OMPD_taskyield:
11164 case OMPD_barrier:
11165 case OMPD_taskwait:
11166 case OMPD_cancellation_point:
11167 case OMPD_flush:
11168 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011169 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011170 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011171 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011172 case OMPD_declare_target:
11173 case OMPD_end_declare_target:
11174 case OMPD_teams:
11175 case OMPD_simd:
11176 case OMPD_for:
11177 case OMPD_for_simd:
11178 case OMPD_sections:
11179 case OMPD_section:
11180 case OMPD_single:
11181 case OMPD_master:
11182 case OMPD_critical:
11183 case OMPD_taskgroup:
11184 case OMPD_distribute:
11185 case OMPD_ordered:
11186 case OMPD_atomic:
11187 case OMPD_distribute_simd:
11188 case OMPD_teams_distribute:
11189 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011190 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011191 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
11192 case OMPD_unknown:
11193 llvm_unreachable("Unknown OpenMP directive");
11194 }
11195 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011196 case OMPC_num_teams:
11197 switch (DKind) {
11198 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011199 case OMPD_target_teams_distribute:
11200 case OMPD_target_teams_distribute_simd:
11201 case OMPD_target_teams_distribute_parallel_for:
11202 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011203 CaptureRegion = OMPD_target;
11204 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011205 case OMPD_teams_distribute_parallel_for:
11206 case OMPD_teams_distribute_parallel_for_simd:
11207 case OMPD_teams:
11208 case OMPD_teams_distribute:
11209 case OMPD_teams_distribute_simd:
11210 // Do not capture num_teams-clause expressions.
11211 break;
11212 case OMPD_distribute_parallel_for:
11213 case OMPD_distribute_parallel_for_simd:
11214 case OMPD_task:
11215 case OMPD_taskloop:
11216 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011217 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011218 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011219 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011220 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011221 case OMPD_target_data:
11222 case OMPD_target_enter_data:
11223 case OMPD_target_exit_data:
11224 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011225 case OMPD_cancel:
11226 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011227 case OMPD_parallel_master:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011228 case OMPD_parallel_sections:
11229 case OMPD_parallel_for:
11230 case OMPD_parallel_for_simd:
11231 case OMPD_target:
11232 case OMPD_target_simd:
11233 case OMPD_target_parallel:
11234 case OMPD_target_parallel_for:
11235 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011236 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011237 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011238 case OMPD_taskyield:
11239 case OMPD_barrier:
11240 case OMPD_taskwait:
11241 case OMPD_cancellation_point:
11242 case OMPD_flush:
11243 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011244 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011245 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011246 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011247 case OMPD_declare_target:
11248 case OMPD_end_declare_target:
11249 case OMPD_simd:
11250 case OMPD_for:
11251 case OMPD_for_simd:
11252 case OMPD_sections:
11253 case OMPD_section:
11254 case OMPD_single:
11255 case OMPD_master:
11256 case OMPD_critical:
11257 case OMPD_taskgroup:
11258 case OMPD_distribute:
11259 case OMPD_ordered:
11260 case OMPD_atomic:
11261 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011262 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011263 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11264 case OMPD_unknown:
11265 llvm_unreachable("Unknown OpenMP directive");
11266 }
11267 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011268 case OMPC_thread_limit:
11269 switch (DKind) {
11270 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011271 case OMPD_target_teams_distribute:
11272 case OMPD_target_teams_distribute_simd:
11273 case OMPD_target_teams_distribute_parallel_for:
11274 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011275 CaptureRegion = OMPD_target;
11276 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011277 case OMPD_teams_distribute_parallel_for:
11278 case OMPD_teams_distribute_parallel_for_simd:
11279 case OMPD_teams:
11280 case OMPD_teams_distribute:
11281 case OMPD_teams_distribute_simd:
11282 // Do not capture thread_limit-clause expressions.
11283 break;
11284 case OMPD_distribute_parallel_for:
11285 case OMPD_distribute_parallel_for_simd:
11286 case OMPD_task:
11287 case OMPD_taskloop:
11288 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011289 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011290 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011291 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011292 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011293 case OMPD_target_data:
11294 case OMPD_target_enter_data:
11295 case OMPD_target_exit_data:
11296 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011297 case OMPD_cancel:
11298 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011299 case OMPD_parallel_master:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011300 case OMPD_parallel_sections:
11301 case OMPD_parallel_for:
11302 case OMPD_parallel_for_simd:
11303 case OMPD_target:
11304 case OMPD_target_simd:
11305 case OMPD_target_parallel:
11306 case OMPD_target_parallel_for:
11307 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011308 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011309 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011310 case OMPD_taskyield:
11311 case OMPD_barrier:
11312 case OMPD_taskwait:
11313 case OMPD_cancellation_point:
11314 case OMPD_flush:
11315 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011316 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011317 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011318 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011319 case OMPD_declare_target:
11320 case OMPD_end_declare_target:
11321 case OMPD_simd:
11322 case OMPD_for:
11323 case OMPD_for_simd:
11324 case OMPD_sections:
11325 case OMPD_section:
11326 case OMPD_single:
11327 case OMPD_master:
11328 case OMPD_critical:
11329 case OMPD_taskgroup:
11330 case OMPD_distribute:
11331 case OMPD_ordered:
11332 case OMPD_atomic:
11333 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011334 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011335 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
11336 case OMPD_unknown:
11337 llvm_unreachable("Unknown OpenMP directive");
11338 }
11339 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011340 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011341 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000011342 case OMPD_parallel_for:
11343 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011344 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000011345 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011346 case OMPD_teams_distribute_parallel_for:
11347 case OMPD_teams_distribute_parallel_for_simd:
11348 case OMPD_target_parallel_for:
11349 case OMPD_target_parallel_for_simd:
11350 case OMPD_target_teams_distribute_parallel_for:
11351 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011352 CaptureRegion = OMPD_parallel;
11353 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011354 case OMPD_for:
11355 case OMPD_for_simd:
11356 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011357 break;
11358 case OMPD_task:
11359 case OMPD_taskloop:
11360 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011361 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011362 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011363 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011364 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011365 case OMPD_target_data:
11366 case OMPD_target_enter_data:
11367 case OMPD_target_exit_data:
11368 case OMPD_target_update:
11369 case OMPD_teams:
11370 case OMPD_teams_distribute:
11371 case OMPD_teams_distribute_simd:
11372 case OMPD_target_teams_distribute:
11373 case OMPD_target_teams_distribute_simd:
11374 case OMPD_target:
11375 case OMPD_target_simd:
11376 case OMPD_target_parallel:
11377 case OMPD_cancel:
11378 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011379 case OMPD_parallel_master:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011380 case OMPD_parallel_sections:
11381 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011382 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011383 case OMPD_taskyield:
11384 case OMPD_barrier:
11385 case OMPD_taskwait:
11386 case OMPD_cancellation_point:
11387 case OMPD_flush:
11388 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011389 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011390 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011391 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011392 case OMPD_declare_target:
11393 case OMPD_end_declare_target:
11394 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011395 case OMPD_sections:
11396 case OMPD_section:
11397 case OMPD_single:
11398 case OMPD_master:
11399 case OMPD_critical:
11400 case OMPD_taskgroup:
11401 case OMPD_distribute:
11402 case OMPD_ordered:
11403 case OMPD_atomic:
11404 case OMPD_distribute_simd:
11405 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011406 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011407 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11408 case OMPD_unknown:
11409 llvm_unreachable("Unknown OpenMP directive");
11410 }
11411 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011412 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011413 switch (DKind) {
11414 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011415 case OMPD_teams_distribute_parallel_for_simd:
11416 case OMPD_teams_distribute:
11417 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011418 case OMPD_target_teams_distribute_parallel_for:
11419 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011420 case OMPD_target_teams_distribute:
11421 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011422 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011423 break;
11424 case OMPD_distribute_parallel_for:
11425 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011426 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011427 case OMPD_distribute_simd:
11428 // Do not capture thread_limit-clause expressions.
11429 break;
11430 case OMPD_parallel_for:
11431 case OMPD_parallel_for_simd:
11432 case OMPD_target_parallel_for_simd:
11433 case OMPD_target_parallel_for:
11434 case OMPD_task:
11435 case OMPD_taskloop:
11436 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011437 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011438 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011439 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011440 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011441 case OMPD_target_data:
11442 case OMPD_target_enter_data:
11443 case OMPD_target_exit_data:
11444 case OMPD_target_update:
11445 case OMPD_teams:
11446 case OMPD_target:
11447 case OMPD_target_simd:
11448 case OMPD_target_parallel:
11449 case OMPD_cancel:
11450 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011451 case OMPD_parallel_master:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011452 case OMPD_parallel_sections:
11453 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011454 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011455 case OMPD_taskyield:
11456 case OMPD_barrier:
11457 case OMPD_taskwait:
11458 case OMPD_cancellation_point:
11459 case OMPD_flush:
11460 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011461 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011462 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011463 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011464 case OMPD_declare_target:
11465 case OMPD_end_declare_target:
11466 case OMPD_simd:
11467 case OMPD_for:
11468 case OMPD_for_simd:
11469 case OMPD_sections:
11470 case OMPD_section:
11471 case OMPD_single:
11472 case OMPD_master:
11473 case OMPD_critical:
11474 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011475 case OMPD_ordered:
11476 case OMPD_atomic:
11477 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011478 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011479 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11480 case OMPD_unknown:
11481 llvm_unreachable("Unknown OpenMP directive");
11482 }
11483 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011484 case OMPC_device:
11485 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011486 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011487 case OMPD_target_enter_data:
11488 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011489 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011490 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011491 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011492 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011493 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011494 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011495 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011496 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011497 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011498 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011499 CaptureRegion = OMPD_task;
11500 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011501 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011502 // Do not capture device-clause expressions.
11503 break;
11504 case OMPD_teams_distribute_parallel_for:
11505 case OMPD_teams_distribute_parallel_for_simd:
11506 case OMPD_teams:
11507 case OMPD_teams_distribute:
11508 case OMPD_teams_distribute_simd:
11509 case OMPD_distribute_parallel_for:
11510 case OMPD_distribute_parallel_for_simd:
11511 case OMPD_task:
11512 case OMPD_taskloop:
11513 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011514 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011515 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011516 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011517 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011518 case OMPD_cancel:
11519 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011520 case OMPD_parallel_master:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011521 case OMPD_parallel_sections:
11522 case OMPD_parallel_for:
11523 case OMPD_parallel_for_simd:
11524 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011525 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011526 case OMPD_taskyield:
11527 case OMPD_barrier:
11528 case OMPD_taskwait:
11529 case OMPD_cancellation_point:
11530 case OMPD_flush:
11531 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011532 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011533 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011534 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011535 case OMPD_declare_target:
11536 case OMPD_end_declare_target:
11537 case OMPD_simd:
11538 case OMPD_for:
11539 case OMPD_for_simd:
11540 case OMPD_sections:
11541 case OMPD_section:
11542 case OMPD_single:
11543 case OMPD_master:
11544 case OMPD_critical:
11545 case OMPD_taskgroup:
11546 case OMPD_distribute:
11547 case OMPD_ordered:
11548 case OMPD_atomic:
11549 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011550 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011551 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11552 case OMPD_unknown:
11553 llvm_unreachable("Unknown OpenMP directive");
11554 }
11555 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011556 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011557 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011558 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011559 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011560 switch (DKind) {
11561 case OMPD_task:
11562 case OMPD_taskloop:
11563 case OMPD_taskloop_simd:
11564 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011565 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011566 break;
11567 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011568 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011569 CaptureRegion = OMPD_parallel;
11570 break;
11571 case OMPD_target_update:
11572 case OMPD_target_enter_data:
11573 case OMPD_target_exit_data:
11574 case OMPD_target:
11575 case OMPD_target_simd:
11576 case OMPD_target_teams:
11577 case OMPD_target_parallel:
11578 case OMPD_target_teams_distribute:
11579 case OMPD_target_teams_distribute_simd:
11580 case OMPD_target_parallel_for:
11581 case OMPD_target_parallel_for_simd:
11582 case OMPD_target_teams_distribute_parallel_for:
11583 case OMPD_target_teams_distribute_parallel_for_simd:
11584 case OMPD_target_data:
11585 case OMPD_teams_distribute_parallel_for:
11586 case OMPD_teams_distribute_parallel_for_simd:
11587 case OMPD_teams:
11588 case OMPD_teams_distribute:
11589 case OMPD_teams_distribute_simd:
11590 case OMPD_distribute_parallel_for:
11591 case OMPD_distribute_parallel_for_simd:
11592 case OMPD_cancel:
11593 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011594 case OMPD_parallel_master:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011595 case OMPD_parallel_sections:
11596 case OMPD_parallel_for:
11597 case OMPD_parallel_for_simd:
11598 case OMPD_threadprivate:
11599 case OMPD_allocate:
11600 case OMPD_taskyield:
11601 case OMPD_barrier:
11602 case OMPD_taskwait:
11603 case OMPD_cancellation_point:
11604 case OMPD_flush:
11605 case OMPD_declare_reduction:
11606 case OMPD_declare_mapper:
11607 case OMPD_declare_simd:
11608 case OMPD_declare_variant:
11609 case OMPD_declare_target:
11610 case OMPD_end_declare_target:
11611 case OMPD_simd:
11612 case OMPD_for:
11613 case OMPD_for_simd:
11614 case OMPD_sections:
11615 case OMPD_section:
11616 case OMPD_single:
11617 case OMPD_master:
11618 case OMPD_critical:
11619 case OMPD_taskgroup:
11620 case OMPD_distribute:
11621 case OMPD_ordered:
11622 case OMPD_atomic:
11623 case OMPD_distribute_simd:
11624 case OMPD_requires:
11625 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11626 case OMPD_unknown:
11627 llvm_unreachable("Unknown OpenMP directive");
11628 }
11629 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011630 case OMPC_firstprivate:
11631 case OMPC_lastprivate:
11632 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011633 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011634 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011635 case OMPC_linear:
11636 case OMPC_default:
11637 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011638 case OMPC_safelen:
11639 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011640 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011641 case OMPC_collapse:
11642 case OMPC_private:
11643 case OMPC_shared:
11644 case OMPC_aligned:
11645 case OMPC_copyin:
11646 case OMPC_copyprivate:
11647 case OMPC_ordered:
11648 case OMPC_nowait:
11649 case OMPC_untied:
11650 case OMPC_mergeable:
11651 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011652 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011653 case OMPC_flush:
11654 case OMPC_read:
11655 case OMPC_write:
11656 case OMPC_update:
11657 case OMPC_capture:
11658 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050011659 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050011660 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050011661 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050011662 case OMPC_relaxed:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011663 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011664 case OMPC_threads:
11665 case OMPC_simd:
11666 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011667 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011668 case OMPC_hint:
11669 case OMPC_defaultmap:
11670 case OMPC_unknown:
11671 case OMPC_uniform:
11672 case OMPC_to:
11673 case OMPC_from:
11674 case OMPC_use_device_ptr:
11675 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011676 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011677 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011678 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011679 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011680 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011681 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011682 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011683 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050011684 case OMPC_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011685 llvm_unreachable("Unexpected OpenMP clause.");
11686 }
11687 return CaptureRegion;
11688}
11689
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011690OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11691 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011692 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011693 SourceLocation NameModifierLoc,
11694 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011695 SourceLocation EndLoc) {
11696 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011697 Stmt *HelperValStmt = nullptr;
11698 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011699 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11700 !Condition->isInstantiationDependent() &&
11701 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011702 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011703 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011704 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011705
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011706 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011707
11708 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011709 CaptureRegion = getOpenMPCaptureRegionForClause(
11710 DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011711 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011712 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011713 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011714 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11715 HelperValStmt = buildPreInits(Context, Captures);
11716 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011717 }
11718
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011719 return new (Context)
11720 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11721 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011722}
11723
Alexey Bataev3778b602014-07-17 07:32:53 +000011724OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11725 SourceLocation StartLoc,
11726 SourceLocation LParenLoc,
11727 SourceLocation EndLoc) {
11728 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011729 Stmt *HelperValStmt = nullptr;
11730 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011731 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11732 !Condition->isInstantiationDependent() &&
11733 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011734 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011735 if (Val.isInvalid())
11736 return nullptr;
11737
Richard Smith03a4aa32016-06-23 19:02:52 +000011738 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011739
11740 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011741 CaptureRegion =
11742 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011743 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11744 ValExpr = MakeFullExpr(ValExpr).get();
11745 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11746 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11747 HelperValStmt = buildPreInits(Context, Captures);
11748 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011749 }
11750
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011751 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11752 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011753}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011754
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011755ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11756 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011757 if (!Op)
11758 return ExprError();
11759
11760 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11761 public:
11762 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011763 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011764 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11765 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011766 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11767 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011768 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11769 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011770 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11771 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011772 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11773 QualType T,
11774 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011775 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11776 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011777 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11778 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011779 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011780 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011781 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011782 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11783 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011784 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11785 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011786 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11787 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011788 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011789 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011790 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011791 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11792 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011793 llvm_unreachable("conversion functions are permitted");
11794 }
11795 } ConvertDiagnoser;
11796 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11797}
11798
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011799static bool
11800isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11801 bool StrictlyPositive, bool BuildCapture = false,
11802 OpenMPDirectiveKind DKind = OMPD_unknown,
11803 OpenMPDirectiveKind *CaptureRegion = nullptr,
11804 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011805 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11806 !ValExpr->isInstantiationDependent()) {
11807 SourceLocation Loc = ValExpr->getExprLoc();
11808 ExprResult Value =
11809 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11810 if (Value.isInvalid())
11811 return false;
11812
11813 ValExpr = Value.get();
11814 // The expression must evaluate to a non-negative integer value.
11815 llvm::APSInt Result;
11816 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011817 Result.isSigned() &&
11818 !((!StrictlyPositive && Result.isNonNegative()) ||
11819 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011820 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011821 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11822 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011823 return false;
11824 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011825 if (!BuildCapture)
11826 return true;
Alexey Bataev61205822019-12-04 09:50:21 -050011827 *CaptureRegion =
11828 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011829 if (*CaptureRegion != OMPD_unknown &&
11830 !SemaRef.CurContext->isDependentContext()) {
11831 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11832 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11833 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11834 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11835 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011836 }
11837 return true;
11838}
11839
Alexey Bataev568a8332014-03-06 06:15:19 +000011840OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11841 SourceLocation StartLoc,
11842 SourceLocation LParenLoc,
11843 SourceLocation EndLoc) {
11844 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011845 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011846
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011847 // OpenMP [2.5, Restrictions]
11848 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011849 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011850 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011851 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011852
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011853 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011854 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050011855 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011856 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011857 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011858 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011859 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11860 HelperValStmt = buildPreInits(Context, Captures);
11861 }
11862
11863 return new (Context) OMPNumThreadsClause(
11864 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011865}
11866
Alexey Bataev62c87d22014-03-21 04:51:18 +000011867ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011868 OpenMPClauseKind CKind,
11869 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011870 if (!E)
11871 return ExprError();
11872 if (E->isValueDependent() || E->isTypeDependent() ||
11873 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011874 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011875 llvm::APSInt Result;
11876 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11877 if (ICE.isInvalid())
11878 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011879 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11880 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011881 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011882 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11883 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011884 return ExprError();
11885 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011886 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11887 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11888 << E->getSourceRange();
11889 return ExprError();
11890 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011891 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11892 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011893 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011894 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011895 return ICE;
11896}
11897
11898OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11899 SourceLocation LParenLoc,
11900 SourceLocation EndLoc) {
11901 // OpenMP [2.8.1, simd construct, Description]
11902 // The parameter of the safelen clause must be a constant
11903 // positive integer expression.
11904 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11905 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011906 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011907 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011908 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011909}
11910
Alexey Bataev66b15b52015-08-21 11:14:16 +000011911OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11912 SourceLocation LParenLoc,
11913 SourceLocation EndLoc) {
11914 // OpenMP [2.8.1, simd construct, Description]
11915 // The parameter of the simdlen clause must be a constant
11916 // positive integer expression.
11917 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11918 if (Simdlen.isInvalid())
11919 return nullptr;
11920 return new (Context)
11921 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11922}
11923
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011924/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011925static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11926 DSAStackTy *Stack) {
11927 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011928 if (!OMPAllocatorHandleT.isNull())
11929 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011930 // Build the predefined allocator expressions.
11931 bool ErrorFound = false;
11932 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11933 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11934 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11935 StringRef Allocator =
11936 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11937 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11938 auto *VD = dyn_cast_or_null<ValueDecl>(
11939 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11940 if (!VD) {
11941 ErrorFound = true;
11942 break;
11943 }
11944 QualType AllocatorType =
11945 VD->getType().getNonLValueExprType(S.getASTContext());
11946 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11947 if (!Res.isUsable()) {
11948 ErrorFound = true;
11949 break;
11950 }
11951 if (OMPAllocatorHandleT.isNull())
11952 OMPAllocatorHandleT = AllocatorType;
11953 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11954 ErrorFound = true;
11955 break;
11956 }
11957 Stack->setAllocator(AllocatorKind, Res.get());
11958 }
11959 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011960 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11961 return false;
11962 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011963 OMPAllocatorHandleT.addConst();
11964 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011965 return true;
11966}
11967
11968OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11969 SourceLocation LParenLoc,
11970 SourceLocation EndLoc) {
11971 // OpenMP [2.11.3, allocate Directive, Description]
11972 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011973 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011974 return nullptr;
11975
11976 ExprResult Allocator = DefaultLvalueConversion(A);
11977 if (Allocator.isInvalid())
11978 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011979 Allocator = PerformImplicitConversion(Allocator.get(),
11980 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011981 Sema::AA_Initializing,
11982 /*AllowExplicit=*/true);
11983 if (Allocator.isInvalid())
11984 return nullptr;
11985 return new (Context)
11986 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11987}
11988
Alexander Musman64d33f12014-06-04 07:53:32 +000011989OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11990 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011991 SourceLocation LParenLoc,
11992 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011993 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011994 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011995 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011996 // The parameter of the collapse clause must be a constant
11997 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011998 ExprResult NumForLoopsResult =
11999 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
12000 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000012001 return nullptr;
12002 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000012003 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000012004}
12005
Alexey Bataev10e775f2015-07-30 11:36:16 +000012006OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
12007 SourceLocation EndLoc,
12008 SourceLocation LParenLoc,
12009 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000012010 // OpenMP [2.7.1, loop construct, Description]
12011 // OpenMP [2.8.1, simd construct, Description]
12012 // OpenMP [2.9.6, distribute construct, Description]
12013 // The parameter of the ordered clause must be a constant
12014 // positive integer expression if any.
12015 if (NumForLoops && LParenLoc.isValid()) {
12016 ExprResult NumForLoopsResult =
12017 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
12018 if (NumForLoopsResult.isInvalid())
12019 return nullptr;
12020 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012021 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000012022 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012023 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000012024 auto *Clause = OMPOrderedClause::Create(
12025 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
12026 StartLoc, LParenLoc, EndLoc);
12027 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
12028 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000012029}
12030
Alexey Bataeved09d242014-05-28 05:53:51 +000012031OMPClause *Sema::ActOnOpenMPSimpleClause(
12032 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
12033 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012034 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012035 switch (Kind) {
12036 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000012037 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000012038 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
12039 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012040 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012041 case OMPC_proc_bind:
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012042 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
12043 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012044 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012045 case OMPC_atomic_default_mem_order:
12046 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
12047 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
12048 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12049 break;
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012050 case OMPC_order:
12051 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
12052 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
12053 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012054 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012055 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012056 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012057 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012058 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012059 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012060 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012061 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012062 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012063 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000012064 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000012065 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000012066 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012067 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012068 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000012069 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012070 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012071 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012072 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012073 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012074 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012075 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012076 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012077 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012078 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012079 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012080 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012081 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012082 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012083 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012084 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050012085 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050012086 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050012087 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012088 case OMPC_relaxed:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012089 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012090 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012091 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012092 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012093 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012094 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012095 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012096 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012097 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012098 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012099 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012100 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012101 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012102 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012103 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012104 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012105 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012106 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012107 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012108 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000012109 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012110 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012111 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012112 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000012113 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012114 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012115 case OMPC_nontemporal:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012116 llvm_unreachable("Clause is not allowed.");
12117 }
12118 return Res;
12119}
12120
Alexey Bataev6402bca2015-12-28 07:25:51 +000012121static std::string
12122getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
12123 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012124 SmallString<256> Buffer;
12125 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000012126 unsigned Skipped = Exclude.size();
12127 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000012128 for (unsigned I = First; I < Last; ++I) {
12129 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012130 --Skipped;
12131 continue;
12132 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012133 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
Alexey Bataev87a004d2020-01-02 09:26:32 -050012134 if (I + Skipped + 2 == Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000012135 Out << " or ";
Alexey Bataev87a004d2020-01-02 09:26:32 -050012136 else if (I + Skipped + 1 != Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000012137 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000012138 }
Benjamin Krameradcd0262020-01-28 20:23:46 +010012139 return std::string(Out.str());
Alexey Bataev6402bca2015-12-28 07:25:51 +000012140}
12141
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012142OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
12143 SourceLocation KindKwLoc,
12144 SourceLocation StartLoc,
12145 SourceLocation LParenLoc,
12146 SourceLocation EndLoc) {
12147 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000012148 static_assert(OMPC_DEFAULT_unknown > 0,
12149 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012150 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012151 << getListOfPossibleValues(OMPC_default, /*First=*/0,
12152 /*Last=*/OMPC_DEFAULT_unknown)
12153 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012154 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012155 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000012156 switch (Kind) {
12157 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012158 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012159 break;
12160 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012161 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012162 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012163 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012164 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000012165 break;
12166 }
Alexey Bataeved09d242014-05-28 05:53:51 +000012167 return new (Context)
12168 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012169}
12170
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012171OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012172 SourceLocation KindKwLoc,
12173 SourceLocation StartLoc,
12174 SourceLocation LParenLoc,
12175 SourceLocation EndLoc) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012176 if (Kind == OMP_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012177 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012178 << getListOfPossibleValues(OMPC_proc_bind,
12179 /*First=*/unsigned(OMP_PROC_BIND_master),
12180 /*Last=*/5)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012181 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012182 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012183 }
Alexey Bataeved09d242014-05-28 05:53:51 +000012184 return new (Context)
12185 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012186}
12187
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012188OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
12189 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
12190 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12191 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
12192 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12193 << getListOfPossibleValues(
12194 OMPC_atomic_default_mem_order, /*First=*/0,
12195 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
12196 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
12197 return nullptr;
12198 }
12199 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
12200 LParenLoc, EndLoc);
12201}
12202
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012203OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
12204 SourceLocation KindKwLoc,
12205 SourceLocation StartLoc,
12206 SourceLocation LParenLoc,
12207 SourceLocation EndLoc) {
12208 if (Kind == OMPC_ORDER_unknown) {
12209 static_assert(OMPC_ORDER_unknown > 0,
12210 "OMPC_ORDER_unknown not greater than 0");
12211 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12212 << getListOfPossibleValues(OMPC_order, /*First=*/0,
12213 /*Last=*/OMPC_ORDER_unknown)
12214 << getOpenMPClauseName(OMPC_order);
12215 return nullptr;
12216 }
12217 return new (Context)
12218 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12219}
12220
Alexey Bataev56dafe82014-06-20 07:16:17 +000012221OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012222 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012223 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012224 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012225 SourceLocation EndLoc) {
12226 OMPClause *Res = nullptr;
12227 switch (Kind) {
12228 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012229 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
12230 assert(Argument.size() == NumberOfElements &&
12231 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012232 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012233 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
12234 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
12235 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
12236 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
12237 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012238 break;
12239 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012240 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
12241 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
12242 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
12243 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000012244 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012245 case OMPC_dist_schedule:
12246 Res = ActOnOpenMPDistScheduleClause(
12247 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
12248 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
12249 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012250 case OMPC_defaultmap:
12251 enum { Modifier, DefaultmapKind };
12252 Res = ActOnOpenMPDefaultmapClause(
12253 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
12254 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000012255 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
12256 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012257 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000012258 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012259 case OMPC_num_threads:
12260 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012261 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012262 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012263 case OMPC_collapse:
12264 case OMPC_default:
12265 case OMPC_proc_bind:
12266 case OMPC_private:
12267 case OMPC_firstprivate:
12268 case OMPC_lastprivate:
12269 case OMPC_shared:
12270 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012271 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012272 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012273 case OMPC_linear:
12274 case OMPC_aligned:
12275 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012276 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012277 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012278 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012279 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012280 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012281 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012282 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012283 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012284 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012285 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012286 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012287 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012288 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050012289 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050012290 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050012291 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012292 case OMPC_relaxed:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012293 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012294 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012295 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012296 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012297 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012298 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012299 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012300 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012301 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012302 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012303 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012304 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012305 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012306 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012307 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012308 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012309 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012310 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000012311 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012312 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012313 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012314 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012315 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012316 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012317 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012318 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012319 case OMPC_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012320 llvm_unreachable("Clause is not allowed.");
12321 }
12322 return Res;
12323}
12324
Alexey Bataev6402bca2015-12-28 07:25:51 +000012325static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
12326 OpenMPScheduleClauseModifier M2,
12327 SourceLocation M1Loc, SourceLocation M2Loc) {
12328 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
12329 SmallVector<unsigned, 2> Excluded;
12330 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
12331 Excluded.push_back(M2);
12332 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
12333 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
12334 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
12335 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
12336 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
12337 << getListOfPossibleValues(OMPC_schedule,
12338 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
12339 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12340 Excluded)
12341 << getOpenMPClauseName(OMPC_schedule);
12342 return true;
12343 }
12344 return false;
12345}
12346
Alexey Bataev56dafe82014-06-20 07:16:17 +000012347OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012348 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012349 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012350 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
12351 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
12352 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
12353 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
12354 return nullptr;
12355 // OpenMP, 2.7.1, Loop Construct, Restrictions
12356 // Either the monotonic modifier or the nonmonotonic modifier can be specified
12357 // but not both.
12358 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
12359 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
12360 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
12361 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
12362 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
12363 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
12364 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
12365 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
12366 return nullptr;
12367 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012368 if (Kind == OMPC_SCHEDULE_unknown) {
12369 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000012370 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
12371 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
12372 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12373 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12374 Exclude);
12375 } else {
12376 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12377 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012378 }
12379 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12380 << Values << getOpenMPClauseName(OMPC_schedule);
12381 return nullptr;
12382 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000012383 // OpenMP, 2.7.1, Loop Construct, Restrictions
12384 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
12385 // schedule(guided).
12386 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
12387 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
12388 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
12389 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
12390 diag::err_omp_schedule_nonmonotonic_static);
12391 return nullptr;
12392 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012393 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012394 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000012395 if (ChunkSize) {
12396 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12397 !ChunkSize->isInstantiationDependent() &&
12398 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012399 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000012400 ExprResult Val =
12401 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12402 if (Val.isInvalid())
12403 return nullptr;
12404
12405 ValExpr = Val.get();
12406
12407 // OpenMP [2.7.1, Restrictions]
12408 // chunk_size must be a loop invariant integer expression with a positive
12409 // value.
12410 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000012411 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12412 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12413 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000012414 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000012415 return nullptr;
12416 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012417 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050012418 DSAStack->getCurrentDirective(), OMPC_schedule,
12419 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012420 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012421 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012422 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012423 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12424 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012425 }
12426 }
12427 }
12428
Alexey Bataev6402bca2015-12-28 07:25:51 +000012429 return new (Context)
12430 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012431 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012432}
12433
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012434OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12435 SourceLocation StartLoc,
12436 SourceLocation EndLoc) {
12437 OMPClause *Res = nullptr;
12438 switch (Kind) {
12439 case OMPC_ordered:
12440 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12441 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012442 case OMPC_nowait:
12443 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12444 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012445 case OMPC_untied:
12446 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12447 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012448 case OMPC_mergeable:
12449 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12450 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012451 case OMPC_read:
12452 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12453 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012454 case OMPC_write:
12455 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12456 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012457 case OMPC_update:
12458 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12459 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012460 case OMPC_capture:
12461 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12462 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012463 case OMPC_seq_cst:
12464 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12465 break;
Alexey Bataevea9166b2020-02-06 16:30:23 -050012466 case OMPC_acq_rel:
12467 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
12468 break;
Alexey Bataev04a830f2020-02-10 14:30:39 -050012469 case OMPC_acquire:
12470 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
12471 break;
Alexey Bataev95598342020-02-10 15:49:05 -050012472 case OMPC_release:
12473 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
12474 break;
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012475 case OMPC_relaxed:
12476 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
12477 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012478 case OMPC_threads:
12479 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12480 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012481 case OMPC_simd:
12482 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12483 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012484 case OMPC_nogroup:
12485 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12486 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012487 case OMPC_unified_address:
12488 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12489 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012490 case OMPC_unified_shared_memory:
12491 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12492 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012493 case OMPC_reverse_offload:
12494 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12495 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012496 case OMPC_dynamic_allocators:
12497 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12498 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012499 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012500 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012501 case OMPC_num_threads:
12502 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012503 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012504 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012505 case OMPC_collapse:
12506 case OMPC_schedule:
12507 case OMPC_private:
12508 case OMPC_firstprivate:
12509 case OMPC_lastprivate:
12510 case OMPC_shared:
12511 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012512 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012513 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012514 case OMPC_linear:
12515 case OMPC_aligned:
12516 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012517 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012518 case OMPC_default:
12519 case OMPC_proc_bind:
12520 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012521 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012522 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012523 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012524 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012525 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012526 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012527 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012528 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012529 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012530 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012531 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012532 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012533 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012534 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012535 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012536 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012537 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012538 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012539 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012540 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012541 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012542 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012543 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012544 case OMPC_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012545 llvm_unreachable("Clause is not allowed.");
12546 }
12547 return Res;
12548}
12549
Alexey Bataev236070f2014-06-20 11:19:47 +000012550OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12551 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012552 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012553 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12554}
12555
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012556OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12557 SourceLocation EndLoc) {
12558 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12559}
12560
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012561OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12562 SourceLocation EndLoc) {
12563 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12564}
12565
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012566OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12567 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012568 return new (Context) OMPReadClause(StartLoc, EndLoc);
12569}
12570
Alexey Bataevdea47612014-07-23 07:46:59 +000012571OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12572 SourceLocation EndLoc) {
12573 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12574}
12575
Alexey Bataev67a4f222014-07-23 10:25:33 +000012576OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12577 SourceLocation EndLoc) {
12578 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12579}
12580
Alexey Bataev459dec02014-07-24 06:46:57 +000012581OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12582 SourceLocation EndLoc) {
12583 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12584}
12585
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012586OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12587 SourceLocation EndLoc) {
12588 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12589}
12590
Alexey Bataevea9166b2020-02-06 16:30:23 -050012591OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
12592 SourceLocation EndLoc) {
12593 return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
12594}
12595
Alexey Bataev04a830f2020-02-10 14:30:39 -050012596OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
12597 SourceLocation EndLoc) {
12598 return new (Context) OMPAcquireClause(StartLoc, EndLoc);
12599}
12600
Alexey Bataev95598342020-02-10 15:49:05 -050012601OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
12602 SourceLocation EndLoc) {
12603 return new (Context) OMPReleaseClause(StartLoc, EndLoc);
12604}
12605
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012606OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
12607 SourceLocation EndLoc) {
12608 return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
12609}
12610
Alexey Bataev346265e2015-09-25 10:37:12 +000012611OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12612 SourceLocation EndLoc) {
12613 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12614}
12615
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012616OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12617 SourceLocation EndLoc) {
12618 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12619}
12620
Alexey Bataevb825de12015-12-07 10:51:44 +000012621OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12622 SourceLocation EndLoc) {
12623 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12624}
12625
Kelvin Li1408f912018-09-26 04:28:39 +000012626OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12627 SourceLocation EndLoc) {
12628 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12629}
12630
Patrick Lyster4a370b92018-10-01 13:47:43 +000012631OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12632 SourceLocation EndLoc) {
12633 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12634}
12635
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012636OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12637 SourceLocation EndLoc) {
12638 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12639}
12640
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012641OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12642 SourceLocation EndLoc) {
12643 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12644}
12645
Alexey Bataevc5e02582014-06-16 07:08:35 +000012646OMPClause *Sema::ActOnOpenMPVarListClause(
12647 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012648 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12649 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012650 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
Kelvin Lief579432018-12-18 22:18:41 +000012651 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012652 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
12653 SourceLocation DepLinMapLastLoc) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012654 SourceLocation StartLoc = Locs.StartLoc;
12655 SourceLocation LParenLoc = Locs.LParenLoc;
12656 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012657 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012658 switch (Kind) {
12659 case OMPC_private:
12660 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12661 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012662 case OMPC_firstprivate:
12663 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12664 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012665 case OMPC_lastprivate:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012666 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
12667 "Unexpected lastprivate modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012668 Res = ActOnOpenMPLastprivateClause(
12669 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
12670 DepLinMapLastLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012671 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012672 case OMPC_shared:
12673 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12674 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012675 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012676 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012677 EndLoc, ReductionOrMapperIdScopeSpec,
12678 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012679 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012680 case OMPC_task_reduction:
12681 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012682 EndLoc, ReductionOrMapperIdScopeSpec,
12683 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012684 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012685 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012686 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12687 EndLoc, ReductionOrMapperIdScopeSpec,
12688 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012689 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012690 case OMPC_linear:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012691 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
12692 "Unexpected linear modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012693 Res = ActOnOpenMPLinearClause(
12694 VarList, TailExpr, StartLoc, LParenLoc,
12695 static_cast<OpenMPLinearClauseKind>(ExtraModifier), DepLinMapLastLoc,
12696 ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012697 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012698 case OMPC_aligned:
12699 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12700 ColonLoc, EndLoc);
12701 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012702 case OMPC_copyin:
12703 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12704 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012705 case OMPC_copyprivate:
12706 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12707 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012708 case OMPC_flush:
12709 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12710 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012711 case OMPC_depend:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012712 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
12713 "Unexpected depend modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012714 Res = ActOnOpenMPDependClause(
12715 static_cast<OpenMPDependClauseKind>(ExtraModifier), DepLinMapLastLoc,
12716 ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012717 break;
12718 case OMPC_map:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012719 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
12720 "Unexpected map modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012721 Res = ActOnOpenMPMapClause(
12722 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
12723 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
12724 IsMapTypeImplicit, DepLinMapLastLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012725 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012726 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012727 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12728 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012729 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012730 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012731 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12732 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012733 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012734 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012735 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012736 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012737 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012738 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012739 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012740 case OMPC_allocate:
12741 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12742 ColonLoc, EndLoc);
12743 break;
Alexey Bataevb6e70842019-12-16 15:54:17 -050012744 case OMPC_nontemporal:
12745 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
12746 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012747 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012748 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012749 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012750 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012751 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012752 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012753 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012754 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012755 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012756 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012757 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012758 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012759 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012760 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012761 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012762 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012763 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012764 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012765 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012766 case OMPC_seq_cst:
Alexey Bataevea9166b2020-02-06 16:30:23 -050012767 case OMPC_acq_rel:
Alexey Bataev04a830f2020-02-10 14:30:39 -050012768 case OMPC_acquire:
Alexey Bataev95598342020-02-10 15:49:05 -050012769 case OMPC_release:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012770 case OMPC_relaxed:
Michael Wonge710d542015-08-07 16:16:36 +000012771 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012772 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012773 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012774 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012775 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012776 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012777 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012778 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012779 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012780 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012781 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012782 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012783 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012784 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012785 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012786 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012787 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012788 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012789 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012790 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012791 case OMPC_match:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012792 case OMPC_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012793 llvm_unreachable("Clause is not allowed.");
12794 }
12795 return Res;
12796}
12797
Alexey Bataev90c228f2016-02-08 09:29:13 +000012798ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012799 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012800 ExprResult Res = BuildDeclRefExpr(
12801 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12802 if (!Res.isUsable())
12803 return ExprError();
12804 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12805 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12806 if (!Res.isUsable())
12807 return ExprError();
12808 }
12809 if (VK != VK_LValue && Res.get()->isGLValue()) {
12810 Res = DefaultLvalueConversion(Res.get());
12811 if (!Res.isUsable())
12812 return ExprError();
12813 }
12814 return Res;
12815}
12816
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012817OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12818 SourceLocation StartLoc,
12819 SourceLocation LParenLoc,
12820 SourceLocation EndLoc) {
12821 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012822 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012823 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012824 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012825 SourceLocation ELoc;
12826 SourceRange ERange;
12827 Expr *SimpleRefExpr = RefExpr;
12828 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012829 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012830 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012831 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012832 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012833 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012834 ValueDecl *D = Res.first;
12835 if (!D)
12836 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012837
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012838 QualType Type = D->getType();
12839 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012840
12841 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12842 // A variable that appears in a private clause must not have an incomplete
12843 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012844 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012845 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012846 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012847
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012848 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12849 // A variable that is privatized must not have a const-qualified type
12850 // unless it is of class type with a mutable member. This restriction does
12851 // not apply to the firstprivate clause.
12852 //
12853 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12854 // A variable that appears in a private clause must not have a
12855 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012856 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012857 continue;
12858
Alexey Bataev758e55e2013-09-06 18:03:48 +000012859 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12860 // in a Construct]
12861 // Variables with the predetermined data-sharing attributes may not be
12862 // listed in data-sharing attributes clauses, except for the cases
12863 // listed below. For these exceptions only, listing a predetermined
12864 // variable in a data-sharing attribute clause is allowed and overrides
12865 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012866 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012867 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012868 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12869 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012870 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012871 continue;
12872 }
12873
Alexey Bataeve3727102018-04-18 15:57:46 +000012874 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012875 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012876 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012877 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012878 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12879 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012880 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012881 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012882 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012883 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012884 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012885 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012886 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012887 continue;
12888 }
12889
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012890 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12891 // A list item cannot appear in both a map clause and a data-sharing
12892 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012893 //
12894 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12895 // A list item cannot appear in both a map clause and a data-sharing
12896 // attribute clause on the same construct unless the construct is a
12897 // combined construct.
12898 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12899 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012900 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012901 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012902 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012903 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12904 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12905 ConflictKind = WhereFoundClauseKind;
12906 return true;
12907 })) {
12908 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012909 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012910 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012911 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012912 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012913 continue;
12914 }
12915 }
12916
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012917 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12918 // A variable of class type (or array thereof) that appears in a private
12919 // clause requires an accessible, unambiguous default constructor for the
12920 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012921 // Generate helper private variable and initialize it with the default
12922 // value. The address of the original variable is replaced by the address of
12923 // the new private variable in CodeGen. This new variable is not added to
12924 // IdResolver, so the code in the OpenMP region uses original variable for
12925 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012926 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012927 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012928 buildVarDecl(*this, ELoc, Type, D->getName(),
12929 D->hasAttrs() ? &D->getAttrs() : nullptr,
12930 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012931 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012932 if (VDPrivate->isInvalidDecl())
12933 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012934 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012935 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012936
Alexey Bataev90c228f2016-02-08 09:29:13 +000012937 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012938 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012939 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012940 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012941 Vars.push_back((VD || CurContext->isDependentContext())
12942 ? RefExpr->IgnoreParens()
12943 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012944 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012945 }
12946
Alexey Bataeved09d242014-05-28 05:53:51 +000012947 if (Vars.empty())
12948 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012949
Alexey Bataev03b340a2014-10-21 03:16:40 +000012950 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12951 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012952}
12953
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012954namespace {
12955class DiagsUninitializedSeveretyRAII {
12956private:
12957 DiagnosticsEngine &Diags;
12958 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012959 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012960
12961public:
12962 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12963 bool IsIgnored)
12964 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12965 if (!IsIgnored) {
12966 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12967 /*Map*/ diag::Severity::Ignored, Loc);
12968 }
12969 }
12970 ~DiagsUninitializedSeveretyRAII() {
12971 if (!IsIgnored)
12972 Diags.popMappings(SavedLoc);
12973 }
12974};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012975}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012976
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012977OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12978 SourceLocation StartLoc,
12979 SourceLocation LParenLoc,
12980 SourceLocation EndLoc) {
12981 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012982 SmallVector<Expr *, 8> PrivateCopies;
12983 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012984 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012985 bool IsImplicitClause =
12986 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012987 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012988
Alexey Bataeve3727102018-04-18 15:57:46 +000012989 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012990 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012991 SourceLocation ELoc;
12992 SourceRange ERange;
12993 Expr *SimpleRefExpr = RefExpr;
12994 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012995 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012996 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012997 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012998 PrivateCopies.push_back(nullptr);
12999 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013000 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000013001 ValueDecl *D = Res.first;
13002 if (!D)
13003 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013004
Alexey Bataev60da77e2016-02-29 05:54:20 +000013005 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000013006 QualType Type = D->getType();
13007 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013008
13009 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13010 // A variable that appears in a private clause must not have an incomplete
13011 // type or a reference type.
13012 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000013013 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013014 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013015 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013016
13017 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
13018 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000013019 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013020 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013021 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013022
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013023 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000013024 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013025 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013026 DSAStackTy::DSAVarData DVar =
13027 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000013028 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013029 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013030 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013031 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
13032 // A list item that specifies a given variable may not appear in more
13033 // than one clause on the same directive, except that a variable may be
13034 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013035 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13036 // A list item may appear in a firstprivate or lastprivate clause but not
13037 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013038 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000013039 (isOpenMPDistributeDirective(CurrDir) ||
13040 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013041 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013042 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000013043 << getOpenMPClauseName(DVar.CKind)
13044 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013045 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013046 continue;
13047 }
13048
13049 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13050 // in a Construct]
13051 // Variables with the predetermined data-sharing attributes may not be
13052 // listed in data-sharing attributes clauses, except for the cases
13053 // listed below. For these exceptions only, listing a predetermined
13054 // variable in a data-sharing attribute clause is allowed and overrides
13055 // the variable's predetermined data-sharing attributes.
13056 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13057 // in a Construct, C/C++, p.2]
13058 // Variables with const-qualified type having no mutable member may be
13059 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000013060 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013061 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
13062 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000013063 << getOpenMPClauseName(DVar.CKind)
13064 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013065 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013066 continue;
13067 }
13068
13069 // OpenMP [2.9.3.4, Restrictions, p.2]
13070 // A list item that is private within a parallel region must not appear
13071 // in a firstprivate clause on a worksharing construct if any of the
13072 // worksharing regions arising from the worksharing construct ever bind
13073 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013074 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13075 // A list item that is private within a teams region must not appear in a
13076 // firstprivate clause on a distribute construct if any of the distribute
13077 // regions arising from the distribute construct ever bind to any of the
13078 // teams regions arising from the teams construct.
13079 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
13080 // A list item that appears in a reduction clause of a teams construct
13081 // must not appear in a firstprivate clause on a distribute construct if
13082 // any of the distribute regions arising from the distribute construct
13083 // ever bind to any of the teams regions arising from the teams construct.
13084 if ((isOpenMPWorksharingDirective(CurrDir) ||
13085 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013086 !isOpenMPParallelDirective(CurrDir) &&
13087 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000013088 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013089 if (DVar.CKind != OMPC_shared &&
13090 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013091 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013092 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000013093 Diag(ELoc, diag::err_omp_required_access)
13094 << getOpenMPClauseName(OMPC_firstprivate)
13095 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013096 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013097 continue;
13098 }
13099 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013100 // OpenMP [2.9.3.4, Restrictions, p.3]
13101 // A list item that appears in a reduction clause of a parallel construct
13102 // must not appear in a firstprivate clause on a worksharing or task
13103 // construct if any of the worksharing or task regions arising from the
13104 // worksharing or task construct ever bind to any of the parallel regions
13105 // arising from the parallel construct.
13106 // OpenMP [2.9.3.4, Restrictions, p.4]
13107 // A list item that appears in a reduction clause in worksharing
13108 // construct must not appear in a firstprivate clause in a task construct
13109 // encountered during execution of any of the worksharing regions arising
13110 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000013111 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013112 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013113 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
13114 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013115 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013116 isOpenMPWorksharingDirective(K) ||
13117 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013118 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013119 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013120 if (DVar.CKind == OMPC_reduction &&
13121 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013122 isOpenMPWorksharingDirective(DVar.DKind) ||
13123 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013124 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
13125 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013126 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000013127 continue;
13128 }
13129 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000013130
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013131 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13132 // A list item cannot appear in both a map clause and a data-sharing
13133 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000013134 //
13135 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
13136 // A list item cannot appear in both a map clause and a data-sharing
13137 // attribute clause on the same construct unless the construct is a
13138 // combined construct.
13139 if ((LangOpts.OpenMP <= 45 &&
13140 isOpenMPTargetExecutionDirective(CurrDir)) ||
13141 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000013142 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000013143 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013144 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000013145 [&ConflictKind](
13146 OMPClauseMappableExprCommon::MappableExprComponentListRef,
13147 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000013148 ConflictKind = WhereFoundClauseKind;
13149 return true;
13150 })) {
13151 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013152 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000013153 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013154 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013155 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013156 continue;
13157 }
13158 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013159 }
13160
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013161 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000013162 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000013163 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013164 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
13165 << getOpenMPClauseName(OMPC_firstprivate) << Type
13166 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13167 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000013168 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013169 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000013170 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013171 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000013172 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013173 continue;
13174 }
13175
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013176 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013177 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013178 buildVarDecl(*this, ELoc, Type, D->getName(),
13179 D->hasAttrs() ? &D->getAttrs() : nullptr,
13180 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013181 // Generate helper private variable and initialize it with the value of the
13182 // original variable. The address of the original variable is replaced by
13183 // the address of the new private variable in the CodeGen. This new variable
13184 // is not added to IdResolver, so the code in the OpenMP region uses
13185 // original variable for proper diagnostics and variable capturing.
13186 Expr *VDInitRefExpr = nullptr;
13187 // For arrays generate initializer for single element and replace it by the
13188 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013189 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013190 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000013191 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013192 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013193 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013194 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013195 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
13196 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000013197 InitializedEntity Entity =
13198 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013199 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
13200
13201 InitializationSequence InitSeq(*this, Entity, Kind, Init);
13202 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
13203 if (Result.isInvalid())
13204 VDPrivate->setInvalidDecl();
13205 else
13206 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013207 // Remove temp variable declaration.
13208 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013209 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000013210 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
13211 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000013212 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13213 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000013214 AddInitializerToDecl(VDPrivate,
13215 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013216 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013217 }
13218 if (VDPrivate->isInvalidDecl()) {
13219 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000013220 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013221 diag::note_omp_task_predetermined_firstprivate_here);
13222 }
13223 continue;
13224 }
13225 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013226 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000013227 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
13228 RefExpr->getExprLoc());
13229 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013230 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013231 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013232 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013233 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013234 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013235 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013236 ExprCaptures.push_back(Ref->getDecl());
13237 }
Alexey Bataev417089f2016-02-17 13:19:37 +000013238 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000013239 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013240 Vars.push_back((VD || CurContext->isDependentContext())
13241 ? RefExpr->IgnoreParens()
13242 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013243 PrivateCopies.push_back(VDPrivateRefExpr);
13244 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013245 }
13246
Alexey Bataeved09d242014-05-28 05:53:51 +000013247 if (Vars.empty())
13248 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013249
13250 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013251 Vars, PrivateCopies, Inits,
13252 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013253}
13254
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013255OMPClause *Sema::ActOnOpenMPLastprivateClause(
13256 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
13257 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
13258 SourceLocation LParenLoc, SourceLocation EndLoc) {
13259 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
13260 assert(ColonLoc.isValid() && "Colon location must be valid.");
13261 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
13262 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
13263 /*Last=*/OMPC_LASTPRIVATE_unknown)
13264 << getOpenMPClauseName(OMPC_lastprivate);
13265 return nullptr;
13266 }
13267
Alexander Musman1bb328c2014-06-04 13:06:39 +000013268 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000013269 SmallVector<Expr *, 8> SrcExprs;
13270 SmallVector<Expr *, 8> DstExprs;
13271 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000013272 SmallVector<Decl *, 4> ExprCaptures;
13273 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000013274 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013275 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013276 SourceLocation ELoc;
13277 SourceRange ERange;
13278 Expr *SimpleRefExpr = RefExpr;
13279 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000013280 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013281 // It will be analyzed later.
13282 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013283 SrcExprs.push_back(nullptr);
13284 DstExprs.push_back(nullptr);
13285 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013286 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013287 ValueDecl *D = Res.first;
13288 if (!D)
13289 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013290
Alexey Bataev74caaf22016-02-20 04:09:36 +000013291 QualType Type = D->getType();
13292 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013293
13294 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
13295 // A variable that appears in a lastprivate clause must not have an
13296 // incomplete type or a reference type.
13297 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000013298 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000013299 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013300 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013301
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013302 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13303 // A variable that is privatized must not have a const-qualified type
13304 // unless it is of class type with a mutable member. This restriction does
13305 // not apply to the firstprivate clause.
13306 //
13307 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
13308 // A variable that appears in a lastprivate clause must not have a
13309 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013310 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013311 continue;
13312
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013313 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
13314 // A list item that appears in a lastprivate clause with the conditional
13315 // modifier must be a scalar variable.
13316 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
13317 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
13318 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13319 VarDecl::DeclarationOnly;
13320 Diag(D->getLocation(),
13321 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13322 << D;
13323 continue;
13324 }
13325
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013326 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013327 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13328 // in a Construct]
13329 // Variables with the predetermined data-sharing attributes may not be
13330 // listed in data-sharing attributes clauses, except for the cases
13331 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013332 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13333 // A list item may appear in a firstprivate or lastprivate clause but not
13334 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000013335 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013336 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000013337 (isOpenMPDistributeDirective(CurrDir) ||
13338 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000013339 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
13340 Diag(ELoc, diag::err_omp_wrong_dsa)
13341 << getOpenMPClauseName(DVar.CKind)
13342 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013343 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013344 continue;
13345 }
13346
Alexey Bataevf29276e2014-06-18 04:14:57 +000013347 // OpenMP [2.14.3.5, Restrictions, p.2]
13348 // A list item that is private within a parallel region, or that appears in
13349 // the reduction clause of a parallel construct, must not appear in a
13350 // lastprivate clause on a worksharing construct if any of the corresponding
13351 // worksharing regions ever binds to any of the corresponding parallel
13352 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000013353 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000013354 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013355 !isOpenMPParallelDirective(CurrDir) &&
13356 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000013357 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013358 if (DVar.CKind != OMPC_shared) {
13359 Diag(ELoc, diag::err_omp_required_access)
13360 << getOpenMPClauseName(OMPC_lastprivate)
13361 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013362 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013363 continue;
13364 }
13365 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013366
Alexander Musman1bb328c2014-06-04 13:06:39 +000013367 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000013368 // A variable of class type (or array thereof) that appears in a
13369 // lastprivate clause requires an accessible, unambiguous default
13370 // constructor for the class type, unless the list item is also specified
13371 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000013372 // A variable of class type (or array thereof) that appears in a
13373 // lastprivate clause requires an accessible, unambiguous copy assignment
13374 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000013375 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013376 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
13377 Type.getUnqualifiedType(), ".lastprivate.src",
13378 D->hasAttrs() ? &D->getAttrs() : nullptr);
13379 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000013380 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013381 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013382 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000013383 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013384 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000013385 // For arrays generate assignment operation for single element and replace
13386 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013387 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
13388 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013389 if (AssignmentOp.isInvalid())
13390 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013391 AssignmentOp =
13392 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000013393 if (AssignmentOp.isInvalid())
13394 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013395
Alexey Bataev74caaf22016-02-20 04:09:36 +000013396 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013397 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013398 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013399 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013400 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013401 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013402 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013403 ExprCaptures.push_back(Ref->getDecl());
13404 }
13405 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013406 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013407 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013408 ExprResult RefRes = DefaultLvalueConversion(Ref);
13409 if (!RefRes.isUsable())
13410 continue;
13411 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013412 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13413 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013414 if (!PostUpdateRes.isUsable())
13415 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013416 ExprPostUpdates.push_back(
13417 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013418 }
13419 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013420 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013421 Vars.push_back((VD || CurContext->isDependentContext())
13422 ? RefExpr->IgnoreParens()
13423 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000013424 SrcExprs.push_back(PseudoSrcExpr);
13425 DstExprs.push_back(PseudoDstExpr);
13426 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000013427 }
13428
13429 if (Vars.empty())
13430 return nullptr;
13431
13432 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000013433 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013434 LPKind, LPKindLoc, ColonLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013435 buildPreInits(Context, ExprCaptures),
13436 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000013437}
13438
Alexey Bataev758e55e2013-09-06 18:03:48 +000013439OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
13440 SourceLocation StartLoc,
13441 SourceLocation LParenLoc,
13442 SourceLocation EndLoc) {
13443 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013444 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013445 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013446 SourceLocation ELoc;
13447 SourceRange ERange;
13448 Expr *SimpleRefExpr = RefExpr;
13449 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013450 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000013451 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013452 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013453 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013454 ValueDecl *D = Res.first;
13455 if (!D)
13456 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013457
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013458 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013459 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13460 // in a Construct]
13461 // Variables with the predetermined data-sharing attributes may not be
13462 // listed in data-sharing attributes clauses, except for the cases
13463 // listed below. For these exceptions only, listing a predetermined
13464 // variable in a data-sharing attribute clause is allowed and overrides
13465 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000013466 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000013467 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
13468 DVar.RefExpr) {
13469 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13470 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013471 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013472 continue;
13473 }
13474
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013475 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013476 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000013477 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013478 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013479 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
13480 ? RefExpr->IgnoreParens()
13481 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013482 }
13483
Alexey Bataeved09d242014-05-28 05:53:51 +000013484 if (Vars.empty())
13485 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013486
13487 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13488}
13489
Alexey Bataevc5e02582014-06-16 07:08:35 +000013490namespace {
13491class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13492 DSAStackTy *Stack;
13493
13494public:
13495 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013496 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13497 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013498 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13499 return false;
13500 if (DVar.CKind != OMPC_unknown)
13501 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013502 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013503 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013504 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013505 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013506 }
13507 return false;
13508 }
13509 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013510 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013511 if (Child && Visit(Child))
13512 return true;
13513 }
13514 return false;
13515 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013516 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013517};
Alexey Bataev23b69422014-06-18 07:08:49 +000013518} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013519
Alexey Bataev60da77e2016-02-29 05:54:20 +000013520namespace {
13521// Transform MemberExpression for specified FieldDecl of current class to
13522// DeclRefExpr to specified OMPCapturedExprDecl.
13523class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13524 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013525 ValueDecl *Field = nullptr;
13526 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013527
13528public:
13529 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13530 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13531
13532 ExprResult TransformMemberExpr(MemberExpr *E) {
13533 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13534 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013535 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013536 return CapturedExpr;
13537 }
13538 return BaseTransform::TransformMemberExpr(E);
13539 }
13540 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13541};
13542} // namespace
13543
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013544template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013545static T filterLookupForUDReductionAndMapper(
13546 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013547 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013548 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013549 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013550 return Res;
13551 }
13552 }
13553 return T();
13554}
13555
Alexey Bataev43b90b72018-09-12 16:31:59 +000013556static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13557 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13558
13559 for (auto RD : D->redecls()) {
13560 // Don't bother with extra checks if we already know this one isn't visible.
13561 if (RD == D)
13562 continue;
13563
13564 auto ND = cast<NamedDecl>(RD);
13565 if (LookupResult::isVisible(SemaRef, ND))
13566 return ND;
13567 }
13568
13569 return nullptr;
13570}
13571
13572static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013573argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013574 SourceLocation Loc, QualType Ty,
13575 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13576 // Find all of the associated namespaces and classes based on the
13577 // arguments we have.
13578 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13579 Sema::AssociatedClassSet AssociatedClasses;
13580 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13581 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13582 AssociatedClasses);
13583
13584 // C++ [basic.lookup.argdep]p3:
13585 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13586 // and let Y be the lookup set produced by argument dependent
13587 // lookup (defined as follows). If X contains [...] then Y is
13588 // empty. Otherwise Y is the set of declarations found in the
13589 // namespaces associated with the argument types as described
13590 // below. The set of declarations found by the lookup of the name
13591 // is the union of X and Y.
13592 //
13593 // Here, we compute Y and add its members to the overloaded
13594 // candidate set.
13595 for (auto *NS : AssociatedNamespaces) {
13596 // When considering an associated namespace, the lookup is the
13597 // same as the lookup performed when the associated namespace is
13598 // used as a qualifier (3.4.3.2) except that:
13599 //
13600 // -- Any using-directives in the associated namespace are
13601 // ignored.
13602 //
13603 // -- Any namespace-scope friend functions declared in
13604 // associated classes are visible within their respective
13605 // namespaces even if they are not visible during an ordinary
13606 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013607 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013608 for (auto *D : R) {
13609 auto *Underlying = D;
13610 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13611 Underlying = USD->getTargetDecl();
13612
Michael Kruse4304e9d2019-02-19 16:38:20 +000013613 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13614 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013615 continue;
13616
13617 if (!SemaRef.isVisible(D)) {
13618 D = findAcceptableDecl(SemaRef, D);
13619 if (!D)
13620 continue;
13621 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13622 Underlying = USD->getTargetDecl();
13623 }
13624 Lookups.emplace_back();
13625 Lookups.back().addDecl(Underlying);
13626 }
13627 }
13628}
13629
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013630static ExprResult
13631buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13632 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13633 const DeclarationNameInfo &ReductionId, QualType Ty,
13634 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13635 if (ReductionIdScopeSpec.isInvalid())
13636 return ExprError();
13637 SmallVector<UnresolvedSet<8>, 4> Lookups;
13638 if (S) {
13639 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13640 Lookup.suppressDiagnostics();
13641 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013642 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013643 do {
13644 S = S->getParent();
13645 } while (S && !S->isDeclScope(D));
13646 if (S)
13647 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013648 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013649 Lookups.back().append(Lookup.begin(), Lookup.end());
13650 Lookup.clear();
13651 }
13652 } else if (auto *ULE =
13653 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13654 Lookups.push_back(UnresolvedSet<8>());
13655 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013656 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013657 if (D == PrevD)
13658 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013659 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013660 Lookups.back().addDecl(DRD);
13661 PrevD = D;
13662 }
13663 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013664 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13665 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013666 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013667 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013668 return !D->isInvalidDecl() &&
13669 (D->getType()->isDependentType() ||
13670 D->getType()->isInstantiationDependentType() ||
13671 D->getType()->containsUnexpandedParameterPack());
13672 })) {
13673 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013674 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013675 if (Set.empty())
13676 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013677 ResSet.append(Set.begin(), Set.end());
13678 // The last item marks the end of all declarations at the specified scope.
13679 ResSet.addDecl(Set[Set.size() - 1]);
13680 }
13681 return UnresolvedLookupExpr::Create(
13682 SemaRef.Context, /*NamingClass=*/nullptr,
13683 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13684 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13685 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013686 // Lookup inside the classes.
13687 // C++ [over.match.oper]p3:
13688 // For a unary operator @ with an operand of a type whose
13689 // cv-unqualified version is T1, and for a binary operator @ with
13690 // a left operand of a type whose cv-unqualified version is T1 and
13691 // a right operand of a type whose cv-unqualified version is T2,
13692 // three sets of candidate functions, designated member
13693 // candidates, non-member candidates and built-in candidates, are
13694 // constructed as follows:
13695 // -- If T1 is a complete class type or a class currently being
13696 // defined, the set of member candidates is the result of the
13697 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13698 // the set of member candidates is empty.
13699 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13700 Lookup.suppressDiagnostics();
13701 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13702 // Complete the type if it can be completed.
13703 // If the type is neither complete nor being defined, bail out now.
13704 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13705 TyRec->getDecl()->getDefinition()) {
13706 Lookup.clear();
13707 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13708 if (Lookup.empty()) {
13709 Lookups.emplace_back();
13710 Lookups.back().append(Lookup.begin(), Lookup.end());
13711 }
13712 }
13713 }
13714 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013715 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013716 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013717 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13718 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13719 if (!D->isInvalidDecl() &&
13720 SemaRef.Context.hasSameType(D->getType(), Ty))
13721 return D;
13722 return nullptr;
13723 }))
13724 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13725 VK_LValue, Loc);
13726 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013727 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13728 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13729 if (!D->isInvalidDecl() &&
13730 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13731 !Ty.isMoreQualifiedThan(D->getType()))
13732 return D;
13733 return nullptr;
13734 })) {
13735 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13736 /*DetectVirtual=*/false);
13737 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13738 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13739 VD->getType().getUnqualifiedType()))) {
13740 if (SemaRef.CheckBaseClassAccess(
13741 Loc, VD->getType(), Ty, Paths.front(),
13742 /*DiagID=*/0) != Sema::AR_inaccessible) {
13743 SemaRef.BuildBasePathArray(Paths, BasePath);
13744 return SemaRef.BuildDeclRefExpr(
13745 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13746 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013747 }
13748 }
13749 }
13750 }
13751 if (ReductionIdScopeSpec.isSet()) {
Alexey Bataevadd743b2020-01-03 11:58:16 -050013752 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
13753 << Ty << Range;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013754 return ExprError();
13755 }
13756 return ExprEmpty();
13757}
13758
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013759namespace {
13760/// Data for the reduction-based clauses.
13761struct ReductionData {
13762 /// List of original reduction items.
13763 SmallVector<Expr *, 8> Vars;
13764 /// List of private copies of the reduction items.
13765 SmallVector<Expr *, 8> Privates;
13766 /// LHS expressions for the reduction_op expressions.
13767 SmallVector<Expr *, 8> LHSs;
13768 /// RHS expressions for the reduction_op expressions.
13769 SmallVector<Expr *, 8> RHSs;
13770 /// Reduction operation expression.
13771 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013772 /// Taskgroup descriptors for the corresponding reduction items in
13773 /// in_reduction clauses.
13774 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013775 /// List of captures for clause.
13776 SmallVector<Decl *, 4> ExprCaptures;
13777 /// List of postupdate expressions.
13778 SmallVector<Expr *, 4> ExprPostUpdates;
13779 ReductionData() = delete;
13780 /// Reserves required memory for the reduction data.
13781 ReductionData(unsigned Size) {
13782 Vars.reserve(Size);
13783 Privates.reserve(Size);
13784 LHSs.reserve(Size);
13785 RHSs.reserve(Size);
13786 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013787 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013788 ExprCaptures.reserve(Size);
13789 ExprPostUpdates.reserve(Size);
13790 }
13791 /// Stores reduction item and reduction operation only (required for dependent
13792 /// reduction item).
13793 void push(Expr *Item, Expr *ReductionOp) {
13794 Vars.emplace_back(Item);
13795 Privates.emplace_back(nullptr);
13796 LHSs.emplace_back(nullptr);
13797 RHSs.emplace_back(nullptr);
13798 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013799 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013800 }
13801 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013802 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13803 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013804 Vars.emplace_back(Item);
13805 Privates.emplace_back(Private);
13806 LHSs.emplace_back(LHS);
13807 RHSs.emplace_back(RHS);
13808 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013809 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013810 }
13811};
13812} // namespace
13813
Alexey Bataeve3727102018-04-18 15:57:46 +000013814static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013815 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13816 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13817 const Expr *Length = OASE->getLength();
13818 if (Length == nullptr) {
13819 // For array sections of the form [1:] or [:], we would need to analyze
13820 // the lower bound...
13821 if (OASE->getColonLoc().isValid())
13822 return false;
13823
13824 // This is an array subscript which has implicit length 1!
13825 SingleElement = true;
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))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013830 return false;
13831
Fangrui Song407659a2018-11-30 23:41:18 +000013832 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013833 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13834 ArraySizes.push_back(ConstantLengthValue);
13835 }
13836
13837 // Get the base of this array section and walk up from there.
13838 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13839
13840 // We require length = 1 for all array sections except the right-most to
13841 // guarantee that the memory region is contiguous and has no holes in it.
13842 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13843 Length = TempOASE->getLength();
13844 if (Length == nullptr) {
13845 // For array sections of the form [1:] or [:], we would need to analyze
13846 // the lower bound...
13847 if (OASE->getColonLoc().isValid())
13848 return false;
13849
13850 // This is an array subscript which has implicit length 1!
13851 ArraySizes.push_back(llvm::APSInt::get(1));
13852 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013853 Expr::EvalResult Result;
13854 if (!Length->EvaluateAsInt(Result, Context))
13855 return false;
13856
13857 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13858 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013859 return false;
13860
13861 ArraySizes.push_back(ConstantLengthValue);
13862 }
13863 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13864 }
13865
13866 // If we have a single element, we don't need to add the implicit lengths.
13867 if (!SingleElement) {
13868 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13869 // Has implicit length 1!
13870 ArraySizes.push_back(llvm::APSInt::get(1));
13871 Base = TempASE->getBase()->IgnoreParenImpCasts();
13872 }
13873 }
13874
13875 // This array section can be privatized as a single value or as a constant
13876 // sized array.
13877 return true;
13878}
13879
Alexey Bataeve3727102018-04-18 15:57:46 +000013880static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013881 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13882 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13883 SourceLocation ColonLoc, SourceLocation EndLoc,
13884 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013885 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013886 DeclarationName DN = ReductionId.getName();
13887 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013888 BinaryOperatorKind BOK = BO_Comma;
13889
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013890 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013891 // OpenMP [2.14.3.6, reduction clause]
13892 // C
13893 // reduction-identifier is either an identifier or one of the following
13894 // operators: +, -, *, &, |, ^, && and ||
13895 // C++
13896 // reduction-identifier is either an id-expression or one of the following
13897 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013898 switch (OOK) {
13899 case OO_Plus:
13900 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013901 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013902 break;
13903 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013904 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013905 break;
13906 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013907 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013908 break;
13909 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013910 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013911 break;
13912 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013913 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013914 break;
13915 case OO_AmpAmp:
13916 BOK = BO_LAnd;
13917 break;
13918 case OO_PipePipe:
13919 BOK = BO_LOr;
13920 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013921 case OO_New:
13922 case OO_Delete:
13923 case OO_Array_New:
13924 case OO_Array_Delete:
13925 case OO_Slash:
13926 case OO_Percent:
13927 case OO_Tilde:
13928 case OO_Exclaim:
13929 case OO_Equal:
13930 case OO_Less:
13931 case OO_Greater:
13932 case OO_LessEqual:
13933 case OO_GreaterEqual:
13934 case OO_PlusEqual:
13935 case OO_MinusEqual:
13936 case OO_StarEqual:
13937 case OO_SlashEqual:
13938 case OO_PercentEqual:
13939 case OO_CaretEqual:
13940 case OO_AmpEqual:
13941 case OO_PipeEqual:
13942 case OO_LessLess:
13943 case OO_GreaterGreater:
13944 case OO_LessLessEqual:
13945 case OO_GreaterGreaterEqual:
13946 case OO_EqualEqual:
13947 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013948 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013949 case OO_PlusPlus:
13950 case OO_MinusMinus:
13951 case OO_Comma:
13952 case OO_ArrowStar:
13953 case OO_Arrow:
13954 case OO_Call:
13955 case OO_Subscript:
13956 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013957 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013958 case NUM_OVERLOADED_OPERATORS:
13959 llvm_unreachable("Unexpected reduction identifier");
13960 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013961 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013962 if (II->isStr("max"))
13963 BOK = BO_GT;
13964 else if (II->isStr("min"))
13965 BOK = BO_LT;
13966 }
13967 break;
13968 }
13969 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013970 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013971 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013972 else
13973 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013974 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013975
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013976 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13977 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013978 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013979 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013980 // OpenMP [2.1, C/C++]
13981 // A list item is a variable or array section, subject to the restrictions
13982 // specified in Section 2.4 on page 42 and in each of the sections
13983 // describing clauses and directives for which a list appears.
13984 // OpenMP [2.14.3.3, Restrictions, p.1]
13985 // A variable that is part of another variable (as an array or
13986 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013987 if (!FirstIter && IR != ER)
13988 ++IR;
13989 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013990 SourceLocation ELoc;
13991 SourceRange ERange;
13992 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013993 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013994 /*AllowArraySection=*/true);
13995 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013996 // Try to find 'declare reduction' corresponding construct before using
13997 // builtin/overloaded operators.
13998 QualType Type = Context.DependentTy;
13999 CXXCastPath BasePath;
14000 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014001 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014002 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014003 Expr *ReductionOp = nullptr;
14004 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014005 (DeclareReductionRef.isUnset() ||
14006 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014007 ReductionOp = DeclareReductionRef.get();
14008 // It will be analyzed later.
14009 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014010 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014011 ValueDecl *D = Res.first;
14012 if (!D)
14013 continue;
14014
Alexey Bataev88202be2017-07-27 13:20:36 +000014015 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000014016 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000014017 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
14018 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000014019 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000014020 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014021 } else if (OASE) {
14022 QualType BaseType =
14023 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
14024 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000014025 Type = ATy->getElementType();
14026 else
14027 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000014028 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014029 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014030 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000014031 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014032 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000014033
Alexey Bataevc5e02582014-06-16 07:08:35 +000014034 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
14035 // A variable that appears in a private clause must not have an incomplete
14036 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000014037 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014038 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014039 continue;
14040 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000014041 // A list item that appears in a reduction clause must not be
14042 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000014043 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
14044 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014045 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000014046
14047 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000014048 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
14049 // If a list-item is a reference type then it must bind to the same object
14050 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000014051 if (!ASE && !OASE) {
14052 if (VD) {
14053 VarDecl *VDDef = VD->getDefinition();
14054 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
14055 DSARefChecker Check(Stack);
14056 if (Check.Visit(VDDef->getInit())) {
14057 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
14058 << getOpenMPClauseName(ClauseKind) << ERange;
14059 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
14060 continue;
14061 }
Alexey Bataeva1764212015-09-30 09:22:36 +000014062 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000014063 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014064
Alexey Bataevbc529672018-09-28 19:33:14 +000014065 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
14066 // in a Construct]
14067 // Variables with the predetermined data-sharing attributes may not be
14068 // listed in data-sharing attributes clauses, except for the cases
14069 // listed below. For these exceptions only, listing a predetermined
14070 // variable in a data-sharing attribute clause is allowed and overrides
14071 // the variable's predetermined data-sharing attributes.
14072 // OpenMP [2.14.3.6, Restrictions, p.3]
14073 // Any number of reduction clauses can be specified on the directive,
14074 // but a list item can appear only once in the reduction clauses for that
14075 // directive.
14076 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
14077 if (DVar.CKind == OMPC_reduction) {
14078 S.Diag(ELoc, diag::err_omp_once_referenced)
14079 << getOpenMPClauseName(ClauseKind);
14080 if (DVar.RefExpr)
14081 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
14082 continue;
14083 }
14084 if (DVar.CKind != OMPC_unknown) {
14085 S.Diag(ELoc, diag::err_omp_wrong_dsa)
14086 << getOpenMPClauseName(DVar.CKind)
14087 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000014088 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014089 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000014090 }
Alexey Bataevbc529672018-09-28 19:33:14 +000014091
14092 // OpenMP [2.14.3.6, Restrictions, p.1]
14093 // A list item that appears in a reduction clause of a worksharing
14094 // construct must be shared in the parallel regions to which any of the
14095 // worksharing regions arising from the worksharing construct bind.
14096 if (isOpenMPWorksharingDirective(CurrDir) &&
14097 !isOpenMPParallelDirective(CurrDir) &&
14098 !isOpenMPTeamsDirective(CurrDir)) {
14099 DVar = Stack->getImplicitDSA(D, true);
14100 if (DVar.CKind != OMPC_shared) {
14101 S.Diag(ELoc, diag::err_omp_required_access)
14102 << getOpenMPClauseName(OMPC_reduction)
14103 << getOpenMPClauseName(OMPC_shared);
14104 reportOriginalDsa(S, Stack, D, DVar);
14105 continue;
14106 }
14107 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000014108 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014109
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014110 // Try to find 'declare reduction' corresponding construct before using
14111 // builtin/overloaded operators.
14112 CXXCastPath BasePath;
14113 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014114 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014115 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
14116 if (DeclareReductionRef.isInvalid())
14117 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014118 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014119 (DeclareReductionRef.isUnset() ||
14120 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014121 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014122 continue;
14123 }
14124 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
14125 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014126 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014127 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014128 << Type << ReductionIdRange;
14129 continue;
14130 }
14131
14132 // OpenMP [2.14.3.6, reduction clause, Restrictions]
14133 // The type of a list item that appears in a reduction clause must be valid
14134 // for the reduction-identifier. For a max or min reduction in C, the type
14135 // of the list item must be an allowed arithmetic data type: char, int,
14136 // float, double, or _Bool, possibly modified with long, short, signed, or
14137 // unsigned. For a max or min reduction in C++, the type of the list item
14138 // must be an allowed arithmetic data type: char, wchar_t, int, float,
14139 // double, or bool, possibly modified with long, short, signed, or unsigned.
14140 if (DeclareReductionRef.isUnset()) {
14141 if ((BOK == BO_GT || BOK == BO_LT) &&
14142 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014143 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
14144 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000014145 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014146 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014147 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14148 VarDecl::DeclarationOnly;
14149 S.Diag(D->getLocation(),
14150 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014151 << D;
14152 }
14153 continue;
14154 }
14155 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014156 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000014157 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
14158 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014159 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014160 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14161 VarDecl::DeclarationOnly;
14162 S.Diag(D->getLocation(),
14163 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014164 << D;
14165 }
14166 continue;
14167 }
14168 }
14169
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014170 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014171 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
14172 D->hasAttrs() ? &D->getAttrs() : nullptr);
14173 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
14174 D->hasAttrs() ? &D->getAttrs() : nullptr);
14175 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000014176
14177 // Try if we can determine constant lengths for all array sections and avoid
14178 // the VLA.
14179 bool ConstantLengthOASE = false;
14180 if (OASE) {
14181 bool SingleElement;
14182 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000014183 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000014184 Context, OASE, SingleElement, ArraySizes);
14185
14186 // If we don't have a single element, we must emit a constant array type.
14187 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014188 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000014189 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
14190 ArrayType::Normal,
14191 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000014192 }
14193 }
14194
14195 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000014196 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000014197 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000014198 if (!Context.getTargetInfo().isVLASupported()) {
14199 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
14200 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
14201 S.Diag(ELoc, diag::note_vla_unsupported);
14202 } else {
14203 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
14204 S.targetDiag(ELoc, diag::note_vla_unsupported);
14205 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000014206 continue;
14207 }
David Majnemer9d168222016-08-05 17:44:54 +000014208 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014209 // Create pseudo array type for private copy. The size for this array will
14210 // be generated during codegen.
14211 // For array subscripts or single variables Private Ty is the same as Type
14212 // (type of the variable or single array element).
14213 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014214 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000014215 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014216 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000014217 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000014218 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014219 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014220 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014221 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014222 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014223 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
14224 D->hasAttrs() ? &D->getAttrs() : nullptr,
14225 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014226 // Add initializer for private variable.
14227 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014228 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
14229 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014230 if (DeclareReductionRef.isUsable()) {
14231 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
14232 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
14233 if (DRD->getInitializer()) {
14234 Init = DRDRef;
14235 RHSVD->setInit(DRDRef);
14236 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014237 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014238 } else {
14239 switch (BOK) {
14240 case BO_Add:
14241 case BO_Xor:
14242 case BO_Or:
14243 case BO_LOr:
14244 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
14245 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014246 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014247 break;
14248 case BO_Mul:
14249 case BO_LAnd:
14250 if (Type->isScalarType() || Type->isAnyComplexType()) {
14251 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014252 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000014253 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014254 break;
14255 case BO_And: {
14256 // '&' reduction op - initializer is '~0'.
14257 QualType OrigType = Type;
14258 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
14259 Type = ComplexTy->getElementType();
14260 if (Type->isRealFloatingType()) {
14261 llvm::APFloat InitValue =
14262 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
14263 /*isIEEE=*/true);
14264 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14265 Type, ELoc);
14266 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014267 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014268 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
14269 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
14270 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14271 }
14272 if (Init && OrigType->isAnyComplexType()) {
14273 // Init = 0xFFFF + 0xFFFFi;
14274 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014275 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014276 }
14277 Type = OrigType;
14278 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014279 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014280 case BO_LT:
14281 case BO_GT: {
14282 // 'min' reduction op - initializer is 'Largest representable number in
14283 // the reduction list item type'.
14284 // 'max' reduction op - initializer is 'Least representable number in
14285 // the reduction list item type'.
14286 if (Type->isIntegerType() || Type->isPointerType()) {
14287 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014288 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014289 QualType IntTy =
14290 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
14291 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014292 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
14293 : llvm::APInt::getMinValue(Size)
14294 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
14295 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014296 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14297 if (Type->isPointerType()) {
14298 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014299 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000014300 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014301 if (CastExpr.isInvalid())
14302 continue;
14303 Init = CastExpr.get();
14304 }
14305 } else if (Type->isRealFloatingType()) {
14306 llvm::APFloat InitValue = llvm::APFloat::getLargest(
14307 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
14308 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14309 Type, ELoc);
14310 }
14311 break;
14312 }
14313 case BO_PtrMemD:
14314 case BO_PtrMemI:
14315 case BO_MulAssign:
14316 case BO_Div:
14317 case BO_Rem:
14318 case BO_Sub:
14319 case BO_Shl:
14320 case BO_Shr:
14321 case BO_LE:
14322 case BO_GE:
14323 case BO_EQ:
14324 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000014325 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014326 case BO_AndAssign:
14327 case BO_XorAssign:
14328 case BO_OrAssign:
14329 case BO_Assign:
14330 case BO_AddAssign:
14331 case BO_SubAssign:
14332 case BO_DivAssign:
14333 case BO_RemAssign:
14334 case BO_ShlAssign:
14335 case BO_ShrAssign:
14336 case BO_Comma:
14337 llvm_unreachable("Unexpected reduction operation");
14338 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014339 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014340 if (Init && DeclareReductionRef.isUnset())
14341 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
14342 else if (!Init)
14343 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014344 if (RHSVD->isInvalidDecl())
14345 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000014346 if (!RHSVD->hasInit() &&
14347 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014348 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
14349 << Type << ReductionIdRange;
14350 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14351 VarDecl::DeclarationOnly;
14352 S.Diag(D->getLocation(),
14353 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000014354 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014355 continue;
14356 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014357 // Store initializer for single element in private copy. Will be used during
14358 // codegen.
14359 PrivateVD->setInit(RHSVD->getInit());
14360 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000014361 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014362 ExprResult ReductionOp;
14363 if (DeclareReductionRef.isUsable()) {
14364 QualType RedTy = DeclareReductionRef.get()->getType();
14365 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014366 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
14367 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014368 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014369 LHS = S.DefaultLvalueConversion(LHS.get());
14370 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014371 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14372 CK_UncheckedDerivedToBase, LHS.get(),
14373 &BasePath, LHS.get()->getValueKind());
14374 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14375 CK_UncheckedDerivedToBase, RHS.get(),
14376 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014377 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014378 FunctionProtoType::ExtProtoInfo EPI;
14379 QualType Params[] = {PtrRedTy, PtrRedTy};
14380 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
14381 auto *OVE = new (Context) OpaqueValueExpr(
14382 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014383 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014384 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000014385 ReductionOp =
14386 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014387 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014388 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014389 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014390 if (ReductionOp.isUsable()) {
14391 if (BOK != BO_LT && BOK != BO_GT) {
14392 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014393 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014394 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014395 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000014396 auto *ConditionalOp = new (Context)
14397 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
14398 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014399 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014400 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014401 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014402 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014403 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014404 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
14405 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014406 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014407 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014408 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000014409 }
14410
Alexey Bataevfa312f32017-07-21 18:48:21 +000014411 // OpenMP [2.15.4.6, Restrictions, p.2]
14412 // A list item that appears in an in_reduction clause of a task construct
14413 // must appear in a task_reduction clause of a construct associated with a
14414 // taskgroup region that includes the participating task in its taskgroup
14415 // set. The construct associated with the innermost region that meets this
14416 // condition must specify the same reduction-identifier as the in_reduction
14417 // clause.
14418 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000014419 SourceRange ParentSR;
14420 BinaryOperatorKind ParentBOK;
14421 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000014422 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000014423 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014424 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
14425 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014426 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014427 Stack->getTopMostTaskgroupReductionData(
14428 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014429 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
14430 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
14431 if (!IsParentBOK && !IsParentReductionOp) {
14432 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
14433 continue;
14434 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000014435 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
14436 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
14437 IsParentReductionOp) {
14438 bool EmitError = true;
14439 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
14440 llvm::FoldingSetNodeID RedId, ParentRedId;
14441 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
14442 DeclareReductionRef.get()->Profile(RedId, Context,
14443 /*Canonical=*/true);
14444 EmitError = RedId != ParentRedId;
14445 }
14446 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014447 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000014448 diag::err_omp_reduction_identifier_mismatch)
14449 << ReductionIdRange << RefExpr->getSourceRange();
14450 S.Diag(ParentSR.getBegin(),
14451 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000014452 << ParentSR
14453 << (IsParentBOK ? ParentBOKDSA.RefExpr
14454 : ParentReductionOpDSA.RefExpr)
14455 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000014456 continue;
14457 }
14458 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014459 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
14460 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000014461 }
14462
Alexey Bataev60da77e2016-02-29 05:54:20 +000014463 DeclRefExpr *Ref = nullptr;
14464 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014465 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014466 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014467 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000014468 VarsExpr =
14469 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
14470 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000014471 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014472 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014473 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014474 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014475 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014476 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014477 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014478 if (!RefRes.isUsable())
14479 continue;
14480 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014481 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14482 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014483 if (!PostUpdateRes.isUsable())
14484 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014485 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14486 Stack->getCurrentDirective() == OMPD_taskgroup) {
14487 S.Diag(RefExpr->getExprLoc(),
14488 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014489 << RefExpr->getSourceRange();
14490 continue;
14491 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014492 RD.ExprPostUpdates.emplace_back(
14493 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014494 }
14495 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014496 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014497 // All reduction items are still marked as reduction (to do not increase
14498 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014499 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014500 if (CurrDir == OMPD_taskgroup) {
14501 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014502 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14503 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014504 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014505 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014506 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014507 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14508 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014509 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014510 return RD.Vars.empty();
14511}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014512
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014513OMPClause *Sema::ActOnOpenMPReductionClause(
14514 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14515 SourceLocation ColonLoc, SourceLocation EndLoc,
14516 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14517 ArrayRef<Expr *> UnresolvedReductions) {
14518 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014519 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014520 StartLoc, LParenLoc, ColonLoc, EndLoc,
14521 ReductionIdScopeSpec, ReductionId,
14522 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014523 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014524
Alexey Bataevc5e02582014-06-16 07:08:35 +000014525 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014526 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14527 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14528 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14529 buildPreInits(Context, RD.ExprCaptures),
14530 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014531}
14532
Alexey Bataev169d96a2017-07-18 20:17:46 +000014533OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14534 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14535 SourceLocation ColonLoc, SourceLocation EndLoc,
14536 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14537 ArrayRef<Expr *> UnresolvedReductions) {
14538 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014539 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14540 StartLoc, LParenLoc, ColonLoc, EndLoc,
14541 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014542 UnresolvedReductions, RD))
14543 return nullptr;
14544
14545 return OMPTaskReductionClause::Create(
14546 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14547 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14548 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14549 buildPreInits(Context, RD.ExprCaptures),
14550 buildPostUpdate(*this, RD.ExprPostUpdates));
14551}
14552
Alexey Bataevfa312f32017-07-21 18:48:21 +000014553OMPClause *Sema::ActOnOpenMPInReductionClause(
14554 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14555 SourceLocation ColonLoc, SourceLocation EndLoc,
14556 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14557 ArrayRef<Expr *> UnresolvedReductions) {
14558 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014559 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014560 StartLoc, LParenLoc, ColonLoc, EndLoc,
14561 ReductionIdScopeSpec, ReductionId,
14562 UnresolvedReductions, RD))
14563 return nullptr;
14564
14565 return OMPInReductionClause::Create(
14566 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14567 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014568 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014569 buildPreInits(Context, RD.ExprCaptures),
14570 buildPostUpdate(*this, RD.ExprPostUpdates));
14571}
14572
Alexey Bataevecba70f2016-04-12 11:02:11 +000014573bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14574 SourceLocation LinLoc) {
14575 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14576 LinKind == OMPC_LINEAR_unknown) {
14577 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14578 return true;
14579 }
14580 return false;
14581}
14582
Alexey Bataeve3727102018-04-18 15:57:46 +000014583bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014584 OpenMPLinearClauseKind LinKind,
14585 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014586 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014587 // A variable must not have an incomplete type or a reference type.
14588 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14589 return true;
14590 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14591 !Type->isReferenceType()) {
14592 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14593 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14594 return true;
14595 }
14596 Type = Type.getNonReferenceType();
14597
Joel E. Dennybae586f2019-01-04 22:12:13 +000014598 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14599 // A variable that is privatized must not have a const-qualified type
14600 // unless it is of class type with a mutable member. This restriction does
14601 // not apply to the firstprivate clause.
14602 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014603 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014604
14605 // A list item must be of integral or pointer type.
14606 Type = Type.getUnqualifiedType().getCanonicalType();
14607 const auto *Ty = Type.getTypePtrOrNull();
Alexey Bataev3f2e3dc2020-01-07 09:26:10 -050014608 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
14609 !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
Alexey Bataevecba70f2016-04-12 11:02:11 +000014610 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14611 if (D) {
14612 bool IsDecl =
14613 !VD ||
14614 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14615 Diag(D->getLocation(),
14616 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14617 << D;
14618 }
14619 return true;
14620 }
14621 return false;
14622}
14623
Alexey Bataev182227b2015-08-20 10:54:39 +000014624OMPClause *Sema::ActOnOpenMPLinearClause(
14625 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14626 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14627 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014628 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014629 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014630 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014631 SmallVector<Decl *, 4> ExprCaptures;
14632 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014633 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014634 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014635 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014636 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014637 SourceLocation ELoc;
14638 SourceRange ERange;
14639 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014640 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014641 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014642 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014643 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014644 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014645 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014646 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014647 ValueDecl *D = Res.first;
14648 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014649 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014650
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014651 QualType Type = D->getType();
14652 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014653
14654 // OpenMP [2.14.3.7, linear clause]
14655 // A list-item cannot appear in more than one linear clause.
14656 // A list-item that appears in a linear clause cannot appear in any
14657 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014658 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014659 if (DVar.RefExpr) {
14660 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14661 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014662 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014663 continue;
14664 }
14665
Alexey Bataevecba70f2016-04-12 11:02:11 +000014666 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014667 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014668 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014669
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014670 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014671 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014672 buildVarDecl(*this, ELoc, Type, D->getName(),
14673 D->hasAttrs() ? &D->getAttrs() : nullptr,
14674 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014675 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014676 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014677 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014678 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014679 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014680 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014681 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014682 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014683 ExprCaptures.push_back(Ref->getDecl());
14684 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14685 ExprResult RefRes = DefaultLvalueConversion(Ref);
14686 if (!RefRes.isUsable())
14687 continue;
14688 ExprResult PostUpdateRes =
14689 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14690 SimpleRefExpr, RefRes.get());
14691 if (!PostUpdateRes.isUsable())
14692 continue;
14693 ExprPostUpdates.push_back(
14694 IgnoredValueConversions(PostUpdateRes.get()).get());
14695 }
14696 }
14697 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014698 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014699 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014700 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014701 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014702 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014703 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014704 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014705
14706 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014707 Vars.push_back((VD || CurContext->isDependentContext())
14708 ? RefExpr->IgnoreParens()
14709 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014710 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014711 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014712 }
14713
14714 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014715 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014716
14717 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014718 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014719 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14720 !Step->isInstantiationDependent() &&
14721 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014722 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014723 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014724 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014725 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014726 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014727
Alexander Musman3276a272015-03-21 10:12:56 +000014728 // Build var to save the step value.
14729 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014730 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014731 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014732 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014733 ExprResult CalcStep =
14734 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014735 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014736
Alexander Musman8dba6642014-04-22 13:09:42 +000014737 // Warn about zero linear step (it would be probably better specified as
14738 // making corresponding variables 'const').
14739 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014740 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14741 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014742 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14743 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014744 if (!IsConstant && CalcStep.isUsable()) {
14745 // Calculate the step beforehand instead of doing this on each iteration.
14746 // (This is not used if the number of iterations may be kfold-ed).
14747 CalcStepExpr = CalcStep.get();
14748 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014749 }
14750
Alexey Bataev182227b2015-08-20 10:54:39 +000014751 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14752 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014753 StepExpr, CalcStepExpr,
14754 buildPreInits(Context, ExprCaptures),
14755 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014756}
14757
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014758static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14759 Expr *NumIterations, Sema &SemaRef,
14760 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014761 // Walk the vars and build update/final expressions for the CodeGen.
14762 SmallVector<Expr *, 8> Updates;
14763 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014764 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014765 Expr *Step = Clause.getStep();
14766 Expr *CalcStep = Clause.getCalcStep();
14767 // OpenMP [2.14.3.7, linear clause]
14768 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014769 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014770 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014771 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014772 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14773 bool HasErrors = false;
14774 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014775 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014776 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14777 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014778 SourceLocation ELoc;
14779 SourceRange ERange;
14780 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014781 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014782 ValueDecl *D = Res.first;
14783 if (Res.second || !D) {
14784 Updates.push_back(nullptr);
14785 Finals.push_back(nullptr);
14786 HasErrors = true;
14787 continue;
14788 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014789 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014790 // OpenMP [2.15.11, distribute simd Construct]
14791 // A list item may not appear in a linear clause, unless it is the loop
14792 // iteration variable.
14793 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14794 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14795 SemaRef.Diag(ELoc,
14796 diag::err_omp_linear_distribute_var_non_loop_iteration);
14797 Updates.push_back(nullptr);
14798 Finals.push_back(nullptr);
14799 HasErrors = true;
14800 continue;
14801 }
Alexander Musman3276a272015-03-21 10:12:56 +000014802 Expr *InitExpr = *CurInit;
14803
14804 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014805 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014806 Expr *CapturedRef;
14807 if (LinKind == OMPC_LINEAR_uval)
14808 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14809 else
14810 CapturedRef =
14811 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14812 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14813 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014814
14815 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014816 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014817 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014818 Update = buildCounterUpdate(
14819 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14820 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014821 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014822 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014823 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014824 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014825
14826 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014827 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014828 if (!Info.first)
14829 Final =
14830 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014831 InitExpr, NumIterations, Step, /*Subtract=*/false,
14832 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014833 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014834 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014835 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014836 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014837
Alexander Musman3276a272015-03-21 10:12:56 +000014838 if (!Update.isUsable() || !Final.isUsable()) {
14839 Updates.push_back(nullptr);
14840 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014841 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014842 HasErrors = true;
14843 } else {
14844 Updates.push_back(Update.get());
14845 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014846 if (!Info.first)
14847 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014848 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014849 ++CurInit;
14850 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014851 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014852 if (Expr *S = Clause.getStep())
14853 UsedExprs.push_back(S);
14854 // Fill the remaining part with the nullptr.
14855 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014856 Clause.setUpdates(Updates);
14857 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014858 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014859 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014860}
14861
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014862OMPClause *Sema::ActOnOpenMPAlignedClause(
14863 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14864 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014865 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014866 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014867 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14868 SourceLocation ELoc;
14869 SourceRange ERange;
14870 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014871 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014872 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014873 // It will be analyzed later.
14874 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014875 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014876 ValueDecl *D = Res.first;
14877 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014878 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014879
Alexey Bataev1efd1662016-03-29 10:59:56 +000014880 QualType QType = D->getType();
14881 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014882
14883 // OpenMP [2.8.1, simd construct, Restrictions]
14884 // The type of list items appearing in the aligned clause must be
14885 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014886 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014887 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014888 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014889 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014890 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014891 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014892 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014893 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014894 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014895 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014896 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014897 continue;
14898 }
14899
14900 // OpenMP [2.8.1, simd construct, Restrictions]
14901 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014902 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevb6e70842019-12-16 15:54:17 -050014903 Diag(ELoc, diag::err_omp_used_in_clause_twice)
14904 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014905 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14906 << getOpenMPClauseName(OMPC_aligned);
14907 continue;
14908 }
14909
Alexey Bataev1efd1662016-03-29 10:59:56 +000014910 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014911 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014912 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14913 Vars.push_back(DefaultFunctionArrayConversion(
14914 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14915 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014916 }
14917
14918 // OpenMP [2.8.1, simd construct, Description]
14919 // The parameter of the aligned clause, alignment, must be a constant
14920 // positive integer expression.
14921 // If no optional parameter is specified, implementation-defined default
14922 // alignments for SIMD instructions on the target platforms are assumed.
14923 if (Alignment != nullptr) {
14924 ExprResult AlignResult =
14925 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14926 if (AlignResult.isInvalid())
14927 return nullptr;
14928 Alignment = AlignResult.get();
14929 }
14930 if (Vars.empty())
14931 return nullptr;
14932
14933 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14934 EndLoc, Vars, Alignment);
14935}
14936
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014937OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14938 SourceLocation StartLoc,
14939 SourceLocation LParenLoc,
14940 SourceLocation EndLoc) {
14941 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014942 SmallVector<Expr *, 8> SrcExprs;
14943 SmallVector<Expr *, 8> DstExprs;
14944 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014945 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014946 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14947 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014948 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014949 Vars.push_back(RefExpr);
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
Alexey Bataeved09d242014-05-28 05:53:51 +000014956 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014957 // OpenMP [2.1, C/C++]
14958 // A list item is a variable name.
14959 // OpenMP [2.14.4.1, Restrictions, p.1]
14960 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014961 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014962 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014963 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14964 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014965 continue;
14966 }
14967
14968 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014969 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014970
14971 QualType Type = VD->getType();
14972 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14973 // It will be analyzed later.
14974 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014975 SrcExprs.push_back(nullptr);
14976 DstExprs.push_back(nullptr);
14977 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014978 continue;
14979 }
14980
14981 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14982 // A list item that appears in a copyin clause must be threadprivate.
14983 if (!DSAStack->isThreadPrivate(VD)) {
14984 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014985 << getOpenMPClauseName(OMPC_copyin)
14986 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014987 continue;
14988 }
14989
14990 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14991 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014992 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014993 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014994 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14995 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014996 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014997 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014998 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014999 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000015000 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015001 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000015002 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000015003 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000015004 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000015005 // For arrays generate assignment operation for single element and replace
15006 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000015007 ExprResult AssignmentOp =
15008 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
15009 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000015010 if (AssignmentOp.isInvalid())
15011 continue;
15012 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000015013 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000015014 if (AssignmentOp.isInvalid())
15015 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000015016
15017 DSAStack->addDSA(VD, DE, OMPC_copyin);
15018 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000015019 SrcExprs.push_back(PseudoSrcExpr);
15020 DstExprs.push_back(PseudoDstExpr);
15021 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000015022 }
15023
Alexey Bataeved09d242014-05-28 05:53:51 +000015024 if (Vars.empty())
15025 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000015026
Alexey Bataevf56f98c2015-04-16 05:39:01 +000015027 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
15028 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000015029}
15030
Alexey Bataevbae9a792014-06-27 10:37:06 +000015031OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
15032 SourceLocation StartLoc,
15033 SourceLocation LParenLoc,
15034 SourceLocation EndLoc) {
15035 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000015036 SmallVector<Expr *, 8> SrcExprs;
15037 SmallVector<Expr *, 8> DstExprs;
15038 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000015039 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000015040 assert(RefExpr && "NULL expr in OpenMP linear clause.");
15041 SourceLocation ELoc;
15042 SourceRange ERange;
15043 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000015044 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000015045 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000015046 // It will be analyzed later.
15047 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000015048 SrcExprs.push_back(nullptr);
15049 DstExprs.push_back(nullptr);
15050 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015051 }
Alexey Bataeve122da12016-03-17 10:50:17 +000015052 ValueDecl *D = Res.first;
15053 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000015054 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000015055
Alexey Bataeve122da12016-03-17 10:50:17 +000015056 QualType Type = D->getType();
15057 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015058
15059 // OpenMP [2.14.4.2, Restrictions, p.2]
15060 // A list item that appears in a copyprivate clause may not appear in a
15061 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000015062 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015063 DSAStackTy::DSAVarData DVar =
15064 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000015065 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
15066 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000015067 Diag(ELoc, diag::err_omp_wrong_dsa)
15068 << getOpenMPClauseName(DVar.CKind)
15069 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000015070 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015071 continue;
15072 }
15073
15074 // OpenMP [2.11.4.2, Restrictions, p.1]
15075 // All list items that appear in a copyprivate clause must be either
15076 // threadprivate or private in the enclosing context.
15077 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000015078 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015079 if (DVar.CKind == OMPC_shared) {
15080 Diag(ELoc, diag::err_omp_required_access)
15081 << getOpenMPClauseName(OMPC_copyprivate)
15082 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000015083 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015084 continue;
15085 }
15086 }
15087 }
15088
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015089 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000015090 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015091 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000015092 << getOpenMPClauseName(OMPC_copyprivate) << Type
15093 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015094 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000015095 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015096 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000015097 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015098 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000015099 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000015100 continue;
15101 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000015102
Alexey Bataevbae9a792014-06-27 10:37:06 +000015103 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
15104 // A variable of class type (or array thereof) that appears in a
15105 // copyin clause requires an accessible, unambiguous copy assignment
15106 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000015107 Type = Context.getBaseElementType(Type.getNonReferenceType())
15108 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015109 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015110 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000015111 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000015112 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
15113 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015114 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000015115 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000015116 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
15117 ExprResult AssignmentOp = BuildBinOp(
15118 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000015119 if (AssignmentOp.isInvalid())
15120 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000015121 AssignmentOp =
15122 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000015123 if (AssignmentOp.isInvalid())
15124 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000015125
15126 // No need to mark vars as copyprivate, they are already threadprivate or
15127 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000015128 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000015129 Vars.push_back(
15130 VD ? RefExpr->IgnoreParens()
15131 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000015132 SrcExprs.push_back(PseudoSrcExpr);
15133 DstExprs.push_back(PseudoDstExpr);
15134 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000015135 }
15136
15137 if (Vars.empty())
15138 return nullptr;
15139
Alexey Bataeva63048e2015-03-23 06:18:07 +000015140 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
15141 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000015142}
15143
Alexey Bataev6125da92014-07-21 11:26:11 +000015144OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
15145 SourceLocation StartLoc,
15146 SourceLocation LParenLoc,
15147 SourceLocation EndLoc) {
15148 if (VarList.empty())
15149 return nullptr;
15150
15151 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
15152}
Alexey Bataevdea47612014-07-23 07:46:59 +000015153
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015154OMPClause *
15155Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
15156 SourceLocation DepLoc, SourceLocation ColonLoc,
15157 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
15158 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000015159 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015160 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000015161 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000015162 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000015163 return nullptr;
15164 }
15165 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015166 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
15167 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000015168 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015169 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000015170 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
15171 /*Last=*/OMPC_DEPEND_unknown, Except)
15172 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015173 return nullptr;
15174 }
15175 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000015176 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015177 llvm::APSInt DepCounter(/*BitWidth=*/32);
15178 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000015179 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
15180 if (const Expr *OrderedCountExpr =
15181 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015182 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
15183 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015184 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015185 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015186 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000015187 assert(RefExpr && "NULL expr in OpenMP shared clause.");
15188 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
15189 // It will be analyzed later.
15190 Vars.push_back(RefExpr);
15191 continue;
15192 }
15193
15194 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000015195 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000015196 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000015197 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015198 DepCounter >= TotalDepCount) {
15199 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
15200 continue;
15201 }
15202 ++DepCounter;
15203 // OpenMP [2.13.9, Summary]
15204 // depend(dependence-type : vec), where dependence-type is:
15205 // 'sink' and where vec is the iteration vector, which has the form:
15206 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
15207 // where n is the value specified by the ordered clause in the loop
15208 // directive, xi denotes the loop iteration variable of the i-th nested
15209 // loop associated with the loop directive, and di is a constant
15210 // non-negative integer.
15211 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015212 // It will be analyzed later.
15213 Vars.push_back(RefExpr);
15214 continue;
15215 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015216 SimpleExpr = SimpleExpr->IgnoreImplicit();
15217 OverloadedOperatorKind OOK = OO_None;
15218 SourceLocation OOLoc;
15219 Expr *LHS = SimpleExpr;
15220 Expr *RHS = nullptr;
15221 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
15222 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
15223 OOLoc = BO->getOperatorLoc();
15224 LHS = BO->getLHS()->IgnoreParenImpCasts();
15225 RHS = BO->getRHS()->IgnoreParenImpCasts();
15226 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
15227 OOK = OCE->getOperator();
15228 OOLoc = OCE->getOperatorLoc();
15229 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
15230 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
15231 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
15232 OOK = MCE->getMethodDecl()
15233 ->getNameInfo()
15234 .getName()
15235 .getCXXOverloadedOperator();
15236 OOLoc = MCE->getCallee()->getExprLoc();
15237 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
15238 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015239 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015240 SourceLocation ELoc;
15241 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000015242 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015243 if (Res.second) {
15244 // It will be analyzed later.
15245 Vars.push_back(RefExpr);
15246 }
15247 ValueDecl *D = Res.first;
15248 if (!D)
15249 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015250
Alexey Bataev17daedf2018-02-15 22:42:57 +000015251 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
15252 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
15253 continue;
15254 }
15255 if (RHS) {
15256 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
15257 RHS, OMPC_depend, /*StrictlyPositive=*/false);
15258 if (RHSRes.isInvalid())
15259 continue;
15260 }
15261 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015262 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015263 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015264 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000015265 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000015266 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000015267 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
15268 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000015269 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000015270 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000015271 continue;
15272 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015273 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015274 } else {
Kelvin Li427ffa22020-01-03 11:55:37 -050015275 // OpenMP 5.0 [2.17.11, Restrictions]
15276 // List items used in depend clauses cannot be zero-length array sections.
15277 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
15278 if (OASE) {
15279 const Expr *Length = OASE->getLength();
15280 Expr::EvalResult Result;
15281 if (Length && !Length->isValueDependent() &&
15282 Length->EvaluateAsInt(Result, Context) &&
15283 Result.Val.getInt().isNullValue()) {
15284 Diag(ELoc,
15285 diag::err_omp_depend_zero_length_array_section_not_allowed)
15286 << SimpleExpr->getSourceRange();
15287 continue;
15288 }
15289 }
15290
Alexey Bataev17daedf2018-02-15 22:42:57 +000015291 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
15292 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
15293 (ASE &&
15294 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
15295 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
15296 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15297 << RefExpr->getSourceRange();
15298 continue;
15299 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000015300
15301 ExprResult Res;
15302 {
15303 Sema::TentativeAnalysisScope Trap(*this);
15304 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
15305 RefExpr->IgnoreParenImpCasts());
15306 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015307 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
15308 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15309 << RefExpr->getSourceRange();
15310 continue;
15311 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015312 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015313 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015314 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015315
15316 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
15317 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015318 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015319 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
15320 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
15321 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
15322 }
15323 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
15324 Vars.empty())
15325 return nullptr;
15326
Alexey Bataev8b427062016-05-25 12:36:08 +000015327 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000015328 DepKind, DepLoc, ColonLoc, Vars,
15329 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000015330 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
15331 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000015332 DSAStack->addDoacrossDependClause(C, OpsOffs);
15333 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015334}
Michael Wonge710d542015-08-07 16:16:36 +000015335
15336OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
15337 SourceLocation LParenLoc,
15338 SourceLocation EndLoc) {
15339 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015340 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000015341
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015342 // OpenMP [2.9.1, Restrictions]
15343 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015344 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000015345 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015346 return nullptr;
15347
Alexey Bataev931e19b2017-10-02 16:32:39 +000015348 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015349 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050015350 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000015351 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015352 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015353 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015354 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15355 HelperValStmt = buildPreInits(Context, Captures);
15356 }
15357
Alexey Bataev8451efa2018-01-15 19:06:12 +000015358 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
15359 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000015360}
Kelvin Li0bff7af2015-11-23 05:32:03 +000015361
Alexey Bataeve3727102018-04-18 15:57:46 +000015362static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000015363 DSAStackTy *Stack, QualType QTy,
15364 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000015365 NamedDecl *ND;
15366 if (QTy->isIncompleteType(&ND)) {
15367 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
15368 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015369 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000015370 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
Jonas Hahnfeld071dca22019-12-07 13:31:46 +010015371 !QTy.isTriviallyCopyableType(SemaRef.Context))
Alexey Bataev95c23e72018-02-27 21:31:11 +000015372 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015373 return true;
15374}
15375
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000015376/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015377/// (array section or array subscript) does NOT specify the whole size of the
15378/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015379static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015380 const Expr *E,
15381 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015382 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015383
15384 // If this is an array subscript, it refers to the whole size if the size of
15385 // the dimension is constant and equals 1. Also, an array section assumes the
15386 // format of an array subscript if no colon is used.
15387 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015388 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015389 return ATy->getSize().getSExtValue() != 1;
15390 // Size can't be evaluated statically.
15391 return false;
15392 }
15393
15394 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015395 const Expr *LowerBound = OASE->getLowerBound();
15396 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015397
15398 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000015399 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015400 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000015401 Expr::EvalResult Result;
15402 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015403 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000015404
15405 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015406 if (ConstLowerBound.getSExtValue())
15407 return true;
15408 }
15409
15410 // If we don't have a length we covering the whole dimension.
15411 if (!Length)
15412 return false;
15413
15414 // If the base is a pointer, we don't have a way to get the size of the
15415 // pointee.
15416 if (BaseQTy->isPointerType())
15417 return false;
15418
15419 // We can only check if the length is the same as the size of the dimension
15420 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000015421 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015422 if (!CATy)
15423 return false;
15424
Fangrui Song407659a2018-11-30 23:41:18 +000015425 Expr::EvalResult Result;
15426 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015427 return false; // Can't get the integer value as a constant.
15428
Fangrui Song407659a2018-11-30 23:41:18 +000015429 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015430 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
15431}
15432
15433// Return true if it can be proven that the provided array expression (array
15434// section or array subscript) does NOT specify a single element of the array
15435// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015436static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000015437 const Expr *E,
15438 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015439 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015440
15441 // An array subscript always refer to a single element. Also, an array section
15442 // assumes the format of an array subscript if no colon is used.
15443 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
15444 return false;
15445
15446 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015447 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015448
15449 // If we don't have a length we have to check if the array has unitary size
15450 // for this dimension. Also, we should always expect a length if the base type
15451 // is pointer.
15452 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015453 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015454 return ATy->getSize().getSExtValue() != 1;
15455 // We cannot assume anything.
15456 return false;
15457 }
15458
15459 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000015460 Expr::EvalResult Result;
15461 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015462 return false; // Can't get the integer value as a constant.
15463
Fangrui Song407659a2018-11-30 23:41:18 +000015464 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015465 return ConstLength.getSExtValue() != 1;
15466}
15467
Samuel Antao661c0902016-05-26 17:39:58 +000015468// Return the expression of the base of the mappable expression or null if it
15469// cannot be determined and do all the necessary checks to see if the expression
15470// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000015471// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015472static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000015473 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000015474 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015475 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015476 SourceLocation ELoc = E->getExprLoc();
15477 SourceRange ERange = E->getSourceRange();
15478
15479 // The base of elements of list in a map clause have to be either:
15480 // - a reference to variable or field.
15481 // - a member expression.
15482 // - an array expression.
15483 //
15484 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
15485 // reference to 'r'.
15486 //
15487 // If we have:
15488 //
15489 // struct SS {
15490 // Bla S;
15491 // foo() {
15492 // #pragma omp target map (S.Arr[:12]);
15493 // }
15494 // }
15495 //
15496 // We want to retrieve the member expression 'this->S';
15497
Alexey Bataeve3727102018-04-18 15:57:46 +000015498 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015499
Samuel Antao5de996e2016-01-22 20:21:36 +000015500 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15501 // If a list item is an array section, it must specify contiguous storage.
15502 //
15503 // For this restriction it is sufficient that we make sure only references
15504 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015505 // exist except in the rightmost expression (unless they cover the whole
15506 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015507 //
15508 // r.ArrS[3:5].Arr[6:7]
15509 //
15510 // r.ArrS[3:5].x
15511 //
15512 // but these would be valid:
15513 // r.ArrS[3].Arr[6:7]
15514 //
15515 // r.ArrS[3].x
15516
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015517 bool AllowUnitySizeArraySection = true;
15518 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015519
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015520 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015521 E = E->IgnoreParenImpCasts();
15522
15523 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15524 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015525 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015526
15527 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015528
15529 // If we got a reference to a declaration, we should not expect any array
15530 // section before that.
15531 AllowUnitySizeArraySection = false;
15532 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015533
15534 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015535 CurComponents.emplace_back(CurE, CurE->getDecl());
15536 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015537 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015538
15539 if (isa<CXXThisExpr>(BaseE))
15540 // We found a base expression: this->Val.
15541 RelevantExpr = CurE;
15542 else
15543 E = BaseE;
15544
15545 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015546 if (!NoDiagnose) {
15547 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15548 << CurE->getSourceRange();
15549 return nullptr;
15550 }
15551 if (RelevantExpr)
15552 return nullptr;
15553 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015554 }
15555
15556 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15557
15558 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15559 // A bit-field cannot appear in a map clause.
15560 //
15561 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015562 if (!NoDiagnose) {
15563 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15564 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15565 return nullptr;
15566 }
15567 if (RelevantExpr)
15568 return nullptr;
15569 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015570 }
15571
15572 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15573 // If the type of a list item is a reference to a type T then the type
15574 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015575 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015576
15577 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15578 // A list item cannot be a variable that is a member of a structure with
15579 // a union type.
15580 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015581 if (CurType->isUnionType()) {
15582 if (!NoDiagnose) {
15583 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15584 << CurE->getSourceRange();
15585 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015586 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015587 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015588 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015589
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015590 // If we got a member expression, we should not expect any array section
15591 // before that:
15592 //
15593 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15594 // If a list item is an element of a structure, only the rightmost symbol
15595 // of the variable reference can be an array section.
15596 //
15597 AllowUnitySizeArraySection = false;
15598 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015599
15600 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015601 CurComponents.emplace_back(CurE, FD);
15602 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015603 E = CurE->getBase()->IgnoreParenImpCasts();
15604
15605 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015606 if (!NoDiagnose) {
15607 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15608 << 0 << CurE->getSourceRange();
15609 return nullptr;
15610 }
15611 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015612 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015613
15614 // If we got an array subscript that express the whole dimension we
15615 // can have any array expressions before. If it only expressing part of
15616 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015617 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015618 E->getType()))
15619 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015620
Patrick Lystere13b1e32019-01-02 19:28:48 +000015621 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15622 Expr::EvalResult Result;
15623 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15624 if (!Result.Val.getInt().isNullValue()) {
15625 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15626 diag::err_omp_invalid_map_this_expr);
15627 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15628 diag::note_omp_invalid_subscript_on_this_ptr_map);
15629 }
15630 }
15631 RelevantExpr = TE;
15632 }
15633
Samuel Antao90927002016-04-26 14:54:23 +000015634 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015635 CurComponents.emplace_back(CurE, nullptr);
15636 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015637 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015638 E = CurE->getBase()->IgnoreParenImpCasts();
15639
Alexey Bataev27041fa2017-12-05 15:22:49 +000015640 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015641 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15642
Samuel Antao5de996e2016-01-22 20:21:36 +000015643 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15644 // If the type of a list item is a reference to a type T then the type
15645 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015646 if (CurType->isReferenceType())
15647 CurType = CurType->getPointeeType();
15648
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015649 bool IsPointer = CurType->isAnyPointerType();
15650
15651 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015652 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15653 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015654 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015655 }
15656
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015657 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015658 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015659 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015660 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015661
Samuel Antaodab51bb2016-07-18 23:22:11 +000015662 if (AllowWholeSizeArraySection) {
15663 // Any array section is currently allowed. Allowing a whole size array
15664 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015665 //
15666 // If this array section refers to the whole dimension we can still
15667 // accept other array sections before this one, except if the base is a
15668 // pointer. Otherwise, only unitary sections are accepted.
15669 if (NotWhole || IsPointer)
15670 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015671 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015672 // A unity or whole array section is not allowed and that is not
15673 // compatible with the properties of the current array section.
15674 SemaRef.Diag(
15675 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15676 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015677 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015678 }
Samuel Antao90927002016-04-26 14:54:23 +000015679
Patrick Lystere13b1e32019-01-02 19:28:48 +000015680 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15681 Expr::EvalResult ResultR;
15682 Expr::EvalResult ResultL;
15683 if (CurE->getLength()->EvaluateAsInt(ResultR,
15684 SemaRef.getASTContext())) {
15685 if (!ResultR.Val.getInt().isOneValue()) {
15686 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15687 diag::err_omp_invalid_map_this_expr);
15688 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15689 diag::note_omp_invalid_length_on_this_ptr_mapping);
15690 }
15691 }
15692 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15693 ResultL, SemaRef.getASTContext())) {
15694 if (!ResultL.Val.getInt().isNullValue()) {
15695 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15696 diag::err_omp_invalid_map_this_expr);
15697 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15698 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15699 }
15700 }
15701 RelevantExpr = TE;
15702 }
15703
Samuel Antao90927002016-04-26 14:54:23 +000015704 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015705 CurComponents.emplace_back(CurE, nullptr);
15706 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015707 if (!NoDiagnose) {
15708 // If nothing else worked, this is not a valid map clause expression.
15709 SemaRef.Diag(
15710 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15711 << ERange;
15712 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015713 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015714 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015715 }
15716
15717 return RelevantExpr;
15718}
15719
15720// Return true if expression E associated with value VD has conflicts with other
15721// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015722static bool checkMapConflicts(
15723 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015724 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015725 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15726 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015727 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015728 SourceLocation ELoc = E->getExprLoc();
15729 SourceRange ERange = E->getSourceRange();
15730
15731 // In order to easily check the conflicts we need to match each component of
15732 // the expression under test with the components of the expressions that are
15733 // already in the stack.
15734
Samuel Antao5de996e2016-01-22 20:21:36 +000015735 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015736 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015737 "Map clause expression with unexpected base!");
15738
15739 // Variables to help detecting enclosing problems in data environment nests.
15740 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015741 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015742
Samuel Antao90927002016-04-26 14:54:23 +000015743 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15744 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015745 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15746 ERange, CKind, &EnclosingExpr,
15747 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15748 StackComponents,
15749 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015750 assert(!StackComponents.empty() &&
15751 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015752 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015753 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015754 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015755
Samuel Antao90927002016-04-26 14:54:23 +000015756 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015757 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015758
Samuel Antao5de996e2016-01-22 20:21:36 +000015759 // Expressions must start from the same base. Here we detect at which
15760 // point both expressions diverge from each other and see if we can
15761 // detect if the memory referred to both expressions is contiguous and
15762 // do not overlap.
15763 auto CI = CurComponents.rbegin();
15764 auto CE = CurComponents.rend();
15765 auto SI = StackComponents.rbegin();
15766 auto SE = StackComponents.rend();
15767 for (; CI != CE && SI != SE; ++CI, ++SI) {
15768
15769 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15770 // At most one list item can be an array item derived from a given
15771 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015772 if (CurrentRegionOnly &&
15773 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15774 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15775 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15776 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15777 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015778 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015779 << CI->getAssociatedExpression()->getSourceRange();
15780 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15781 diag::note_used_here)
15782 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015783 return true;
15784 }
15785
15786 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015787 if (CI->getAssociatedExpression()->getStmtClass() !=
15788 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015789 break;
15790
15791 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015792 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015793 break;
15794 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015795 // Check if the extra components of the expressions in the enclosing
15796 // data environment are redundant for the current base declaration.
15797 // If they are, the maps completely overlap, which is legal.
15798 for (; SI != SE; ++SI) {
15799 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015800 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015801 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015802 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015803 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015804 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015805 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015806 Type =
15807 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15808 }
15809 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015810 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015811 SemaRef, SI->getAssociatedExpression(), Type))
15812 break;
15813 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015814
15815 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15816 // List items of map clauses in the same construct must not share
15817 // original storage.
15818 //
15819 // If the expressions are exactly the same or one is a subset of the
15820 // other, it means they are sharing storage.
15821 if (CI == CE && SI == SE) {
15822 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015823 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015824 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015825 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015826 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015827 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15828 << ERange;
15829 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015830 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15831 << RE->getSourceRange();
15832 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015833 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015834 // If we find the same expression in the enclosing data environment,
15835 // that is legal.
15836 IsEnclosedByDataEnvironmentExpr = true;
15837 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015838 }
15839
Samuel Antao90927002016-04-26 14:54:23 +000015840 QualType DerivedType =
15841 std::prev(CI)->getAssociatedDeclaration()->getType();
15842 SourceLocation DerivedLoc =
15843 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015844
15845 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15846 // If the type of a list item is a reference to a type T then the type
15847 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015848 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015849
15850 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15851 // A variable for which the type is pointer and an array section
15852 // derived from that variable must not appear as list items of map
15853 // clauses of the same construct.
15854 //
15855 // Also, cover one of the cases in:
15856 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15857 // If any part of the original storage of a list item has corresponding
15858 // storage in the device data environment, all of the original storage
15859 // must have corresponding storage in the device data environment.
15860 //
15861 if (DerivedType->isAnyPointerType()) {
15862 if (CI == CE || SI == SE) {
15863 SemaRef.Diag(
15864 DerivedLoc,
15865 diag::err_omp_pointer_mapped_along_with_derived_section)
15866 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015867 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15868 << RE->getSourceRange();
15869 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015870 }
15871 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015872 SI->getAssociatedExpression()->getStmtClass() ||
15873 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15874 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015875 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015876 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015877 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015878 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15879 << RE->getSourceRange();
15880 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015881 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015882 }
15883
15884 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15885 // List items of map clauses in the same construct must not share
15886 // original storage.
15887 //
15888 // An expression is a subset of the other.
15889 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015890 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015891 if (CI != CE || SI != SE) {
15892 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15893 // a pointer.
15894 auto Begin =
15895 CI != CE ? CurComponents.begin() : StackComponents.begin();
15896 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15897 auto It = Begin;
15898 while (It != End && !It->getAssociatedDeclaration())
15899 std::advance(It, 1);
15900 assert(It != End &&
15901 "Expected at least one component with the declaration.");
15902 if (It != Begin && It->getAssociatedDeclaration()
15903 ->getType()
15904 .getCanonicalType()
15905 ->isAnyPointerType()) {
15906 IsEnclosedByDataEnvironmentExpr = false;
15907 EnclosingExpr = nullptr;
15908 return false;
15909 }
15910 }
Samuel Antao661c0902016-05-26 17:39:58 +000015911 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015912 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015913 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015914 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15915 << ERange;
15916 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015917 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15918 << RE->getSourceRange();
15919 return true;
15920 }
15921
15922 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015923 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015924 if (!CurrentRegionOnly && SI != SE)
15925 EnclosingExpr = RE;
15926
15927 // The current expression is a subset of the expression in the data
15928 // environment.
15929 IsEnclosedByDataEnvironmentExpr |=
15930 (!CurrentRegionOnly && CI != CE && SI == SE);
15931
15932 return false;
15933 });
15934
15935 if (CurrentRegionOnly)
15936 return FoundError;
15937
15938 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15939 // If any part of the original storage of a list item has corresponding
15940 // storage in the device data environment, all of the original storage must
15941 // have corresponding storage in the device data environment.
15942 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15943 // If a list item is an element of a structure, and a different element of
15944 // the structure has a corresponding list item in the device data environment
15945 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015946 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015947 // data environment prior to the task encountering the construct.
15948 //
15949 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15950 SemaRef.Diag(ELoc,
15951 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15952 << ERange;
15953 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15954 << EnclosingExpr->getSourceRange();
15955 return true;
15956 }
15957
15958 return FoundError;
15959}
15960
Michael Kruse4304e9d2019-02-19 16:38:20 +000015961// Look up the user-defined mapper given the mapper name and mapped type, and
15962// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015963static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15964 CXXScopeSpec &MapperIdScopeSpec,
15965 const DeclarationNameInfo &MapperId,
15966 QualType Type,
15967 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015968 if (MapperIdScopeSpec.isInvalid())
15969 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015970 // Get the actual type for the array type.
15971 if (Type->isArrayType()) {
15972 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15973 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15974 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015975 // Find all user-defined mappers with the given MapperId.
15976 SmallVector<UnresolvedSet<8>, 4> Lookups;
15977 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15978 Lookup.suppressDiagnostics();
15979 if (S) {
15980 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15981 NamedDecl *D = Lookup.getRepresentativeDecl();
15982 while (S && !S->isDeclScope(D))
15983 S = S->getParent();
15984 if (S)
15985 S = S->getParent();
15986 Lookups.emplace_back();
15987 Lookups.back().append(Lookup.begin(), Lookup.end());
15988 Lookup.clear();
15989 }
15990 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15991 // Extract the user-defined mappers with the given MapperId.
15992 Lookups.push_back(UnresolvedSet<8>());
15993 for (NamedDecl *D : ULE->decls()) {
15994 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15995 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15996 Lookups.back().addDecl(DMD);
15997 }
15998 }
15999 // Defer the lookup for dependent types. The results will be passed through
16000 // UnresolvedMapper on instantiation.
16001 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
16002 Type->isInstantiationDependentType() ||
16003 Type->containsUnexpandedParameterPack() ||
16004 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
16005 return !D->isInvalidDecl() &&
16006 (D->getType()->isDependentType() ||
16007 D->getType()->isInstantiationDependentType() ||
16008 D->getType()->containsUnexpandedParameterPack());
16009 })) {
16010 UnresolvedSet<8> URS;
16011 for (const UnresolvedSet<8> &Set : Lookups) {
16012 if (Set.empty())
16013 continue;
16014 URS.append(Set.begin(), Set.end());
16015 }
16016 return UnresolvedLookupExpr::Create(
16017 SemaRef.Context, /*NamingClass=*/nullptr,
16018 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
16019 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
16020 }
Michael Kruse945249b2019-09-26 22:53:01 +000016021 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000016022 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16023 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000016024 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
16025 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
16026 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
16027 return ExprError();
16028 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016029 // Perform argument dependent lookup.
16030 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
16031 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
16032 // Return the first user-defined mapper with the desired type.
16033 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16034 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
16035 if (!D->isInvalidDecl() &&
16036 SemaRef.Context.hasSameType(D->getType(), Type))
16037 return D;
16038 return nullptr;
16039 }))
16040 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
16041 // Find the first user-defined mapper with a type derived from the desired
16042 // type.
16043 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
16044 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
16045 if (!D->isInvalidDecl() &&
16046 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
16047 !Type.isMoreQualifiedThan(D->getType()))
16048 return D;
16049 return nullptr;
16050 })) {
16051 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
16052 /*DetectVirtual=*/false);
16053 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
16054 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
16055 VD->getType().getUnqualifiedType()))) {
16056 if (SemaRef.CheckBaseClassAccess(
16057 Loc, VD->getType(), Type, Paths.front(),
16058 /*DiagID=*/0) != Sema::AR_inaccessible) {
16059 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
16060 }
16061 }
16062 }
16063 }
16064 // Report error if a mapper is specified, but cannot be found.
16065 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
16066 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
16067 << Type << MapperId.getName();
16068 return ExprError();
16069 }
16070 return ExprEmpty();
16071}
16072
Samuel Antao661c0902016-05-26 17:39:58 +000016073namespace {
16074// Utility struct that gathers all the related lists associated with a mappable
16075// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000016076struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000016077 // The list of expressions.
16078 ArrayRef<Expr *> VarList;
16079 // The list of processed expressions.
16080 SmallVector<Expr *, 16> ProcessedVarList;
16081 // The mappble components for each expression.
16082 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
16083 // The base declaration of the variable.
16084 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000016085 // The reference to the user-defined mapper associated with every expression.
16086 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000016087
16088 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
16089 // We have a list of components and base declarations for each entry in the
16090 // variable list.
16091 VarComponents.reserve(VarList.size());
16092 VarBaseDeclarations.reserve(VarList.size());
16093 }
16094};
16095}
16096
16097// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000016098// \a CKind. In the check process the valid expressions, mappable expression
16099// components, variables, and user-defined mappers are extracted and used to
16100// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
16101// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
16102// and \a MapperId are expected to be valid if the clause kind is 'map'.
16103static void checkMappableExpressionList(
16104 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
16105 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016106 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
16107 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016108 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000016109 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016110 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
16111 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000016112 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000016113
16114 // If the identifier of user-defined mapper is not specified, it is "default".
16115 // We do not change the actual name in this clause to distinguish whether a
16116 // mapper is specified explicitly, i.e., it is not explicitly specified when
16117 // MapperId.getName() is empty.
16118 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
16119 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
16120 MapperId.setName(DeclNames.getIdentifier(
16121 &SemaRef.getASTContext().Idents.get("default")));
16122 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016123
16124 // Iterators to find the current unresolved mapper expression.
16125 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
16126 bool UpdateUMIt = false;
16127 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000016128
Samuel Antao90927002016-04-26 14:54:23 +000016129 // Keep track of the mappable components and base declarations in this clause.
16130 // Each entry in the list is going to have a list of components associated. We
16131 // record each set of the components so that we can build the clause later on.
16132 // In the end we should have the same amount of declarations and component
16133 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000016134
Alexey Bataeve3727102018-04-18 15:57:46 +000016135 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016136 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000016137 SourceLocation ELoc = RE->getExprLoc();
16138
Michael Kruse4304e9d2019-02-19 16:38:20 +000016139 // Find the current unresolved mapper expression.
16140 if (UpdateUMIt && UMIt != UMEnd) {
16141 UMIt++;
16142 assert(
16143 UMIt != UMEnd &&
16144 "Expect the size of UnresolvedMappers to match with that of VarList");
16145 }
16146 UpdateUMIt = true;
16147 if (UMIt != UMEnd)
16148 UnresolvedMapper = *UMIt;
16149
Alexey Bataeve3727102018-04-18 15:57:46 +000016150 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000016151
16152 if (VE->isValueDependent() || VE->isTypeDependent() ||
16153 VE->isInstantiationDependent() ||
16154 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000016155 // Try to find the associated user-defined mapper.
16156 ExprResult ER = buildUserDefinedMapperRef(
16157 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16158 VE->getType().getCanonicalType(), UnresolvedMapper);
16159 if (ER.isInvalid())
16160 continue;
16161 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000016162 // We can only analyze this information once the missing information is
16163 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000016164 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016165 continue;
16166 }
16167
Alexey Bataeve3727102018-04-18 15:57:46 +000016168 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000016169
Samuel Antao5de996e2016-01-22 20:21:36 +000016170 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000016171 SemaRef.Diag(ELoc,
16172 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000016173 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000016174 continue;
16175 }
16176
Samuel Antao90927002016-04-26 14:54:23 +000016177 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
16178 ValueDecl *CurDeclaration = nullptr;
16179
16180 // Obtain the array or member expression bases if required. Also, fill the
16181 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000016182 const Expr *BE = checkMapClauseExpressionBase(
16183 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000016184 if (!BE)
16185 continue;
16186
Samuel Antao90927002016-04-26 14:54:23 +000016187 assert(!CurComponents.empty() &&
16188 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000016189
Patrick Lystere13b1e32019-01-02 19:28:48 +000016190 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
16191 // Add store "this" pointer to class in DSAStackTy for future checking
16192 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000016193 // Try to find the associated user-defined mapper.
16194 ExprResult ER = buildUserDefinedMapperRef(
16195 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16196 VE->getType().getCanonicalType(), UnresolvedMapper);
16197 if (ER.isInvalid())
16198 continue;
16199 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000016200 // Skip restriction checking for variable or field declarations
16201 MVLI.ProcessedVarList.push_back(RE);
16202 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16203 MVLI.VarComponents.back().append(CurComponents.begin(),
16204 CurComponents.end());
16205 MVLI.VarBaseDeclarations.push_back(nullptr);
16206 continue;
16207 }
16208
Samuel Antao90927002016-04-26 14:54:23 +000016209 // For the following checks, we rely on the base declaration which is
16210 // expected to be associated with the last component. The declaration is
16211 // expected to be a variable or a field (if 'this' is being mapped).
16212 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
16213 assert(CurDeclaration && "Null decl on map clause.");
16214 assert(
16215 CurDeclaration->isCanonicalDecl() &&
16216 "Expecting components to have associated only canonical declarations.");
16217
16218 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000016219 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000016220
16221 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000016222 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000016223
16224 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000016225 // threadprivate variables cannot appear in a map clause.
16226 // OpenMP 4.5 [2.10.5, target update Construct]
16227 // threadprivate variables cannot appear in a from clause.
16228 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016229 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016230 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
16231 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000016232 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016233 continue;
16234 }
16235
Samuel Antao5de996e2016-01-22 20:21:36 +000016236 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
16237 // A list item cannot appear in both a map clause and a data-sharing
16238 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000016239
Samuel Antao5de996e2016-01-22 20:21:36 +000016240 // Check conflicts with other map clause expressions. We check the conflicts
16241 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000016242 // environment, because the restrictions are different. We only have to
16243 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000016244 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016245 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016246 break;
Samuel Antao661c0902016-05-26 17:39:58 +000016247 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000016248 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016249 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016250 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000016251
Samuel Antao661c0902016-05-26 17:39:58 +000016252 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000016253 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16254 // If the type of a list item is a reference to a type T then the type will
16255 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000016256 auto I = llvm::find_if(
16257 CurComponents,
16258 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
16259 return MC.getAssociatedDeclaration();
16260 });
16261 assert(I != CurComponents.end() && "Null decl on map clause.");
Alexey Bataev48bad082020-01-14 14:13:47 -050016262 QualType Type;
16263 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
16264 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
16265 if (ASE) {
16266 Type = ASE->getType().getNonReferenceType();
16267 } else if (OASE) {
16268 QualType BaseType =
16269 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16270 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16271 Type = ATy->getElementType();
16272 else
16273 Type = BaseType->getPointeeType();
16274 Type = Type.getNonReferenceType();
16275 } else {
16276 Type = VE->getType();
16277 }
Samuel Antao5de996e2016-01-22 20:21:36 +000016278
Samuel Antao661c0902016-05-26 17:39:58 +000016279 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
16280 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000016281 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000016282 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000016283 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000016284 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000016285 continue;
16286
Alexey Bataev48bad082020-01-14 14:13:47 -050016287 Type = I->getAssociatedDeclaration()->getType().getNonReferenceType();
16288
Samuel Antao661c0902016-05-26 17:39:58 +000016289 if (CKind == OMPC_map) {
16290 // target enter data
16291 // OpenMP [2.10.2, Restrictions, p. 99]
16292 // A map-type must be specified in all map clauses and must be either
16293 // to or alloc.
16294 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
16295 if (DKind == OMPD_target_enter_data &&
16296 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
16297 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16298 << (IsMapTypeImplicit ? 1 : 0)
16299 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16300 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016301 continue;
16302 }
Samuel Antao661c0902016-05-26 17:39:58 +000016303
16304 // target exit_data
16305 // OpenMP [2.10.3, Restrictions, p. 102]
16306 // A map-type must be specified in all map clauses and must be either
16307 // from, release, or delete.
16308 if (DKind == OMPD_target_exit_data &&
16309 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
16310 MapType == OMPC_MAP_delete)) {
16311 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16312 << (IsMapTypeImplicit ? 1 : 0)
16313 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16314 << getOpenMPDirectiveName(DKind);
16315 continue;
16316 }
16317
16318 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16319 // A list item cannot appear in both a map clause and a data-sharing
16320 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000016321 //
16322 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16323 // A list item cannot appear in both a map clause and a data-sharing
16324 // attribute clause on the same construct unless the construct is a
16325 // combined construct.
16326 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
16327 isOpenMPTargetExecutionDirective(DKind)) ||
16328 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016329 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016330 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000016331 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000016332 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000016333 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000016334 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016335 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000016336 continue;
16337 }
16338 }
Michael Kruse01f670d2019-02-22 22:29:42 +000016339 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016340
Michael Kruse01f670d2019-02-22 22:29:42 +000016341 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000016342 ExprResult ER = buildUserDefinedMapperRef(
16343 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16344 Type.getCanonicalType(), UnresolvedMapper);
16345 if (ER.isInvalid())
16346 continue;
16347 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016348
Samuel Antao90927002016-04-26 14:54:23 +000016349 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000016350 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000016351
16352 // Store the components in the stack so that they can be used to check
16353 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000016354 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
16355 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000016356
16357 // Save the components and declaration to create the clause. For purposes of
16358 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000016359 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000016360 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16361 MVLI.VarComponents.back().append(CurComponents.begin(),
16362 CurComponents.end());
16363 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
16364 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016365 }
Samuel Antao661c0902016-05-26 17:39:58 +000016366}
16367
Michael Kruse4304e9d2019-02-19 16:38:20 +000016368OMPClause *Sema::ActOnOpenMPMapClause(
16369 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16370 ArrayRef<SourceLocation> MapTypeModifiersLoc,
16371 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
16372 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
16373 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
16374 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
16375 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
16376 OMPC_MAP_MODIFIER_unknown,
16377 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000016378 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
16379
16380 // Process map-type-modifiers, flag errors for duplicate modifiers.
16381 unsigned Count = 0;
16382 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
16383 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
16384 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
16385 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
16386 continue;
16387 }
16388 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000016389 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000016390 Modifiers[Count] = MapTypeModifiers[I];
16391 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
16392 ++Count;
16393 }
16394
Michael Kruse4304e9d2019-02-19 16:38:20 +000016395 MappableVarListInfo MVLI(VarList);
16396 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016397 MapperIdScopeSpec, MapperId, UnresolvedMappers,
16398 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000016399
Samuel Antao5de996e2016-01-22 20:21:36 +000016400 // We need to produce a map clause even if we don't have variables so that
16401 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000016402 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
16403 MVLI.VarBaseDeclarations, MVLI.VarComponents,
16404 MVLI.UDMapperList, Modifiers, ModifiersLoc,
16405 MapperIdScopeSpec.getWithLocInContext(Context),
16406 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016407}
Kelvin Li099bb8c2015-11-24 20:50:12 +000016408
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016409QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
16410 TypeResult ParsedType) {
16411 assert(ParsedType.isUsable());
16412
16413 QualType ReductionType = GetTypeFromParser(ParsedType.get());
16414 if (ReductionType.isNull())
16415 return QualType();
16416
16417 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
16418 // A type name in a declare reduction directive cannot be a function type, an
16419 // array type, a reference type, or a type qualified with const, volatile or
16420 // restrict.
16421 if (ReductionType.hasQualifiers()) {
16422 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
16423 return QualType();
16424 }
16425
16426 if (ReductionType->isFunctionType()) {
16427 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
16428 return QualType();
16429 }
16430 if (ReductionType->isReferenceType()) {
16431 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
16432 return QualType();
16433 }
16434 if (ReductionType->isArrayType()) {
16435 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
16436 return QualType();
16437 }
16438 return ReductionType;
16439}
16440
16441Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
16442 Scope *S, DeclContext *DC, DeclarationName Name,
16443 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
16444 AccessSpecifier AS, Decl *PrevDeclInScope) {
16445 SmallVector<Decl *, 8> Decls;
16446 Decls.reserve(ReductionTypes.size());
16447
16448 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000016449 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016450 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
16451 // A reduction-identifier may not be re-declared in the current scope for the
16452 // same type or for a type that is compatible according to the base language
16453 // rules.
16454 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16455 OMPDeclareReductionDecl *PrevDRD = nullptr;
16456 bool InCompoundScope = true;
16457 if (S != nullptr) {
16458 // Find previous declaration with the same name not referenced in other
16459 // declarations.
16460 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16461 InCompoundScope =
16462 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16463 LookupName(Lookup, S);
16464 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16465 /*AllowInlineNamespace=*/false);
16466 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000016467 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016468 while (Filter.hasNext()) {
16469 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
16470 if (InCompoundScope) {
16471 auto I = UsedAsPrevious.find(PrevDecl);
16472 if (I == UsedAsPrevious.end())
16473 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000016474 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016475 UsedAsPrevious[D] = true;
16476 }
16477 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16478 PrevDecl->getLocation();
16479 }
16480 Filter.done();
16481 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016482 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016483 if (!PrevData.second) {
16484 PrevDRD = PrevData.first;
16485 break;
16486 }
16487 }
16488 }
16489 } else if (PrevDeclInScope != nullptr) {
16490 auto *PrevDRDInScope = PrevDRD =
16491 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
16492 do {
16493 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
16494 PrevDRDInScope->getLocation();
16495 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
16496 } while (PrevDRDInScope != nullptr);
16497 }
Alexey Bataeve3727102018-04-18 15:57:46 +000016498 for (const auto &TyData : ReductionTypes) {
16499 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016500 bool Invalid = false;
16501 if (I != PreviousRedeclTypes.end()) {
16502 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
16503 << TyData.first;
16504 Diag(I->second, diag::note_previous_definition);
16505 Invalid = true;
16506 }
16507 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
16508 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
16509 Name, TyData.first, PrevDRD);
16510 DC->addDecl(DRD);
16511 DRD->setAccess(AS);
16512 Decls.push_back(DRD);
16513 if (Invalid)
16514 DRD->setInvalidDecl();
16515 else
16516 PrevDRD = DRD;
16517 }
16518
16519 return DeclGroupPtrTy::make(
16520 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16521}
16522
16523void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16524 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16525
16526 // Enter new function scope.
16527 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016528 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016529 getCurFunction()->setHasOMPDeclareReductionCombiner();
16530
16531 if (S != nullptr)
16532 PushDeclContext(S, DRD);
16533 else
16534 CurContext = DRD;
16535
Faisal Valid143a0c2017-04-01 21:30:49 +000016536 PushExpressionEvaluationContext(
16537 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016538
16539 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016540 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16541 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16542 // uses semantics of argument handles by value, but it should be passed by
16543 // reference. C lang does not support references, so pass all parameters as
16544 // pointers.
16545 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016546 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016547 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016548 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16549 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16550 // uses semantics of argument handles by value, but it should be passed by
16551 // reference. C lang does not support references, so pass all parameters as
16552 // pointers.
16553 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016554 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016555 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16556 if (S != nullptr) {
16557 PushOnScopeChains(OmpInParm, S);
16558 PushOnScopeChains(OmpOutParm, S);
16559 } else {
16560 DRD->addDecl(OmpInParm);
16561 DRD->addDecl(OmpOutParm);
16562 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016563 Expr *InE =
16564 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16565 Expr *OutE =
16566 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16567 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016568}
16569
16570void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16571 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16572 DiscardCleanupsInEvaluationContext();
16573 PopExpressionEvaluationContext();
16574
16575 PopDeclContext();
16576 PopFunctionScopeInfo();
16577
16578 if (Combiner != nullptr)
16579 DRD->setCombiner(Combiner);
16580 else
16581 DRD->setInvalidDecl();
16582}
16583
Alexey Bataev070f43a2017-09-06 14:49:58 +000016584VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016585 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16586
16587 // Enter new function scope.
16588 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016589 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016590
16591 if (S != nullptr)
16592 PushDeclContext(S, DRD);
16593 else
16594 CurContext = DRD;
16595
Faisal Valid143a0c2017-04-01 21:30:49 +000016596 PushExpressionEvaluationContext(
16597 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016598
16599 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016600 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16601 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16602 // uses semantics of argument handles by value, but it should be passed by
16603 // reference. C lang does not support references, so pass all parameters as
16604 // pointers.
16605 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016606 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016607 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016608 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16609 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16610 // uses semantics of argument handles by value, but it should be passed by
16611 // reference. C lang does not support references, so pass all parameters as
16612 // pointers.
16613 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016614 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016615 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016616 if (S != nullptr) {
16617 PushOnScopeChains(OmpPrivParm, S);
16618 PushOnScopeChains(OmpOrigParm, S);
16619 } else {
16620 DRD->addDecl(OmpPrivParm);
16621 DRD->addDecl(OmpOrigParm);
16622 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016623 Expr *OrigE =
16624 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16625 Expr *PrivE =
16626 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16627 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016628 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016629}
16630
Alexey Bataev070f43a2017-09-06 14:49:58 +000016631void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16632 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016633 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16634 DiscardCleanupsInEvaluationContext();
16635 PopExpressionEvaluationContext();
16636
16637 PopDeclContext();
16638 PopFunctionScopeInfo();
16639
Alexey Bataev070f43a2017-09-06 14:49:58 +000016640 if (Initializer != nullptr) {
16641 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16642 } else if (OmpPrivParm->hasInit()) {
16643 DRD->setInitializer(OmpPrivParm->getInit(),
16644 OmpPrivParm->isDirectInit()
16645 ? OMPDeclareReductionDecl::DirectInit
16646 : OMPDeclareReductionDecl::CopyInit);
16647 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016648 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016649 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016650}
16651
16652Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16653 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016654 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016655 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016656 if (S)
16657 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16658 /*AddToContext=*/false);
16659 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016660 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016661 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016662 }
16663 return DeclReductions;
16664}
16665
Michael Kruse251e1482019-02-01 20:25:04 +000016666TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16667 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16668 QualType T = TInfo->getType();
16669 if (D.isInvalidType())
16670 return true;
16671
16672 if (getLangOpts().CPlusPlus) {
16673 // Check that there are no default arguments (C++ only).
16674 CheckExtraCXXDefaultArguments(D);
16675 }
16676
16677 return CreateParsedType(T, TInfo);
16678}
16679
16680QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16681 TypeResult ParsedType) {
16682 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16683
16684 QualType MapperType = GetTypeFromParser(ParsedType.get());
16685 assert(!MapperType.isNull() && "Expect valid mapper type");
16686
16687 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16688 // The type must be of struct, union or class type in C and C++
16689 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16690 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16691 return QualType();
16692 }
16693 return MapperType;
16694}
16695
16696OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16697 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16698 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16699 Decl *PrevDeclInScope) {
16700 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16701 forRedeclarationInCurContext());
16702 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16703 // A mapper-identifier may not be redeclared in the current scope for the
16704 // same type or for a type that is compatible according to the base language
16705 // rules.
16706 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16707 OMPDeclareMapperDecl *PrevDMD = nullptr;
16708 bool InCompoundScope = true;
16709 if (S != nullptr) {
16710 // Find previous declaration with the same name not referenced in other
16711 // declarations.
16712 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16713 InCompoundScope =
16714 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16715 LookupName(Lookup, S);
16716 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16717 /*AllowInlineNamespace=*/false);
16718 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16719 LookupResult::Filter Filter = Lookup.makeFilter();
16720 while (Filter.hasNext()) {
16721 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16722 if (InCompoundScope) {
16723 auto I = UsedAsPrevious.find(PrevDecl);
16724 if (I == UsedAsPrevious.end())
16725 UsedAsPrevious[PrevDecl] = false;
16726 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16727 UsedAsPrevious[D] = true;
16728 }
16729 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16730 PrevDecl->getLocation();
16731 }
16732 Filter.done();
16733 if (InCompoundScope) {
16734 for (const auto &PrevData : UsedAsPrevious) {
16735 if (!PrevData.second) {
16736 PrevDMD = PrevData.first;
16737 break;
16738 }
16739 }
16740 }
16741 } else if (PrevDeclInScope) {
16742 auto *PrevDMDInScope = PrevDMD =
16743 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16744 do {
16745 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16746 PrevDMDInScope->getLocation();
16747 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16748 } while (PrevDMDInScope != nullptr);
16749 }
16750 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16751 bool Invalid = false;
16752 if (I != PreviousRedeclTypes.end()) {
16753 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16754 << MapperType << Name;
16755 Diag(I->second, diag::note_previous_definition);
16756 Invalid = true;
16757 }
16758 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16759 MapperType, VN, PrevDMD);
16760 DC->addDecl(DMD);
16761 DMD->setAccess(AS);
16762 if (Invalid)
16763 DMD->setInvalidDecl();
16764
16765 // Enter new function scope.
16766 PushFunctionScope();
16767 setFunctionHasBranchProtectedScope();
16768
16769 CurContext = DMD;
16770
16771 return DMD;
16772}
16773
16774void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16775 Scope *S,
16776 QualType MapperType,
16777 SourceLocation StartLoc,
16778 DeclarationName VN) {
16779 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16780 if (S)
16781 PushOnScopeChains(VD, S);
16782 else
16783 DMD->addDecl(VD);
16784 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16785 DMD->setMapperVarRef(MapperVarRefExpr);
16786}
16787
16788Sema::DeclGroupPtrTy
16789Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16790 ArrayRef<OMPClause *> ClauseList) {
16791 PopDeclContext();
16792 PopFunctionScopeInfo();
16793
16794 if (D) {
16795 if (S)
16796 PushOnScopeChains(D, S, /*AddToContext=*/false);
16797 D->CreateClauses(Context, ClauseList);
16798 }
16799
16800 return DeclGroupPtrTy::make(DeclGroupRef(D));
16801}
16802
David Majnemer9d168222016-08-05 17:44:54 +000016803OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016804 SourceLocation StartLoc,
16805 SourceLocation LParenLoc,
16806 SourceLocation EndLoc) {
16807 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016808 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016809
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016810 // OpenMP [teams Constrcut, Restrictions]
16811 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016812 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016813 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016814 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016815
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016816 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016817 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016818 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016819 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016820 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016821 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016822 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16823 HelperValStmt = buildPreInits(Context, Captures);
16824 }
16825
16826 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16827 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016828}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016829
16830OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16831 SourceLocation StartLoc,
16832 SourceLocation LParenLoc,
16833 SourceLocation EndLoc) {
16834 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016835 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016836
16837 // OpenMP [teams Constrcut, Restrictions]
16838 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016839 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016840 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016841 return nullptr;
16842
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016843 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016844 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16845 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016846 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016847 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016848 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016849 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16850 HelperValStmt = buildPreInits(Context, Captures);
16851 }
16852
16853 return new (Context) OMPThreadLimitClause(
16854 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016855}
Alexey Bataeva0569352015-12-01 10:17:31 +000016856
16857OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16858 SourceLocation StartLoc,
16859 SourceLocation LParenLoc,
16860 SourceLocation EndLoc) {
16861 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016862 Stmt *HelperValStmt = nullptr;
16863 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016864
16865 // OpenMP [2.9.1, task Constrcut]
16866 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016867 if (!isNonNegativeIntegerValue(
16868 ValExpr, *this, OMPC_priority,
16869 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16870 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016871 return nullptr;
16872
Alexey Bataev31ba4762019-10-16 18:09:37 +000016873 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16874 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016875}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016876
16877OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16878 SourceLocation StartLoc,
16879 SourceLocation LParenLoc,
16880 SourceLocation EndLoc) {
16881 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016882 Stmt *HelperValStmt = nullptr;
16883 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016884
16885 // OpenMP [2.9.2, taskloop Constrcut]
16886 // The parameter of the grainsize clause must be a positive integer
16887 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016888 if (!isNonNegativeIntegerValue(
16889 ValExpr, *this, OMPC_grainsize,
16890 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16891 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016892 return nullptr;
16893
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016894 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16895 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016896}
Alexey Bataev382967a2015-12-08 12:06:20 +000016897
16898OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16899 SourceLocation StartLoc,
16900 SourceLocation LParenLoc,
16901 SourceLocation EndLoc) {
16902 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016903 Stmt *HelperValStmt = nullptr;
16904 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016905
16906 // OpenMP [2.9.2, taskloop Constrcut]
16907 // The parameter of the num_tasks clause must be a positive integer
16908 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016909 if (!isNonNegativeIntegerValue(
16910 ValExpr, *this, OMPC_num_tasks,
16911 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16912 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016913 return nullptr;
16914
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016915 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16916 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016917}
16918
Alexey Bataev28c75412015-12-15 08:19:24 +000016919OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16920 SourceLocation LParenLoc,
16921 SourceLocation EndLoc) {
16922 // OpenMP [2.13.2, critical construct, Description]
16923 // ... where hint-expression is an integer constant expression that evaluates
16924 // to a valid lock hint.
16925 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16926 if (HintExpr.isInvalid())
16927 return nullptr;
16928 return new (Context)
16929 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16930}
16931
Carlo Bertollib4adf552016-01-15 18:50:31 +000016932OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16933 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16934 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16935 SourceLocation EndLoc) {
16936 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16937 std::string Values;
16938 Values += "'";
16939 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16940 Values += "'";
16941 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16942 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16943 return nullptr;
16944 }
16945 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016946 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016947 if (ChunkSize) {
16948 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16949 !ChunkSize->isInstantiationDependent() &&
16950 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016951 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016952 ExprResult Val =
16953 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16954 if (Val.isInvalid())
16955 return nullptr;
16956
16957 ValExpr = Val.get();
16958
16959 // OpenMP [2.7.1, Restrictions]
16960 // chunk_size must be a loop invariant integer expression with a positive
16961 // value.
16962 llvm::APSInt Result;
16963 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16964 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16965 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16966 << "dist_schedule" << ChunkSize->getSourceRange();
16967 return nullptr;
16968 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016969 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016970 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16971 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016972 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016973 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016974 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016975 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16976 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016977 }
16978 }
16979 }
16980
16981 return new (Context)
16982 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016983 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016984}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016985
16986OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16987 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16988 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16989 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016990 if (getLangOpts().OpenMP < 50) {
16991 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16992 Kind != OMPC_DEFAULTMAP_scalar) {
16993 std::string Value;
16994 SourceLocation Loc;
16995 Value += "'";
16996 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16997 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16998 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16999 Loc = MLoc;
17000 } else {
17001 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
17002 OMPC_DEFAULTMAP_scalar);
17003 Loc = KindLoc;
17004 }
17005 Value += "'";
17006 Diag(Loc, diag::err_omp_unexpected_clause_value)
17007 << Value << getOpenMPClauseName(OMPC_defaultmap);
17008 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000017009 }
cchene06f3e02019-11-15 13:02:06 -050017010 } else {
17011 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
17012 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
17013 if (!isDefaultmapKind || !isDefaultmapModifier) {
17014 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
17015 "'firstprivate', 'none', 'default'";
17016 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
17017 if (!isDefaultmapKind && isDefaultmapModifier) {
17018 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
17019 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
17020 } else if (isDefaultmapKind && !isDefaultmapModifier) {
17021 Diag(MLoc, diag::err_omp_unexpected_clause_value)
17022 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
17023 } else {
17024 Diag(MLoc, diag::err_omp_unexpected_clause_value)
17025 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
17026 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
17027 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
17028 }
17029 return nullptr;
17030 }
17031
17032 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
17033 // At most one defaultmap clause for each category can appear on the
17034 // directive.
17035 if (DSAStack->checkDefaultmapCategory(Kind)) {
17036 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
17037 return nullptr;
17038 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000017039 }
cchene06f3e02019-11-15 13:02:06 -050017040 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000017041
17042 return new (Context)
17043 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
17044}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017045
17046bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
17047 DeclContext *CurLexicalContext = getCurLexicalContext();
17048 if (!CurLexicalContext->isFileContext() &&
17049 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000017050 !CurLexicalContext->isExternCXXContext() &&
17051 !isa<CXXRecordDecl>(CurLexicalContext) &&
17052 !isa<ClassTemplateDecl>(CurLexicalContext) &&
17053 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
17054 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017055 Diag(Loc, diag::err_omp_region_not_file_context);
17056 return false;
17057 }
Kelvin Libc38e632018-09-10 02:07:09 +000017058 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017059 return true;
17060}
17061
17062void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000017063 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017064 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000017065 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017066}
17067
Alexey Bataev729e2422019-08-23 16:11:14 +000017068NamedDecl *
17069Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
17070 const DeclarationNameInfo &Id,
17071 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017072 LookupResult Lookup(*this, Id, LookupOrdinaryName);
17073 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
17074
17075 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000017076 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017077 Lookup.suppressDiagnostics();
17078
17079 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000017080 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017081 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000017082 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017083 CTK_ErrorRecovery)) {
17084 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
17085 << Id.getName());
17086 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000017087 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017088 }
17089
17090 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000017091 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017092 }
17093
17094 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000017095 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
17096 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017097 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000017098 return nullptr;
17099 }
17100 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
17101 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
17102 return ND;
17103}
17104
17105void Sema::ActOnOpenMPDeclareTargetName(
17106 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
17107 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
17108 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
17109 isa<FunctionTemplateDecl>(ND)) &&
17110 "Expected variable, function or function template.");
17111
17112 // Diagnose marking after use as it may lead to incorrect diagnosis and
17113 // codegen.
17114 if (LangOpts.OpenMP >= 50 &&
17115 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
17116 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
17117
17118 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17119 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
17120 if (DevTy.hasValue() && *DevTy != DT) {
17121 Diag(Loc, diag::err_omp_device_type_mismatch)
17122 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
17123 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
17124 return;
17125 }
17126 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
17127 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
17128 if (!Res) {
17129 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
17130 SourceRange(Loc, Loc));
17131 ND->addAttr(A);
17132 if (ASTMutationListener *ML = Context.getASTMutationListener())
17133 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
17134 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
17135 } else if (*Res != MT) {
17136 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000017137 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000017138}
17139
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017140static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
17141 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000017142 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017143 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000017144 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000017145 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
17146 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
17147 if (SemaRef.LangOpts.OpenMP >= 50 &&
17148 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
17149 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
17150 VD->hasGlobalStorage()) {
17151 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
17152 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
17153 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
17154 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
17155 // If a lambda declaration and definition appears between a
17156 // declare target directive and the matching end declare target
17157 // directive, all variables that are captured by the lambda
17158 // expression must also appear in a to clause.
17159 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000017160 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000017161 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
17162 << VD << 0 << SR;
17163 return;
17164 }
17165 }
17166 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000017167 return;
17168 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
17169 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017170}
17171
17172static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
17173 Sema &SemaRef, DSAStackTy *Stack,
17174 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000017175 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000017176 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
17177 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017178}
17179
Kelvin Li1ce87c72017-12-12 20:08:12 +000017180void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
17181 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017182 if (!D || D->isInvalidDecl())
17183 return;
17184 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000017185 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000017186 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000017187 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000017188 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
17189 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000017190 return;
17191 // 2.10.6: threadprivate variable cannot appear in a declare target
17192 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017193 if (DSAStack->isThreadPrivate(VD)) {
17194 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000017195 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017196 return;
17197 }
17198 }
Alexey Bataev97b72212018-08-14 18:31:20 +000017199 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
17200 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017201 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000017202 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
17203 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017204 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000017205 Diag(IdLoc, diag::err_omp_function_in_link_clause);
17206 Diag(FD->getLocation(), diag::note_defined_here) << FD;
17207 return;
17208 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017209 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000017210 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17211 OMPDeclareTargetDeclAttr::getDeviceType(FD);
17212 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
17213 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017214 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000017215 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
17216 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
17217 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000017218 }
Alexey Bataev30a78212018-09-11 13:59:10 +000017219 if (auto *VD = dyn_cast<ValueDecl>(D)) {
17220 // Problem if any with var declared with incomplete type will be reported
17221 // as normal, so no need to check it here.
17222 if ((E || !VD->getType()->isIncompleteType()) &&
17223 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
17224 return;
17225 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
17226 // Checking declaration inside declare target region.
17227 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
17228 isa<FunctionTemplateDecl>(D)) {
17229 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000017230 Context, OMPDeclareTargetDeclAttr::MT_To,
17231 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000017232 D->addAttr(A);
17233 if (ASTMutationListener *ML = Context.getASTMutationListener())
17234 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
17235 }
17236 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017237 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017238 }
Alexey Bataev30a78212018-09-11 13:59:10 +000017239 if (!E)
17240 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017241 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
17242}
Samuel Antao661c0902016-05-26 17:39:58 +000017243
17244OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000017245 CXXScopeSpec &MapperIdScopeSpec,
17246 DeclarationNameInfo &MapperId,
17247 const OMPVarListLocTy &Locs,
17248 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000017249 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017250 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
17251 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000017252 if (MVLI.ProcessedVarList.empty())
17253 return nullptr;
17254
Michael Kruse01f670d2019-02-22 22:29:42 +000017255 return OMPToClause::Create(
17256 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17257 MVLI.VarComponents, MVLI.UDMapperList,
17258 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000017259}
Samuel Antaoec172c62016-05-26 17:49:04 +000017260
17261OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000017262 CXXScopeSpec &MapperIdScopeSpec,
17263 DeclarationNameInfo &MapperId,
17264 const OMPVarListLocTy &Locs,
17265 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000017266 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017267 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
17268 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000017269 if (MVLI.ProcessedVarList.empty())
17270 return nullptr;
17271
Michael Kruse0336c752019-02-25 20:34:15 +000017272 return OMPFromClause::Create(
17273 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17274 MVLI.VarComponents, MVLI.UDMapperList,
17275 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000017276}
Carlo Bertolli2404b172016-07-13 15:37:16 +000017277
17278OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017279 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000017280 MappableVarListInfo MVLI(VarList);
17281 SmallVector<Expr *, 8> PrivateCopies;
17282 SmallVector<Expr *, 8> Inits;
17283
Alexey Bataeve3727102018-04-18 15:57:46 +000017284 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017285 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
17286 SourceLocation ELoc;
17287 SourceRange ERange;
17288 Expr *SimpleRefExpr = RefExpr;
17289 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17290 if (Res.second) {
17291 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000017292 MVLI.ProcessedVarList.push_back(RefExpr);
17293 PrivateCopies.push_back(nullptr);
17294 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017295 }
17296 ValueDecl *D = Res.first;
17297 if (!D)
17298 continue;
17299
17300 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000017301 Type = Type.getNonReferenceType().getUnqualifiedType();
17302
17303 auto *VD = dyn_cast<VarDecl>(D);
17304
17305 // Item should be a pointer or reference to pointer.
17306 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017307 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
17308 << 0 << RefExpr->getSourceRange();
17309 continue;
17310 }
Samuel Antaocc10b852016-07-28 14:23:26 +000017311
17312 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000017313 auto VDPrivate =
17314 buildVarDecl(*this, ELoc, Type, D->getName(),
17315 D->hasAttrs() ? &D->getAttrs() : nullptr,
17316 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000017317 if (VDPrivate->isInvalidDecl())
17318 continue;
17319
17320 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000017321 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000017322 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
17323
17324 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000017325 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000017326 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000017327 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
17328 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000017329 AddInitializerToDecl(VDPrivate,
17330 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000017331 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000017332
17333 // If required, build a capture to implement the privatization initialized
17334 // with the current list item value.
17335 DeclRefExpr *Ref = nullptr;
17336 if (!VD)
17337 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17338 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
17339 PrivateCopies.push_back(VDPrivateRefExpr);
17340 Inits.push_back(VDInitRefExpr);
17341
17342 // We need to add a data sharing attribute for this variable to make sure it
17343 // is correctly captured. A variable that shows up in a use_device_ptr has
17344 // similar properties of a first private variable.
17345 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
17346
17347 // Create a mappable component for the list item. List items in this clause
17348 // only need a component.
17349 MVLI.VarBaseDeclarations.push_back(D);
17350 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17351 MVLI.VarComponents.back().push_back(
17352 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000017353 }
17354
Samuel Antaocc10b852016-07-28 14:23:26 +000017355 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000017356 return nullptr;
17357
Samuel Antaocc10b852016-07-28 14:23:26 +000017358 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000017359 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
17360 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017361}
Carlo Bertolli70594e92016-07-13 17:16:49 +000017362
17363OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017364 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000017365 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000017366 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000017367 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000017368 SourceLocation ELoc;
17369 SourceRange ERange;
17370 Expr *SimpleRefExpr = RefExpr;
17371 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17372 if (Res.second) {
17373 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000017374 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017375 }
17376 ValueDecl *D = Res.first;
17377 if (!D)
17378 continue;
17379
17380 QualType Type = D->getType();
17381 // item should be a pointer or array or reference to pointer or array
17382 if (!Type.getNonReferenceType()->isPointerType() &&
17383 !Type.getNonReferenceType()->isArrayType()) {
17384 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
17385 << 0 << RefExpr->getSourceRange();
17386 continue;
17387 }
Samuel Antao6890b092016-07-28 14:25:09 +000017388
17389 // Check if the declaration in the clause does not show up in any data
17390 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000017391 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000017392 if (isOpenMPPrivate(DVar.CKind)) {
17393 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17394 << getOpenMPClauseName(DVar.CKind)
17395 << getOpenMPClauseName(OMPC_is_device_ptr)
17396 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000017397 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000017398 continue;
17399 }
17400
Alexey Bataeve3727102018-04-18 15:57:46 +000017401 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000017402 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000017403 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000017404 [&ConflictExpr](
17405 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
17406 OpenMPClauseKind) -> bool {
17407 ConflictExpr = R.front().getAssociatedExpression();
17408 return true;
17409 })) {
17410 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
17411 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
17412 << ConflictExpr->getSourceRange();
17413 continue;
17414 }
17415
17416 // Store the components in the stack so that they can be used to check
17417 // against other clauses later on.
17418 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
17419 DSAStack->addMappableExpressionComponents(
17420 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
17421
17422 // Record the expression we've just processed.
17423 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
17424
17425 // Create a mappable component for the list item. List items in this clause
17426 // only need a component. We use a null declaration to signal fields in
17427 // 'this'.
17428 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
17429 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
17430 "Unexpected device pointer expression!");
17431 MVLI.VarBaseDeclarations.push_back(
17432 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
17433 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17434 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017435 }
17436
Samuel Antao6890b092016-07-28 14:25:09 +000017437 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000017438 return nullptr;
17439
Michael Kruse4304e9d2019-02-19 16:38:20 +000017440 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
17441 MVLI.VarBaseDeclarations,
17442 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017443}
Alexey Bataeve04483e2019-03-27 14:14:31 +000017444
17445OMPClause *Sema::ActOnOpenMPAllocateClause(
17446 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17447 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
17448 if (Allocator) {
17449 // OpenMP [2.11.4 allocate Clause, Description]
17450 // allocator is an expression of omp_allocator_handle_t type.
17451 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
17452 return nullptr;
17453
17454 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
17455 if (AllocatorRes.isInvalid())
17456 return nullptr;
17457 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
17458 DSAStack->getOMPAllocatorHandleT(),
17459 Sema::AA_Initializing,
17460 /*AllowExplicit=*/true);
17461 if (AllocatorRes.isInvalid())
17462 return nullptr;
17463 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000017464 } else {
17465 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
17466 // allocate clauses that appear on a target construct or on constructs in a
17467 // target region must specify an allocator expression unless a requires
17468 // directive with the dynamic_allocators clause is present in the same
17469 // compilation unit.
17470 if (LangOpts.OpenMPIsDevice &&
17471 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
17472 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017473 }
17474 // Analyze and build list of variables.
17475 SmallVector<Expr *, 8> Vars;
17476 for (Expr *RefExpr : VarList) {
17477 assert(RefExpr && "NULL expr in OpenMP private clause.");
17478 SourceLocation ELoc;
17479 SourceRange ERange;
17480 Expr *SimpleRefExpr = RefExpr;
17481 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17482 if (Res.second) {
17483 // It will be analyzed later.
17484 Vars.push_back(RefExpr);
17485 }
17486 ValueDecl *D = Res.first;
17487 if (!D)
17488 continue;
17489
17490 auto *VD = dyn_cast<VarDecl>(D);
17491 DeclRefExpr *Ref = nullptr;
17492 if (!VD && !CurContext->isDependentContext())
17493 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17494 Vars.push_back((VD || CurContext->isDependentContext())
17495 ? RefExpr->IgnoreParens()
17496 : Ref);
17497 }
17498
17499 if (Vars.empty())
17500 return nullptr;
17501
Alexey Bataevf3c508f2020-01-23 10:47:16 -050017502 if (Allocator)
17503 DSAStack->addInnerAllocatorExpr(Allocator);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017504 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
17505 ColonLoc, EndLoc, Vars);
17506}
Alexey Bataevb6e70842019-12-16 15:54:17 -050017507
17508OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
17509 SourceLocation StartLoc,
17510 SourceLocation LParenLoc,
17511 SourceLocation EndLoc) {
17512 SmallVector<Expr *, 8> Vars;
17513 for (Expr *RefExpr : VarList) {
17514 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
17515 SourceLocation ELoc;
17516 SourceRange ERange;
17517 Expr *SimpleRefExpr = RefExpr;
17518 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17519 if (Res.second)
17520 // It will be analyzed later.
17521 Vars.push_back(RefExpr);
17522 ValueDecl *D = Res.first;
17523 if (!D)
17524 continue;
17525
Alexey Bataevb6e70842019-12-16 15:54:17 -050017526 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
17527 // A list-item cannot appear in more than one nontemporal clause.
17528 if (const Expr *PrevRef =
17529 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
17530 Diag(ELoc, diag::err_omp_used_in_clause_twice)
17531 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
17532 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17533 << getOpenMPClauseName(OMPC_nontemporal);
17534 continue;
17535 }
17536
Alexey Bataev0860db92019-12-19 10:01:10 -050017537 Vars.push_back(RefExpr);
Alexey Bataevb6e70842019-12-16 15:54:17 -050017538 }
17539
17540 if (Vars.empty())
17541 return nullptr;
17542
17543 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17544 Vars);
17545}