blob: 72afe63749acf725f052d5aad3a2778207a9bf85 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev0ee89c12019-12-12 14:13:02 -050026#include "clang/Basic/PartialDiagnostic.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000027#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000028#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000031#include "clang/Sema/SemaInternal.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060032#include "llvm/ADT/IndexedMap.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000033#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataev36635632020-01-17 20:39:04 -050034#include "llvm/ADT/STLExtras.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060035#include "llvm/Frontend/OpenMP/OMPConstants.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000036using namespace clang;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060037using namespace llvm::omp;
Alexey Bataeva769e072013-03-22 06:34:35 +000038
Alexey Bataev758e55e2013-09-06 18:03:48 +000039//===----------------------------------------------------------------------===//
40// Stack of data-sharing attributes for variables
41//===----------------------------------------------------------------------===//
42
Alexey Bataeve3727102018-04-18 15:57:46 +000043static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000044 Sema &SemaRef, Expr *E,
45 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000046 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000049/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000050enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000051 DSA_unspecified = 0, /// Data sharing attribute not specified.
52 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
53 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000054};
55
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000056/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000057/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000058class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000059public:
Alexey Bataeve3727102018-04-18 15:57:46 +000060 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000061 OpenMPDirectiveKind DKind = OMPD_unknown;
62 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000063 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000065 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000066 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000067 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
68 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
69 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000070 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000072 };
Alexey Bataeve3727102018-04-18 15:57:46 +000073 using OperatorOffsetTy =
74 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000075 using DoacrossDependMapTy =
76 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000077
Alexey Bataev758e55e2013-09-06 18:03:48 +000078private:
Alexey Bataeve3727102018-04-18 15:57:46 +000079 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000080 OpenMPClauseKind Attributes = OMPC_unknown;
81 /// Pointer to a reference expression and a flag which shows that the
82 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000083 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000084 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000085 };
Alexey Bataeve3727102018-04-18 15:57:46 +000086 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
Alexey Bataevb6e70842019-12-16 15:54:17 -050087 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
Alexey Bataeve3727102018-04-18 15:57:46 +000088 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
89 using LoopControlVariablesMapTy =
90 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000091 /// Struct that associates a component with the clause kind where they are
92 /// found.
93 struct MappedExprComponentTy {
94 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
95 OpenMPClauseKind Kind = OMPC_unknown;
96 };
Alexey Bataeve3727102018-04-18 15:57:46 +000097 using MappedExprComponentsTy =
98 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
99 using CriticalsWithHintsTy =
100 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000101 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000102 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000103 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000104 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000105 ReductionData() = default;
106 void set(BinaryOperatorKind BO, SourceRange RR) {
107 ReductionRange = RR;
108 ReductionOp = BO;
109 }
110 void set(const Expr *RefExpr, SourceRange RR) {
111 ReductionRange = RR;
112 ReductionOp = RefExpr;
113 }
114 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000115 using DeclReductionMapTy =
116 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
cchene06f3e02019-11-15 13:02:06 -0500117 struct DefaultmapInfo {
118 OpenMPDefaultmapClauseModifier ImplicitBehavior =
119 OMPC_DEFAULTMAP_MODIFIER_unknown;
120 SourceLocation SLoc;
121 DefaultmapInfo() = default;
122 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
123 : ImplicitBehavior(M), SLoc(Loc) {}
124 };
Alexey Bataev758e55e2013-09-06 18:03:48 +0000125
Alexey Bataeve3727102018-04-18 15:57:46 +0000126 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000127 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000128 DeclReductionMapTy ReductionMap;
Alexey Bataevb6e70842019-12-16 15:54:17 -0500129 UsedRefMapTy AlignedMap;
130 UsedRefMapTy NontemporalMap;
Samuel Antao90927002016-04-26 14:54:23 +0000131 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000132 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000133 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000134 SourceLocation DefaultAttrLoc;
cchene06f3e02019-11-15 13:02:06 -0500135 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000136 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000137 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000138 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000139 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000140 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
141 /// get the data (loop counters etc.) about enclosing loop-based construct.
142 /// This data is required during codegen.
143 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000144 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000145 /// 'ordered' clause, the second one is true if the regions has 'ordered'
146 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000147 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000148 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000149 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000150 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000151 bool NowaitRegion = false;
152 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000153 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000154 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000155 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000156 /// Reference to the taskgroup task_reduction reference expression.
157 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000158 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000159 /// List of globals marked as declare target link in this target region
160 /// (isOpenMPTargetExecutionDirective(Directive) == true).
161 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000162 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000163 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000164 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
165 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000166 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000167 };
168
Alexey Bataeve3727102018-04-18 15:57:46 +0000169 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000170
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000171 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000172 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000173 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
174 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000175 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000176 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000177 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000178 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000179 bool ForceCapturing = false;
Alexey Bataevd1caf932019-09-30 14:05:26 +0000180 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000181 /// captured by reference.
182 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000183 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000184 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000185
Richard Smith375dec52019-05-30 23:21:14 +0000186 /// Iterators over the stack iterate in order from innermost to outermost
187 /// directive.
188 using const_iterator = StackTy::const_reverse_iterator;
189 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000190 return Stack.empty() ? const_iterator()
191 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000192 }
193 const_iterator end() const {
194 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
195 }
196 using iterator = StackTy::reverse_iterator;
197 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000198 return Stack.empty() ? iterator()
199 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000200 }
201 iterator end() {
202 return Stack.empty() ? iterator() : Stack.back().first.rend();
203 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000204
Richard Smith375dec52019-05-30 23:21:14 +0000205 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000206
Alexey Bataev4b465392017-04-26 15:06:24 +0000207 bool isStackEmpty() const {
208 return Stack.empty() ||
209 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000210 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000211 }
Richard Smith375dec52019-05-30 23:21:14 +0000212 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000213 return isStackEmpty() ? 0
214 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000215 }
216
217 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000218 size_t Size = getStackSize();
219 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000220 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000221 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000222 }
223 const SharingMapTy *getTopOfStackOrNull() const {
224 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
225 }
226 SharingMapTy &getTopOfStack() {
227 assert(!isStackEmpty() && "no current directive");
228 return *getTopOfStackOrNull();
229 }
230 const SharingMapTy &getTopOfStack() const {
231 return const_cast<DSAStackTy&>(*this).getTopOfStack();
232 }
233
234 SharingMapTy *getSecondOnStackOrNull() {
235 size_t Size = getStackSize();
236 if (Size <= 1)
237 return nullptr;
238 return &Stack.back().first[Size - 2];
239 }
240 const SharingMapTy *getSecondOnStackOrNull() const {
241 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
242 }
243
244 /// Get the stack element at a certain level (previously returned by
245 /// \c getNestingLevel).
246 ///
247 /// Note that nesting levels count from outermost to innermost, and this is
248 /// the reverse of our iteration order where new inner levels are pushed at
249 /// the front of the stack.
250 SharingMapTy &getStackElemAtLevel(unsigned Level) {
251 assert(Level < getStackSize() && "no such stack element");
252 return Stack.back().first[Level];
253 }
254 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
255 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
256 }
257
258 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
259
260 /// Checks if the variable is a local for OpenMP region.
261 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000262
Kelvin Li1408f912018-09-26 04:28:39 +0000263 /// Vector of previously declared requires directives
264 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000265 /// omp_allocator_handle_t type.
266 QualType OMPAllocatorHandleT;
267 /// Expression for the predefined allocators.
268 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
269 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000270 /// Vector of previously encountered target directives
271 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000272
Alexey Bataev758e55e2013-09-06 18:03:48 +0000273public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000274 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000275
Alexey Bataev27ef9512019-03-20 20:14:22 +0000276 /// Sets omp_allocator_handle_t type.
277 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
278 /// Gets omp_allocator_handle_t type.
279 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
280 /// Sets the given default allocator.
281 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
282 Expr *Allocator) {
283 OMPPredefinedAllocators[AllocatorKind] = Allocator;
284 }
285 /// Returns the specified default allocator.
286 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
287 return OMPPredefinedAllocators[AllocatorKind];
288 }
289
Alexey Bataevaac108a2015-06-23 04:51:00 +0000290 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000291 OpenMPClauseKind getClauseParsingMode() const {
292 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
293 return ClauseKindMode;
294 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000295 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000296
Richard Smith0621a8f2019-05-31 00:45:10 +0000297 bool isBodyComplete() const {
298 const SharingMapTy *Top = getTopOfStackOrNull();
299 return Top && Top->BodyComplete;
300 }
301 void setBodyComplete() {
302 getTopOfStack().BodyComplete = true;
303 }
304
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000305 bool isForceVarCapturing() const { return ForceCapturing; }
306 void setForceVarCapturing(bool V) { ForceCapturing = V; }
307
Alexey Bataev60705422018-10-30 15:50:12 +0000308 void setForceCaptureByReferenceInTargetExecutable(bool V) {
309 ForceCaptureByReferenceInTargetExecutable = V;
310 }
311 bool isForceCaptureByReferenceInTargetExecutable() const {
312 return ForceCaptureByReferenceInTargetExecutable;
313 }
314
Alexey Bataev758e55e2013-09-06 18:03:48 +0000315 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000316 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000317 assert(!IgnoredStackElements &&
318 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000319 if (Stack.empty() ||
320 Stack.back().second != CurrentNonCapturingFunctionScope)
321 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
322 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
323 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000324 }
325
326 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000327 assert(!IgnoredStackElements &&
328 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000329 assert(!Stack.back().first.empty() &&
330 "Data-sharing attributes stack is empty!");
331 Stack.back().first.pop_back();
332 }
333
Richard Smith0621a8f2019-05-31 00:45:10 +0000334 /// RAII object to temporarily leave the scope of a directive when we want to
335 /// logically operate in its parent.
336 class ParentDirectiveScope {
337 DSAStackTy &Self;
338 bool Active;
339 public:
340 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
341 : Self(Self), Active(false) {
342 if (Activate)
343 enable();
344 }
345 ~ParentDirectiveScope() { disable(); }
346 void disable() {
347 if (Active) {
348 --Self.IgnoredStackElements;
349 Active = false;
350 }
351 }
352 void enable() {
353 if (!Active) {
354 ++Self.IgnoredStackElements;
355 Active = true;
356 }
357 }
358 };
359
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000360 /// Marks that we're started loop parsing.
361 void loopInit() {
362 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
363 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000364 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000365 }
366 /// Start capturing of the variables in the loop context.
367 void loopStart() {
368 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
369 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000370 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000371 }
372 /// true, if variables are captured, false otherwise.
373 bool isLoopStarted() const {
374 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
375 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000376 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000377 }
378 /// Marks (or clears) declaration as possibly loop counter.
379 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000380 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000381 D ? D->getCanonicalDecl() : D;
382 }
383 /// Gets the possible loop counter decl.
384 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000385 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000386 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000387 /// Start new OpenMP region stack in new non-capturing function.
388 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000389 assert(!IgnoredStackElements &&
390 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000391 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
392 assert(!isa<CapturingScopeInfo>(CurFnScope));
393 CurrentNonCapturingFunctionScope = CurFnScope;
394 }
395 /// Pop region stack for non-capturing function.
396 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000397 assert(!IgnoredStackElements &&
398 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000399 if (!Stack.empty() && Stack.back().second == OldFSI) {
400 assert(Stack.back().first.empty());
401 Stack.pop_back();
402 }
403 CurrentNonCapturingFunctionScope = nullptr;
404 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
405 if (!isa<CapturingScopeInfo>(FSI)) {
406 CurrentNonCapturingFunctionScope = FSI;
407 break;
408 }
409 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000410 }
411
Alexey Bataeve3727102018-04-18 15:57:46 +0000412 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000413 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000414 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000415 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000416 getCriticalWithHint(const DeclarationNameInfo &Name) const {
417 auto I = Criticals.find(Name.getAsString());
418 if (I != Criticals.end())
419 return I->second;
420 return std::make_pair(nullptr, llvm::APSInt());
421 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000422 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000423 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000424 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000425 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexey Bataevb6e70842019-12-16 15:54:17 -0500426 /// If 'nontemporal' declaration for given variable \a D was not seen yet,
427 /// add it and return NULL; otherwise return previous occurrence's expression
428 /// for diagnostics.
429 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000431 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000432 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000434 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000435 /// \return The index of the loop control variable in the list of associated
436 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000437 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000438 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000439 /// parent region.
440 /// \return The index of the loop control variable in the list of associated
441 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000442 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000443 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000444 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000445 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000446
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000448 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000449 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000450
Alexey Bataevfa312f32017-07-21 18:48:21 +0000451 /// Adds additional information for the reduction items with the reduction id
452 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000453 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000454 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000455 /// Adds additional information for the reduction items with the reduction id
456 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000457 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000458 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000459 /// Returns the location and reduction operation from the innermost parent
460 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000461 const DSAVarData
462 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
463 BinaryOperatorKind &BOK,
464 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000465 /// Returns the location and reduction operation from the innermost parent
466 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000467 const DSAVarData
468 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
469 const Expr *&ReductionRef,
470 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000471 /// Return reduction reference expression for the current taskgroup.
472 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000473 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000474 "taskgroup reference expression requested for non taskgroup "
475 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000476 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000477 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000478 /// Checks if the given \p VD declaration is actually a taskgroup reduction
479 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000480 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000481 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
482 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000483 ->getDecl() == VD;
484 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000486 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000487 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000488 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000489 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000490 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000491 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000492 /// match specified \a CPred predicate in any directive which matches \a DPred
493 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000494 const DSAVarData
495 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
496 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
497 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000498 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000499 /// match specified \a CPred predicate in any innermost directive which
500 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000501 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000502 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000503 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
504 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000505 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000506 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000507 /// attributes which match specified \a CPred predicate at the specified
508 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000509 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000510 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000511 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000513 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000514 /// specified \a DPred predicate.
515 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000516 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000517 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000518
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000519 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000520 bool hasDirective(
521 const llvm::function_ref<bool(
522 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
523 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000524 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000525
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000526 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000527 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000528 const SharingMapTy *Top = getTopOfStackOrNull();
529 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000530 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000531 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000532 OpenMPDirectiveKind getDirective(unsigned Level) const {
533 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000534 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000535 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000536 /// Returns the capture region at the specified level.
537 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
538 unsigned OpenMPCaptureLevel) const {
539 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
540 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
541 return CaptureRegions[OpenMPCaptureLevel];
542 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000543 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000544 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000545 const SharingMapTy *Parent = getSecondOnStackOrNull();
546 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000547 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000548
Kelvin Li1408f912018-09-26 04:28:39 +0000549 /// Add requires decl to internal vector
550 void addRequiresDecl(OMPRequiresDecl *RD) {
551 RequiresDecls.push_back(RD);
552 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000553
Alexey Bataev318f431b2019-03-22 15:25:12 +0000554 /// Checks if the defined 'requires' directive has specified type of clause.
555 template <typename ClauseType>
556 bool hasRequiresDeclWithClause() {
557 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
558 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
559 return isa<ClauseType>(C);
560 });
561 });
562 }
563
Kelvin Li1408f912018-09-26 04:28:39 +0000564 /// Checks for a duplicate clause amongst previously declared requires
565 /// directives
566 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
567 bool IsDuplicate = false;
568 for (OMPClause *CNew : ClauseList) {
569 for (const OMPRequiresDecl *D : RequiresDecls) {
570 for (const OMPClause *CPrev : D->clauselists()) {
571 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
572 SemaRef.Diag(CNew->getBeginLoc(),
573 diag::err_omp_requires_clause_redeclaration)
574 << getOpenMPClauseName(CNew->getClauseKind());
575 SemaRef.Diag(CPrev->getBeginLoc(),
576 diag::note_omp_requires_previous_clause)
577 << getOpenMPClauseName(CPrev->getClauseKind());
578 IsDuplicate = true;
579 }
580 }
581 }
582 }
583 return IsDuplicate;
584 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000585
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000586 /// Add location of previously encountered target to internal vector
587 void addTargetDirLocation(SourceLocation LocStart) {
588 TargetLocations.push_back(LocStart);
589 }
590
591 // Return previously encountered target region locations.
592 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
593 return TargetLocations;
594 }
595
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000596 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000597 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000598 getTopOfStack().DefaultAttr = DSA_none;
599 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000600 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000601 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000602 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000603 getTopOfStack().DefaultAttr = DSA_shared;
604 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000605 }
cchene06f3e02019-11-15 13:02:06 -0500606 /// Set default data mapping attribute to Modifier:Kind
607 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
608 OpenMPDefaultmapClauseKind Kind,
609 SourceLocation Loc) {
610 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
611 DMI.ImplicitBehavior = M;
612 DMI.SLoc = Loc;
613 }
614 /// Check whether the implicit-behavior has been set in defaultmap
615 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
616 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
617 OMPC_DEFAULTMAP_MODIFIER_unknown;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000618 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619
620 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000621 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000622 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000623 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000624 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000625 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000626 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000627 }
cchene06f3e02019-11-15 13:02:06 -0500628 OpenMPDefaultmapClauseModifier
629 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
630 return isStackEmpty()
631 ? OMPC_DEFAULTMAP_MODIFIER_unknown
632 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000633 }
cchene06f3e02019-11-15 13:02:06 -0500634 OpenMPDefaultmapClauseModifier
635 getDefaultmapModifierAtLevel(unsigned Level,
636 OpenMPDefaultmapClauseKind Kind) const {
637 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000638 }
cchene06f3e02019-11-15 13:02:06 -0500639 bool isDefaultmapCapturedByRef(unsigned Level,
640 OpenMPDefaultmapClauseKind Kind) const {
641 OpenMPDefaultmapClauseModifier M =
642 getDefaultmapModifierAtLevel(Level, Kind);
643 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
644 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
645 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
646 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
647 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
648 }
649 return true;
650 }
651 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
652 OpenMPDefaultmapClauseKind Kind) {
653 switch (Kind) {
654 case OMPC_DEFAULTMAP_scalar:
655 case OMPC_DEFAULTMAP_pointer:
656 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
657 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
658 (M == OMPC_DEFAULTMAP_MODIFIER_default);
659 case OMPC_DEFAULTMAP_aggregate:
660 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000661 default:
662 break;
cchene06f3e02019-11-15 13:02:06 -0500663 }
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000664 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
cchene06f3e02019-11-15 13:02:06 -0500665 }
666 bool mustBeFirstprivateAtLevel(unsigned Level,
667 OpenMPDefaultmapClauseKind Kind) const {
668 OpenMPDefaultmapClauseModifier M =
669 getDefaultmapModifierAtLevel(Level, Kind);
670 return mustBeFirstprivateBase(M, Kind);
671 }
672 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
673 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
674 return mustBeFirstprivateBase(M, Kind);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000675 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000676
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000677 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000678 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000679 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000680 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000681 }
682
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000683 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000684 void setOrderedRegion(bool IsOrdered, const Expr *Param,
685 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000686 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000687 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000688 else
Richard Smith375dec52019-05-30 23:21:14 +0000689 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000690 }
691 /// Returns true, if region is ordered (has associated 'ordered' clause),
692 /// false - otherwise.
693 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000694 if (const SharingMapTy *Top = getTopOfStackOrNull())
695 return Top->OrderedRegion.hasValue();
696 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000697 }
698 /// Returns optional parameter for the ordered region.
699 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000700 if (const SharingMapTy *Top = getTopOfStackOrNull())
701 if (Top->OrderedRegion.hasValue())
702 return Top->OrderedRegion.getValue();
703 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000704 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000705 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000706 /// 'ordered' clause), false - otherwise.
707 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000708 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
709 return Parent->OrderedRegion.hasValue();
710 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000711 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000712 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000713 std::pair<const Expr *, OMPOrderedClause *>
714 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000715 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
716 if (Parent->OrderedRegion.hasValue())
717 return Parent->OrderedRegion.getValue();
718 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000719 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000720 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000721 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000722 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000723 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000724 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000725 /// 'nowait' clause), false - otherwise.
726 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000727 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
728 return Parent->NowaitRegion;
729 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000730 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000731 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000732 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000733 if (SharingMapTy *Parent = getSecondOnStackOrNull())
734 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000735 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000736 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000737 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000738 const SharingMapTy *Top = getTopOfStackOrNull();
739 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000740 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000741
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000742 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000743 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000744 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000745 if (Val > 1)
746 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000747 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000748 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000749 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000750 const SharingMapTy *Top = getTopOfStackOrNull();
751 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000752 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000753 /// Returns true if the construct is associated with multiple loops.
754 bool hasMutipleLoops() const {
755 const SharingMapTy *Top = getTopOfStackOrNull();
756 return Top ? Top->HasMutipleLoops : false;
757 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000758
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000759 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000760 /// region.
761 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000762 if (SharingMapTy *Parent = getSecondOnStackOrNull())
763 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000764 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000765 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000766 bool hasInnerTeamsRegion() const {
767 return getInnerTeamsRegionLoc().isValid();
768 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000769 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000770 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000771 const SharingMapTy *Top = getTopOfStackOrNull();
772 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000773 }
774
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000775 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000776 const SharingMapTy *Top = getTopOfStackOrNull();
777 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000778 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000779 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000780 const SharingMapTy *Top = getTopOfStackOrNull();
781 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000782 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000783
Samuel Antao4c8035b2016-12-12 18:00:20 +0000784 /// Do the check specified in \a Check to all component lists and return true
785 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000786 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000787 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000788 const llvm::function_ref<
789 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000790 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000791 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000792 if (isStackEmpty())
793 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000794 auto SI = begin();
795 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000796
797 if (SI == SE)
798 return false;
799
Alexey Bataeve3727102018-04-18 15:57:46 +0000800 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000801 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000802 else
803 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000804
805 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000806 auto MI = SI->MappedExprComponents.find(VD);
807 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000808 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
809 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000810 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000811 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000812 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000813 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000814 }
815
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000816 /// Do the check specified in \a Check to all component lists at a given level
817 /// and return true if any issue is found.
818 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000819 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000820 const llvm::function_ref<
821 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000822 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000823 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000824 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000825 return false;
826
Richard Smith375dec52019-05-30 23:21:14 +0000827 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
828 auto MI = StackElem.MappedExprComponents.find(VD);
829 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000830 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
831 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000832 if (Check(L, MI->second.Kind))
833 return true;
834 return false;
835 }
836
Samuel Antao4c8035b2016-12-12 18:00:20 +0000837 /// Create a new mappable expression component list associated with a given
838 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000839 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000840 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000841 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
842 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000843 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000844 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000845 MEC.Components.resize(MEC.Components.size() + 1);
846 MEC.Components.back().append(Components.begin(), Components.end());
847 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000848 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000849
850 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000851 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000852 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000853 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000854 void addDoacrossDependClause(OMPDependClause *C,
855 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000856 SharingMapTy *Parent = getSecondOnStackOrNull();
857 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
858 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000859 }
860 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
861 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000862 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000863 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000864 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000865 return llvm::make_range(Ref.begin(), Ref.end());
866 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000867 return llvm::make_range(StackElem.DoacrossDepends.end(),
868 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000869 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000870
871 // Store types of classes which have been explicitly mapped
872 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000873 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000874 StackElem.MappedClassesQualTypes.insert(QT);
875 }
876
877 // Return set of mapped classes types
878 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000879 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000880 return StackElem.MappedClassesQualTypes.count(QT) != 0;
881 }
882
Alexey Bataeva495c642019-03-11 19:51:42 +0000883 /// Adds global declare target to the parent target region.
884 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
885 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
886 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
887 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000888 for (auto &Elem : *this) {
889 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
890 Elem.DeclareTargetLinkVarDecls.push_back(E);
891 return;
892 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000893 }
894 }
895
896 /// Returns the list of globals with declare target link if current directive
897 /// is target.
898 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
899 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
900 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000901 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000902 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000903};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000904
905bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
906 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
907}
908
909bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000910 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
911 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000912}
Alexey Bataeve3727102018-04-18 15:57:46 +0000913
Alexey Bataeved09d242014-05-28 05:53:51 +0000914} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000915
Alexey Bataeve3727102018-04-18 15:57:46 +0000916static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000917 if (const auto *FE = dyn_cast<FullExpr>(E))
918 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000919
Alexey Bataeve3727102018-04-18 15:57:46 +0000920 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +0100921 E = MTE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000922
Alexey Bataeve3727102018-04-18 15:57:46 +0000923 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000924 E = Binder->getSubExpr();
925
Alexey Bataeve3727102018-04-18 15:57:46 +0000926 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000927 E = ICE->getSubExprAsWritten();
928 return E->IgnoreParens();
929}
930
Alexey Bataeve3727102018-04-18 15:57:46 +0000931static Expr *getExprAsWritten(Expr *E) {
932 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
933}
934
935static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
936 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
937 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000938 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000939 const auto *VD = dyn_cast<VarDecl>(D);
940 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000941 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000942 VD = VD->getCanonicalDecl();
943 D = VD;
944 } else {
945 assert(FD);
946 FD = FD->getCanonicalDecl();
947 D = FD;
948 }
949 return D;
950}
951
Alexey Bataeve3727102018-04-18 15:57:46 +0000952static ValueDecl *getCanonicalDecl(ValueDecl *D) {
953 return const_cast<ValueDecl *>(
954 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
955}
956
Richard Smith375dec52019-05-30 23:21:14 +0000957DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000958 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000959 D = getCanonicalDecl(D);
960 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000961 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000962 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000963 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000964 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
965 // in a region but not in construct]
966 // File-scope or namespace-scope variables referenced in called routines
967 // in the region are shared unless they appear in a threadprivate
968 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000969 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000970 DVar.CKind = OMPC_shared;
971
972 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
973 // in a region but not in construct]
974 // Variables with static storage duration that are declared in called
975 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000976 if (VD && VD->hasGlobalStorage())
977 DVar.CKind = OMPC_shared;
978
979 // Non-static data members are shared by default.
980 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000981 DVar.CKind = OMPC_shared;
982
Alexey Bataev758e55e2013-09-06 18:03:48 +0000983 return DVar;
984 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000985
Alexey Bataevec3da872014-01-31 05:15:34 +0000986 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
987 // in a Construct, C/C++, predetermined, p.1]
988 // Variables with automatic storage duration that are declared in a scope
989 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000990 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
991 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000992 DVar.CKind = OMPC_private;
993 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000994 }
995
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000996 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000997 // Explicitly specified attributes and local variables with predetermined
998 // attributes.
999 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001000 const DSAInfo &Data = Iter->SharingMap.lookup(D);
1001 DVar.RefExpr = Data.RefExpr.getPointer();
1002 DVar.PrivateCopy = Data.PrivateCopy;
1003 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001004 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001005 return DVar;
1006 }
1007
1008 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1009 // in a Construct, C/C++, implicitly determined, p.1]
1010 // In a parallel or task construct, the data-sharing attributes of these
1011 // variables are determined by the default clause, if present.
1012 switch (Iter->DefaultAttr) {
1013 case DSA_shared:
1014 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001015 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001016 return DVar;
1017 case DSA_none:
1018 return DVar;
1019 case DSA_unspecified:
1020 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1021 // in a Construct, implicitly determined, p.2]
1022 // In a parallel construct, if no default clause is present, these
1023 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +00001024 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001025 if ((isOpenMPParallelDirective(DVar.DKind) &&
1026 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001027 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001028 DVar.CKind = OMPC_shared;
1029 return DVar;
1030 }
1031
1032 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1033 // in a Construct, implicitly determined, p.4]
1034 // In a task construct, if no default clause is present, a variable that in
1035 // the enclosing context is determined to be shared by all implicit tasks
1036 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001037 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001038 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +00001039 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001040 do {
1041 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001042 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +00001043 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +00001044 // In a task construct, if no default clause is present, a variable
1045 // whose data-sharing attribute is not determined by the rules above is
1046 // firstprivate.
1047 DVarTemp = getDSA(I, D);
1048 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001049 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001050 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001051 return DVar;
1052 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001053 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +00001055 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001056 return DVar;
1057 }
1058 }
1059 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1060 // in a Construct, implicitly determined, p.3]
1061 // For constructs other than task, if no default clause is present, these
1062 // variables inherit their data-sharing attributes from the enclosing
1063 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001064 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001065}
1066
Alexey Bataeve3727102018-04-18 15:57:46 +00001067const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1068 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001069 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001070 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001071 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001072 auto It = StackElem.AlignedMap.find(D);
1073 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001074 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001075 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001076 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001077 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001078 assert(It->second && "Unexpected nullptr expr in the aligned map");
1079 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001080}
1081
Alexey Bataevb6e70842019-12-16 15:54:17 -05001082const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1083 const Expr *NewDE) {
1084 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1085 D = getCanonicalDecl(D);
1086 SharingMapTy &StackElem = getTopOfStack();
1087 auto It = StackElem.NontemporalMap.find(D);
1088 if (It == StackElem.NontemporalMap.end()) {
1089 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1090 StackElem.NontemporalMap[D] = NewDE;
1091 return nullptr;
1092 }
1093 assert(It->second && "Unexpected nullptr expr in the aligned map");
1094 return It->second;
1095}
1096
Alexey Bataeve3727102018-04-18 15:57:46 +00001097void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001098 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001099 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001100 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001101 StackElem.LCVMap.try_emplace(
1102 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001103}
1104
Alexey Bataeve3727102018-04-18 15:57:46 +00001105const DSAStackTy::LCDeclInfo
1106DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001107 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001108 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001109 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001110 auto It = StackElem.LCVMap.find(D);
1111 if (It != StackElem.LCVMap.end())
1112 return It->second;
1113 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001114}
1115
Alexey Bataeve3727102018-04-18 15:57:46 +00001116const DSAStackTy::LCDeclInfo
1117DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001118 const SharingMapTy *Parent = getSecondOnStackOrNull();
1119 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001120 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001121 auto It = Parent->LCVMap.find(D);
1122 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001123 return It->second;
1124 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001125}
1126
Alexey Bataeve3727102018-04-18 15:57:46 +00001127const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001128 const SharingMapTy *Parent = getSecondOnStackOrNull();
1129 assert(Parent && "Data-sharing attributes stack is empty");
1130 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001131 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001132 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001133 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001134 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001135 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001136}
1137
Alexey Bataeve3727102018-04-18 15:57:46 +00001138void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001139 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001140 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001141 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001142 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001143 Data.Attributes = A;
1144 Data.RefExpr.setPointer(E);
1145 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001146 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001147 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001148 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1149 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1150 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1151 (isLoopControlVariable(D).first && A == OMPC_private));
1152 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1153 Data.RefExpr.setInt(/*IntVal=*/true);
1154 return;
1155 }
1156 const bool IsLastprivate =
1157 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1158 Data.Attributes = A;
1159 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1160 Data.PrivateCopy = PrivateCopy;
1161 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001162 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001163 Data.Attributes = A;
1164 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1165 Data.PrivateCopy = nullptr;
1166 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001167 }
1168}
1169
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001170/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001171static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001172 StringRef Name, const AttrVec *Attrs = nullptr,
1173 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001174 DeclContext *DC = SemaRef.CurContext;
1175 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1176 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001177 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001178 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1179 if (Attrs) {
1180 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1181 I != E; ++I)
1182 Decl->addAttr(*I);
1183 }
1184 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001185 if (OrigRef) {
1186 Decl->addAttr(
1187 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1188 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001189 return Decl;
1190}
1191
1192static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1193 SourceLocation Loc,
1194 bool RefersToCapture = false) {
1195 D->setReferenced();
1196 D->markUsed(S.Context);
1197 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1198 SourceLocation(), D, RefersToCapture, Loc, Ty,
1199 VK_LValue);
1200}
1201
Alexey Bataeve3727102018-04-18 15:57:46 +00001202void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001203 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001204 D = getCanonicalDecl(D);
1205 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001206 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001207 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001208 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001209 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001210 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001211 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001212 "Additional reduction info may be specified only once for reduction "
1213 "items.");
1214 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001215 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001216 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001217 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001218 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1219 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001220 TaskgroupReductionRef =
1221 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001222 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001223}
1224
Alexey Bataeve3727102018-04-18 15:57:46 +00001225void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001226 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001227 D = getCanonicalDecl(D);
1228 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001229 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001230 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001231 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001232 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001233 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001234 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001235 "Additional reduction info may be specified only once for reduction "
1236 "items.");
1237 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001238 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001239 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001240 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001241 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1242 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001243 TaskgroupReductionRef =
1244 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001245 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001246}
1247
Alexey Bataeve3727102018-04-18 15:57:46 +00001248const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1249 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1250 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001251 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001252 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001253 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001254 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001255 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001256 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001257 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001258 if (!ReductionData.ReductionOp ||
1259 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001260 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001261 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001262 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001263 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1264 "expression for the descriptor is not "
1265 "set.");
1266 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001267 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1268 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001269 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001270 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001271}
1272
Alexey Bataeve3727102018-04-18 15:57:46 +00001273const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1274 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1275 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001276 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001277 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001278 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001279 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001280 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001281 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001282 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001283 if (!ReductionData.ReductionOp ||
1284 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001285 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001286 SR = ReductionData.ReductionRange;
1287 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001288 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1289 "expression for the descriptor is not "
1290 "set.");
1291 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001292 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1293 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001294 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001295 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001296}
1297
Richard Smith375dec52019-05-30 23:21:14 +00001298bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001299 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001300 for (const_iterator E = end(); I != E; ++I) {
1301 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1302 isOpenMPTargetExecutionDirective(I->Directive)) {
1303 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1304 Scope *CurScope = getCurScope();
1305 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1306 CurScope = CurScope->getParent();
1307 return CurScope != TopScope;
1308 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001309 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001310 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001311}
1312
Joel E. Dennyd2649292019-01-04 22:11:56 +00001313static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1314 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001315 bool *IsClassType = nullptr) {
1316 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001317 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001318 bool IsConstant = Type.isConstant(Context);
1319 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001320 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1321 ? Type->getAsCXXRecordDecl()
1322 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001323 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1324 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1325 RD = CTD->getTemplatedDecl();
1326 if (IsClassType)
1327 *IsClassType = RD;
1328 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1329 RD->hasDefinition() && RD->hasMutableFields());
1330}
1331
Joel E. Dennyd2649292019-01-04 22:11:56 +00001332static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1333 QualType Type, OpenMPClauseKind CKind,
1334 SourceLocation ELoc,
1335 bool AcceptIfMutable = true,
1336 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001337 ASTContext &Context = SemaRef.getASTContext();
1338 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001339 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1340 unsigned Diag = ListItemNotVar
1341 ? diag::err_omp_const_list_item
1342 : IsClassType ? diag::err_omp_const_not_mutable_variable
1343 : diag::err_omp_const_variable;
1344 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1345 if (!ListItemNotVar && D) {
1346 const VarDecl *VD = dyn_cast<VarDecl>(D);
1347 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1348 VarDecl::DeclarationOnly;
1349 SemaRef.Diag(D->getLocation(),
1350 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1351 << D;
1352 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001353 return true;
1354 }
1355 return false;
1356}
1357
Alexey Bataeve3727102018-04-18 15:57:46 +00001358const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1359 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001360 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001361 DSAVarData DVar;
1362
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001363 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001364 auto TI = Threadprivates.find(D);
1365 if (TI != Threadprivates.end()) {
1366 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001367 DVar.CKind = OMPC_threadprivate;
1368 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001369 }
1370 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001371 DVar.RefExpr = buildDeclRefExpr(
1372 SemaRef, VD, D->getType().getNonReferenceType(),
1373 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1374 DVar.CKind = OMPC_threadprivate;
1375 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001376 return DVar;
1377 }
1378 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1379 // in a Construct, C/C++, predetermined, p.1]
1380 // Variables appearing in threadprivate directives are threadprivate.
1381 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1382 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1383 SemaRef.getLangOpts().OpenMPUseTLS &&
1384 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1385 (VD && VD->getStorageClass() == SC_Register &&
1386 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1387 DVar.RefExpr = buildDeclRefExpr(
1388 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1389 DVar.CKind = OMPC_threadprivate;
1390 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1391 return DVar;
1392 }
1393 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1394 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1395 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001396 const_iterator IterTarget =
1397 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1398 return isOpenMPTargetExecutionDirective(Data.Directive);
1399 });
1400 if (IterTarget != end()) {
1401 const_iterator ParentIterTarget = IterTarget + 1;
1402 for (const_iterator Iter = begin();
1403 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001404 if (isOpenMPLocal(VD, Iter)) {
1405 DVar.RefExpr =
1406 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1407 D->getLocation());
1408 DVar.CKind = OMPC_threadprivate;
1409 return DVar;
1410 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001411 }
Richard Smith375dec52019-05-30 23:21:14 +00001412 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001413 auto DSAIter = IterTarget->SharingMap.find(D);
1414 if (DSAIter != IterTarget->SharingMap.end() &&
1415 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1416 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1417 DVar.CKind = OMPC_threadprivate;
1418 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001419 }
Richard Smith375dec52019-05-30 23:21:14 +00001420 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001421 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001422 D, std::distance(ParentIterTarget, End),
1423 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001424 DVar.RefExpr =
1425 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1426 IterTarget->ConstructLoc);
1427 DVar.CKind = OMPC_threadprivate;
1428 return DVar;
1429 }
1430 }
1431 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001432 }
1433
Alexey Bataev4b465392017-04-26 15:06:24 +00001434 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001435 // Not in OpenMP execution region and top scope was already checked.
1436 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001437
Alexey Bataev758e55e2013-09-06 18:03:48 +00001438 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001439 // in a Construct, C/C++, predetermined, p.4]
1440 // Static data members are shared.
1441 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1442 // in a Construct, C/C++, predetermined, p.7]
1443 // Variables with static storage duration that are declared in a scope
1444 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001445 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001446 // Check for explicitly specified attributes.
1447 const_iterator I = begin();
1448 const_iterator EndI = end();
1449 if (FromParent && I != EndI)
1450 ++I;
1451 auto It = I->SharingMap.find(D);
1452 if (It != I->SharingMap.end()) {
1453 const DSAInfo &Data = It->getSecond();
1454 DVar.RefExpr = Data.RefExpr.getPointer();
1455 DVar.PrivateCopy = Data.PrivateCopy;
1456 DVar.CKind = Data.Attributes;
1457 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1458 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001459 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001460 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001461
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001462 DVar.CKind = OMPC_shared;
1463 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001464 }
1465
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001466 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001467 // The predetermined shared attribute for const-qualified types having no
1468 // mutable members was removed after OpenMP 3.1.
1469 if (SemaRef.LangOpts.OpenMP <= 31) {
1470 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1471 // in a Construct, C/C++, predetermined, p.6]
1472 // Variables with const qualified type having no mutable member are
1473 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001474 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001475 // Variables with const-qualified type having no mutable member may be
1476 // listed in a firstprivate clause, even if they are static data members.
1477 DSAVarData DVarTemp = hasInnermostDSA(
1478 D,
1479 [](OpenMPClauseKind C) {
1480 return C == OMPC_firstprivate || C == OMPC_shared;
1481 },
1482 MatchesAlways, FromParent);
1483 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1484 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001485
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001486 DVar.CKind = OMPC_shared;
1487 return DVar;
1488 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001489 }
1490
Alexey Bataev758e55e2013-09-06 18:03:48 +00001491 // Explicitly specified attributes and local variables with predetermined
1492 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001493 const_iterator I = begin();
1494 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001495 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001496 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001497 auto It = I->SharingMap.find(D);
1498 if (It != I->SharingMap.end()) {
1499 const DSAInfo &Data = It->getSecond();
1500 DVar.RefExpr = Data.RefExpr.getPointer();
1501 DVar.PrivateCopy = Data.PrivateCopy;
1502 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001503 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001504 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001505 }
1506
1507 return DVar;
1508}
1509
Alexey Bataeve3727102018-04-18 15:57:46 +00001510const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1511 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001512 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001513 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001514 return getDSA(I, D);
1515 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001516 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001517 const_iterator StartI = begin();
1518 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001519 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001520 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001521 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001522}
1523
Alexey Bataeve3727102018-04-18 15:57:46 +00001524const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001525DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001526 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1527 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001528 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001529 if (isStackEmpty())
1530 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001531 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001532 const_iterator I = begin();
1533 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001534 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001535 ++I;
1536 for (; I != EndI; ++I) {
1537 if (!DPred(I->Directive) &&
1538 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001539 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001540 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001541 DSAVarData DVar = getDSA(NewI, D);
1542 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001543 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001544 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001545 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001546}
1547
Alexey Bataeve3727102018-04-18 15:57:46 +00001548const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001549 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1550 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001551 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001552 if (isStackEmpty())
1553 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001554 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001555 const_iterator StartI = begin();
1556 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001557 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001558 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001559 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001560 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001561 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001562 DSAVarData DVar = getDSA(NewI, D);
1563 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001564}
1565
Alexey Bataevaac108a2015-06-23 04:51:00 +00001566bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001567 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1568 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001569 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001570 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001571 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001572 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1573 auto I = StackElem.SharingMap.find(D);
1574 if (I != StackElem.SharingMap.end() &&
1575 I->getSecond().RefExpr.getPointer() &&
1576 CPred(I->getSecond().Attributes) &&
1577 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001578 return true;
1579 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001580 auto LI = StackElem.LCVMap.find(D);
1581 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001582 return CPred(OMPC_private);
1583 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001584}
1585
Samuel Antao4be30e92015-10-02 17:14:03 +00001586bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001587 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1588 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001589 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001590 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001591 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1592 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001593}
1594
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001595bool DSAStackTy::hasDirective(
1596 const llvm::function_ref<bool(OpenMPDirectiveKind,
1597 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001598 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001599 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001600 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001601 size_t Skip = FromParent ? 2 : 1;
1602 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1603 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001604 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1605 return true;
1606 }
1607 return false;
1608}
1609
Alexey Bataev758e55e2013-09-06 18:03:48 +00001610void Sema::InitDataSharingAttributesStack() {
1611 VarDataSharingAttributesStack = new DSAStackTy(*this);
1612}
1613
1614#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1615
Alexey Bataev4b465392017-04-26 15:06:24 +00001616void Sema::pushOpenMPFunctionRegion() {
1617 DSAStack->pushFunction();
1618}
1619
1620void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1621 DSAStack->popFunction(OldFSI);
1622}
1623
Alexey Bataevc416e642019-02-08 18:02:25 +00001624static bool isOpenMPDeviceDelayedContext(Sema &S) {
1625 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1626 "Expected OpenMP device compilation.");
1627 return !S.isInOpenMPTargetExecutionDirective() &&
1628 !S.isInOpenMPDeclareTargetContext();
1629}
1630
Alexey Bataev729e2422019-08-23 16:11:14 +00001631namespace {
1632/// Status of the function emission on the host/device.
1633enum class FunctionEmissionStatus {
1634 Emitted,
1635 Discarded,
1636 Unknown,
1637};
1638} // anonymous namespace
1639
Alexey Bataevc416e642019-02-08 18:02:25 +00001640Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1641 unsigned DiagID) {
1642 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1643 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001644 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001645 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1646 switch (FES) {
1647 case FunctionEmissionStatus::Emitted:
1648 Kind = DeviceDiagBuilder::K_Immediate;
1649 break;
1650 case FunctionEmissionStatus::Unknown:
1651 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1652 : DeviceDiagBuilder::K_Immediate;
1653 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001654 case FunctionEmissionStatus::TemplateDiscarded:
1655 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001656 Kind = DeviceDiagBuilder::K_Nop;
1657 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001658 case FunctionEmissionStatus::CUDADiscarded:
1659 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1660 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001661 }
1662
1663 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1664}
1665
Alexey Bataev729e2422019-08-23 16:11:14 +00001666Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1667 unsigned DiagID) {
1668 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1669 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001670 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001671 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1672 switch (FES) {
1673 case FunctionEmissionStatus::Emitted:
1674 Kind = DeviceDiagBuilder::K_Immediate;
1675 break;
1676 case FunctionEmissionStatus::Unknown:
1677 Kind = DeviceDiagBuilder::K_Deferred;
1678 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001679 case FunctionEmissionStatus::TemplateDiscarded:
1680 case FunctionEmissionStatus::OMPDiscarded:
1681 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001682 Kind = DeviceDiagBuilder::K_Nop;
1683 break;
1684 }
1685
1686 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001687}
1688
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001689void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1690 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001691 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1692 "Expected OpenMP device compilation.");
1693 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001694 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001695 FunctionDecl *Caller = getCurFunctionDecl();
1696
Alexey Bataev729e2422019-08-23 16:11:14 +00001697 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001698 if (Caller) {
1699 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1700 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1701 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1702 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1703 "CUDADiscarded unexpected in OpenMP device function check");
1704 if ((CallerS == FunctionEmissionStatus::Emitted ||
1705 (!isOpenMPDeviceDelayedContext(*this) &&
1706 CallerS == FunctionEmissionStatus::Unknown)) &&
1707 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1708 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1709 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1710 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1711 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1712 diag::note_omp_marked_device_type_here)
1713 << HostDevTy;
1714 return;
1715 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001716 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001717 // If the caller is known-emitted, mark the callee as known-emitted.
1718 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001719 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1720 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001721 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001722 markKnownEmitted(*this, Caller, Callee, Loc,
1723 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001724 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001725 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001726 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001727 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001728 else if (Caller)
1729 DeviceCallGraph[Caller].insert({Callee, Loc});
1730}
1731
Alexey Bataev729e2422019-08-23 16:11:14 +00001732void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1733 bool CheckCaller) {
1734 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1735 "Expected OpenMP host compilation.");
1736 assert(Callee && "Callee may not be null.");
1737 Callee = Callee->getMostRecentDecl();
1738 FunctionDecl *Caller = getCurFunctionDecl();
1739
1740 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001741 if (Caller) {
1742 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1743 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1744 assert(
1745 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1746 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1747 "CUDADiscarded unexpected in OpenMP host function check");
1748 if (CallerS == FunctionEmissionStatus::Emitted &&
1749 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1750 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1751 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1752 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1753 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1754 diag::note_omp_marked_device_type_here)
1755 << NoHostDevTy;
1756 return;
1757 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001758 }
1759 // If the caller is known-emitted, mark the callee as known-emitted.
1760 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001761 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1762 if ((!CheckCaller && !Caller) ||
1763 (Caller &&
1764 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1765 markKnownEmitted(
1766 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1767 return CheckCaller &&
1768 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1769 });
1770 else if (Caller)
1771 DeviceCallGraph[Caller].insert({Callee, Loc});
1772 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001773}
1774
Alexey Bataev123ad192019-02-27 20:29:45 +00001775void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1776 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1777 "OpenMP device compilation mode is expected.");
1778 QualType Ty = E->getType();
1779 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001780 ((Ty->isFloat128Type() ||
1781 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1782 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001783 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1784 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001785 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1786 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1787 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001788}
1789
cchene06f3e02019-11-15 13:02:06 -05001790static OpenMPDefaultmapClauseKind
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001791getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1792 if (LO.OpenMP <= 45) {
1793 if (VD->getType().getNonReferenceType()->isScalarType())
1794 return OMPC_DEFAULTMAP_scalar;
1795 return OMPC_DEFAULTMAP_aggregate;
1796 }
cchene06f3e02019-11-15 13:02:06 -05001797 if (VD->getType().getNonReferenceType()->isAnyPointerType())
1798 return OMPC_DEFAULTMAP_pointer;
1799 if (VD->getType().getNonReferenceType()->isScalarType())
1800 return OMPC_DEFAULTMAP_scalar;
1801 return OMPC_DEFAULTMAP_aggregate;
1802}
1803
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001804bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1805 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001806 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1807
Alexey Bataeve3727102018-04-18 15:57:46 +00001808 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001809 bool IsByRef = true;
1810
1811 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001812 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001813 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001814
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001815 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001816 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001817 // This table summarizes how a given variable should be passed to the device
1818 // given its type and the clauses where it appears. This table is based on
1819 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1820 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1821 //
1822 // =========================================================================
1823 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1824 // | |(tofrom:scalar)| | pvt | | | |
1825 // =========================================================================
1826 // | scl | | | | - | | bycopy|
1827 // | scl | | - | x | - | - | bycopy|
1828 // | scl | | x | - | - | - | null |
1829 // | scl | x | | | - | | byref |
1830 // | scl | x | - | x | - | - | bycopy|
1831 // | scl | x | x | - | - | - | null |
1832 // | scl | | - | - | - | x | byref |
1833 // | scl | x | - | - | - | x | byref |
1834 //
1835 // | agg | n.a. | | | - | | byref |
1836 // | agg | n.a. | - | x | - | - | byref |
1837 // | agg | n.a. | x | - | - | - | null |
1838 // | agg | n.a. | - | - | - | x | byref |
1839 // | agg | n.a. | - | - | - | x[] | byref |
1840 //
1841 // | ptr | n.a. | | | - | | bycopy|
1842 // | ptr | n.a. | - | x | - | - | bycopy|
1843 // | ptr | n.a. | x | - | - | - | null |
1844 // | ptr | n.a. | - | - | - | x | byref |
1845 // | ptr | n.a. | - | - | - | x[] | bycopy|
1846 // | ptr | n.a. | - | - | x | | bycopy|
1847 // | ptr | n.a. | - | - | x | x | bycopy|
1848 // | ptr | n.a. | - | - | x | x[] | bycopy|
1849 // =========================================================================
1850 // Legend:
1851 // scl - scalar
1852 // ptr - pointer
1853 // agg - aggregate
1854 // x - applies
1855 // - - invalid in this combination
1856 // [] - mapped with an array section
1857 // byref - should be mapped by reference
1858 // byval - should be mapped by value
1859 // null - initialize a local variable to null on the device
1860 //
1861 // Observations:
1862 // - All scalar declarations that show up in a map clause have to be passed
1863 // by reference, because they may have been mapped in the enclosing data
1864 // environment.
1865 // - If the scalar value does not fit the size of uintptr, it has to be
1866 // passed by reference, regardless the result in the table above.
1867 // - For pointers mapped by value that have either an implicit map or an
1868 // array section, the runtime library may pass the NULL value to the
1869 // device instead of the value passed to it by the compiler.
1870
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001871 if (Ty->isReferenceType())
1872 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001873
1874 // Locate map clauses and see if the variable being captured is referred to
1875 // in any of those clauses. Here we only care about variables, not fields,
1876 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001877 bool IsVariableAssociatedWithSection = false;
1878
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001879 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001880 D, Level,
1881 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1882 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001883 MapExprComponents,
1884 OpenMPClauseKind WhereFoundClauseKind) {
1885 // Only the map clause information influences how a variable is
1886 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001887 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001888 if (WhereFoundClauseKind != OMPC_map)
1889 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001890
1891 auto EI = MapExprComponents.rbegin();
1892 auto EE = MapExprComponents.rend();
1893
1894 assert(EI != EE && "Invalid map expression!");
1895
1896 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1897 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1898
1899 ++EI;
1900 if (EI == EE)
1901 return false;
1902
1903 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1904 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1905 isa<MemberExpr>(EI->getAssociatedExpression())) {
1906 IsVariableAssociatedWithSection = true;
1907 // There is nothing more we need to know about this variable.
1908 return true;
1909 }
1910
1911 // Keep looking for more map info.
1912 return false;
1913 });
1914
1915 if (IsVariableUsedInMapClause) {
1916 // If variable is identified in a map clause it is always captured by
1917 // reference except if it is a pointer that is dereferenced somehow.
1918 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1919 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001920 // By default, all the data that has a scalar type is mapped by copy
1921 // (except for reduction variables).
cchene06f3e02019-11-15 13:02:06 -05001922 // Defaultmap scalar is mutual exclusive to defaultmap pointer
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001923 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001924 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1925 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001926 !Ty->isScalarType() ||
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001927 DSAStack->isDefaultmapCapturedByRef(
1928 Level, getVariableCategoryFromDecl(LangOpts, D)) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001929 DSAStack->hasExplicitDSA(
1930 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001931 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001932 }
1933
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001934 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001935 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001936 ((IsVariableUsedInMapClause &&
1937 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1938 OMPD_target) ||
1939 !DSAStack->hasExplicitDSA(
1940 D,
1941 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1942 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001943 // If the variable is artificial and must be captured by value - try to
1944 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001945 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1946 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001947 }
1948
Samuel Antao86ace552016-04-27 22:40:57 +00001949 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001950 // and alignment, because the runtime library only deals with uintptr types.
1951 // If it does not fit the uintptr size, we need to pass the data by reference
1952 // instead.
1953 if (!IsByRef &&
1954 (Ctx.getTypeSizeInChars(Ty) >
1955 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001956 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001957 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001958 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001959
1960 return IsByRef;
1961}
1962
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001963unsigned Sema::getOpenMPNestingLevel() const {
1964 assert(getLangOpts().OpenMP);
1965 return DSAStack->getNestingLevel();
1966}
1967
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001968bool Sema::isInOpenMPTargetExecutionDirective() const {
1969 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1970 !DSAStack->isClauseParsingMode()) ||
1971 DSAStack->hasDirective(
1972 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1973 SourceLocation) -> bool {
1974 return isOpenMPTargetExecutionDirective(K);
1975 },
1976 false);
1977}
1978
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001979VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1980 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001981 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001982 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001983
Alexey Bataev7c860692019-10-25 16:35:32 -04001984 auto *VD = dyn_cast<VarDecl>(D);
1985 // Do not capture constexpr variables.
1986 if (VD && VD->isConstexpr())
1987 return nullptr;
1988
Richard Smith0621a8f2019-05-31 00:45:10 +00001989 // If we want to determine whether the variable should be captured from the
1990 // perspective of the current capturing scope, and we've already left all the
1991 // capturing scopes of the top directive on the stack, check from the
1992 // perspective of its parent directive (if any) instead.
1993 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1994 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1995
Samuel Antao4be30e92015-10-02 17:14:03 +00001996 // If we are attempting to capture a global variable in a directive with
1997 // 'target' we return true so that this global is also mapped to the device.
1998 //
Richard Smith0621a8f2019-05-31 00:45:10 +00001999 if (VD && !VD->hasLocalStorage() &&
2000 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2001 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002002 // Try to mark variable as declare target if it is used in capturing
2003 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00002004 if (LangOpts.OpenMP <= 45 &&
2005 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002006 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002007 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002008 } else if (isInOpenMPTargetExecutionDirective()) {
2009 // If the declaration is enclosed in a 'declare target' directive,
2010 // then it should not be captured.
2011 //
Alexey Bataev97b72212018-08-14 18:31:20 +00002012 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002013 return nullptr;
Alexey Bataev36635632020-01-17 20:39:04 -05002014 CapturedRegionScopeInfo *CSI = nullptr;
2015 for (FunctionScopeInfo *FSI : llvm::drop_begin(
2016 llvm::reverse(FunctionScopes),
2017 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2018 if (!isa<CapturingScopeInfo>(FSI))
2019 return nullptr;
2020 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2021 if (RSI->CapRegionKind == CR_OpenMP) {
2022 CSI = RSI;
2023 break;
2024 }
2025 }
2026 SmallVector<OpenMPDirectiveKind, 4> Regions;
2027 getOpenMPCaptureRegions(Regions,
2028 DSAStack->getDirective(CSI->OpenMPLevel));
2029 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2030 return VD;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002031 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002032 }
Samuel Antao4be30e92015-10-02 17:14:03 +00002033
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002034 if (CheckScopeInfo) {
2035 bool OpenMPFound = false;
2036 for (unsigned I = StopAt + 1; I > 0; --I) {
2037 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2038 if(!isa<CapturingScopeInfo>(FSI))
2039 return nullptr;
2040 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2041 if (RSI->CapRegionKind == CR_OpenMP) {
2042 OpenMPFound = true;
2043 break;
2044 }
2045 }
2046 if (!OpenMPFound)
2047 return nullptr;
2048 }
2049
Alexey Bataev48977c32015-08-04 08:10:48 +00002050 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2051 (!DSAStack->isClauseParsingMode() ||
2052 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002053 auto &&Info = DSAStack->isLoopControlVariable(D);
2054 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002055 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002056 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002057 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002058 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00002059 DSAStackTy::DSAVarData DVarPrivate =
2060 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002061 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002062 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00002063 // Threadprivate variables must not be captured.
2064 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
2065 return nullptr;
2066 // The variable is not private or it is the variable in the directive with
2067 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002068 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
2069 [](OpenMPDirectiveKind) { return true; },
2070 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002071 if (DVarPrivate.CKind != OMPC_unknown ||
2072 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002073 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002074 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00002075 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00002076}
2077
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002078void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2079 unsigned Level) const {
2080 SmallVector<OpenMPDirectiveKind, 4> Regions;
2081 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2082 FunctionScopesIndex -= Regions.size();
2083}
2084
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002085void Sema::startOpenMPLoop() {
2086 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2087 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2088 DSAStack->loopInit();
2089}
2090
Alexey Bataevbef93a92019-10-07 18:54:57 +00002091void Sema::startOpenMPCXXRangeFor() {
2092 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2093 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2094 DSAStack->resetPossibleLoopCounter();
2095 DSAStack->loopStart();
2096 }
2097}
2098
Alexey Bataeve3727102018-04-18 15:57:46 +00002099bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002100 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002101 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2102 if (DSAStack->getAssociatedLoops() > 0 &&
2103 !DSAStack->isLoopStarted()) {
2104 DSAStack->resetPossibleLoopCounter(D);
2105 DSAStack->loopStart();
2106 return true;
2107 }
2108 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2109 DSAStack->isLoopControlVariable(D).first) &&
2110 !DSAStack->hasExplicitDSA(
2111 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2112 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2113 return true;
2114 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002115 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2116 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2117 DSAStack->isForceVarCapturing() &&
2118 !DSAStack->hasExplicitDSA(
2119 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2120 return true;
2121 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002122 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002123 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002124 (DSAStack->isClauseParsingMode() &&
2125 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002126 // Consider taskgroup reduction descriptor variable a private to avoid
2127 // possible capture in the region.
2128 (DSAStack->hasExplicitDirective(
2129 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2130 Level) &&
2131 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002132}
2133
Alexey Bataeve3727102018-04-18 15:57:46 +00002134void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2135 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002136 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2137 D = getCanonicalDecl(D);
2138 OpenMPClauseKind OMPC = OMPC_unknown;
2139 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2140 const unsigned NewLevel = I - 1;
2141 if (DSAStack->hasExplicitDSA(D,
2142 [&OMPC](const OpenMPClauseKind K) {
2143 if (isOpenMPPrivate(K)) {
2144 OMPC = K;
2145 return true;
2146 }
2147 return false;
2148 },
2149 NewLevel))
2150 break;
2151 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2152 D, NewLevel,
2153 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2154 OpenMPClauseKind) { return true; })) {
2155 OMPC = OMPC_map;
2156 break;
2157 }
2158 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2159 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002160 OMPC = OMPC_map;
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002161 if (DSAStack->mustBeFirstprivateAtLevel(
2162 NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002163 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002164 break;
2165 }
2166 }
2167 if (OMPC != OMPC_unknown)
2168 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2169}
2170
Alexey Bataev36635632020-01-17 20:39:04 -05002171bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2172 unsigned CaptureLevel) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002173 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2174 // Return true if the current level is no longer enclosed in a target region.
2175
Alexey Bataev36635632020-01-17 20:39:04 -05002176 SmallVector<OpenMPDirectiveKind, 4> Regions;
2177 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
Alexey Bataeve3727102018-04-18 15:57:46 +00002178 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002179 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002180 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
Alexey Bataev36635632020-01-17 20:39:04 -05002181 Level) &&
2182 Regions[CaptureLevel] != OMPD_task;
Samuel Antao4be30e92015-10-02 17:14:03 +00002183}
2184
Alexey Bataeved09d242014-05-28 05:53:51 +00002185void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002186
Alexey Bataev729e2422019-08-23 16:11:14 +00002187void Sema::finalizeOpenMPDelayedAnalysis() {
2188 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2189 // Diagnose implicit declare target functions and their callees.
2190 for (const auto &CallerCallees : DeviceCallGraph) {
2191 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2192 OMPDeclareTargetDeclAttr::getDeviceType(
2193 CallerCallees.getFirst()->getMostRecentDecl());
2194 // Ignore host functions during device analyzis.
2195 if (LangOpts.OpenMPIsDevice && DevTy &&
2196 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2197 continue;
2198 // Ignore nohost functions during host analyzis.
2199 if (!LangOpts.OpenMPIsDevice && DevTy &&
2200 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2201 continue;
2202 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2203 &Callee : CallerCallees.getSecond()) {
2204 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2205 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2206 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2207 if (LangOpts.OpenMPIsDevice && DevTy &&
2208 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2209 // Diagnose host function called during device codegen.
2210 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2211 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2212 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2213 << HostDevTy << 0;
2214 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2215 diag::note_omp_marked_device_type_here)
2216 << HostDevTy;
2217 continue;
2218 }
2219 if (!LangOpts.OpenMPIsDevice && DevTy &&
2220 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2221 // Diagnose nohost function called during host codegen.
2222 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2223 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2224 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2225 << NoHostDevTy << 1;
2226 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2227 diag::note_omp_marked_device_type_here)
2228 << NoHostDevTy;
2229 continue;
2230 }
2231 }
2232 }
2233}
2234
Alexey Bataev758e55e2013-09-06 18:03:48 +00002235void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2236 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002237 Scope *CurScope, SourceLocation Loc) {
2238 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002239 PushExpressionEvaluationContext(
2240 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002241}
2242
Alexey Bataevaac108a2015-06-23 04:51:00 +00002243void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2244 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002245}
2246
Alexey Bataevaac108a2015-06-23 04:51:00 +00002247void Sema::EndOpenMPClause() {
2248 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002249}
2250
Alexey Bataeve106f252019-04-01 14:25:31 +00002251static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2252 ArrayRef<OMPClause *> Clauses);
Alexey Bataev0860db92019-12-19 10:01:10 -05002253static std::pair<ValueDecl *, bool>
2254getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2255 SourceRange &ERange, bool AllowArraySection = false);
2256static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2257 bool WithInit);
Alexey Bataeve106f252019-04-01 14:25:31 +00002258
Alexey Bataev758e55e2013-09-06 18:03:48 +00002259void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002260 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2261 // A variable of class type (or array thereof) that appears in a lastprivate
2262 // clause requires an accessible, unambiguous default constructor for the
2263 // class type, unless the list item is also specified in a firstprivate
2264 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002265 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2266 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002267 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2268 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002269 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002270 if (DE->isValueDependent() || DE->isTypeDependent()) {
2271 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002272 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002273 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002274 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002275 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002276 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002277 const DSAStackTy::DSAVarData DVar =
2278 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002279 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002280 // Generate helper private variable and initialize it with the
2281 // default value. The address of the original variable is replaced
2282 // by the address of the new private variable in CodeGen. This new
2283 // variable is not added to IdResolver, so the code in the OpenMP
2284 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002285 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002286 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002287 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002288 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002289 if (VDPrivate->isInvalidDecl()) {
2290 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002291 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002292 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002293 PrivateCopies.push_back(buildDeclRefExpr(
2294 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002295 } else {
2296 // The variable is also a firstprivate, so initialization sequence
2297 // for private copy is generated already.
2298 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002299 }
2300 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002301 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataev0860db92019-12-19 10:01:10 -05002302 continue;
2303 }
2304 // Finalize nontemporal clause by handling private copies, if any.
2305 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2306 SmallVector<Expr *, 8> PrivateRefs;
2307 for (Expr *RefExpr : Clause->varlists()) {
2308 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2309 SourceLocation ELoc;
2310 SourceRange ERange;
2311 Expr *SimpleRefExpr = RefExpr;
2312 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2313 if (Res.second)
2314 // It will be analyzed later.
2315 PrivateRefs.push_back(RefExpr);
2316 ValueDecl *D = Res.first;
2317 if (!D)
2318 continue;
2319
2320 const DSAStackTy::DSAVarData DVar =
2321 DSAStack->getTopDSA(D, /*FromParent=*/false);
2322 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2323 : SimpleRefExpr);
2324 }
2325 Clause->setPrivateRefs(PrivateRefs);
2326 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002327 }
2328 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002329 // Check allocate clauses.
2330 if (!CurContext->isDependentContext())
2331 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002332 }
2333
Alexey Bataev758e55e2013-09-06 18:03:48 +00002334 DSAStack->pop();
2335 DiscardCleanupsInEvaluationContext();
2336 PopExpressionEvaluationContext();
2337}
2338
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002339static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2340 Expr *NumIterations, Sema &SemaRef,
2341 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002342
Alexey Bataeva769e072013-03-22 06:34:35 +00002343namespace {
2344
Alexey Bataeve3727102018-04-18 15:57:46 +00002345class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002346private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002347 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002348
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002349public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002350 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002351 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002352 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002353 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002354 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002355 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2356 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002357 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002358 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002359 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002360
2361 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002362 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002363 }
2364
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002365};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002366
Alexey Bataeve3727102018-04-18 15:57:46 +00002367class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002368private:
2369 Sema &SemaRef;
2370
2371public:
2372 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2373 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2374 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002375 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2376 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002377 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2378 SemaRef.getCurScope());
2379 }
2380 return false;
2381 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002382
2383 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002384 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002385 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002386};
2387
Alexey Bataeved09d242014-05-28 05:53:51 +00002388} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002389
2390ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2391 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002392 const DeclarationNameInfo &Id,
2393 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002394 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2395 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2396
2397 if (Lookup.isAmbiguous())
2398 return ExprError();
2399
2400 VarDecl *VD;
2401 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002402 VarDeclFilterCCC CCC(*this);
2403 if (TypoCorrection Corrected =
2404 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2405 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002406 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002407 PDiag(Lookup.empty()
2408 ? diag::err_undeclared_var_use_suggest
2409 : diag::err_omp_expected_var_arg_suggest)
2410 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002411 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002412 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002413 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2414 : diag::err_omp_expected_var_arg)
2415 << Id.getName();
2416 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002417 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002418 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2419 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2420 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2421 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002422 }
2423 Lookup.suppressDiagnostics();
2424
2425 // OpenMP [2.9.2, Syntax, C/C++]
2426 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002427 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002428 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002429 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002430 bool IsDecl =
2431 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002432 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002433 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2434 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002435 return ExprError();
2436 }
2437
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002438 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002439 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002440 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2441 // A threadprivate directive for file-scope variables must appear outside
2442 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002443 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2444 !getCurLexicalContext()->isTranslationUnit()) {
2445 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002446 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002447 bool IsDecl =
2448 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2449 Diag(VD->getLocation(),
2450 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2451 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002452 return ExprError();
2453 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002454 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2455 // A threadprivate directive for static class member variables must appear
2456 // in the class definition, in the same scope in which the member
2457 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002458 if (CanonicalVD->isStaticDataMember() &&
2459 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2460 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002461 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002462 bool IsDecl =
2463 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2464 Diag(VD->getLocation(),
2465 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2466 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002467 return ExprError();
2468 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002469 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2470 // A threadprivate directive for namespace-scope variables must appear
2471 // outside any definition or declaration other than the namespace
2472 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002473 if (CanonicalVD->getDeclContext()->isNamespace() &&
2474 (!getCurLexicalContext()->isFileContext() ||
2475 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2476 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002477 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002478 bool IsDecl =
2479 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2480 Diag(VD->getLocation(),
2481 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2482 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002483 return ExprError();
2484 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002485 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2486 // A threadprivate directive for static block-scope variables must appear
2487 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002488 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002489 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002490 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002491 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002492 bool IsDecl =
2493 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2494 Diag(VD->getLocation(),
2495 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2496 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002497 return ExprError();
2498 }
2499
2500 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2501 // A threadprivate directive must lexically precede all references to any
2502 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002503 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2504 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002505 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002506 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002507 return ExprError();
2508 }
2509
2510 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002511 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2512 SourceLocation(), VD,
2513 /*RefersToEnclosingVariableOrCapture=*/false,
2514 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002515}
2516
Alexey Bataeved09d242014-05-28 05:53:51 +00002517Sema::DeclGroupPtrTy
2518Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2519 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002520 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002521 CurContext->addDecl(D);
2522 return DeclGroupPtrTy::make(DeclGroupRef(D));
2523 }
David Blaikie0403cb12016-01-15 23:43:25 +00002524 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002525}
2526
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002527namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002528class LocalVarRefChecker final
2529 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002530 Sema &SemaRef;
2531
2532public:
2533 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002534 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002535 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002536 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002537 diag::err_omp_local_var_in_threadprivate_init)
2538 << E->getSourceRange();
2539 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2540 << VD << VD->getSourceRange();
2541 return true;
2542 }
2543 }
2544 return false;
2545 }
2546 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002547 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002548 if (Child && Visit(Child))
2549 return true;
2550 }
2551 return false;
2552 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002553 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002554};
2555} // namespace
2556
Alexey Bataeved09d242014-05-28 05:53:51 +00002557OMPThreadPrivateDecl *
2558Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002559 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002560 for (Expr *RefExpr : VarList) {
2561 auto *DE = cast<DeclRefExpr>(RefExpr);
2562 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002563 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002564
Alexey Bataev376b4a42016-02-09 09:41:09 +00002565 // Mark variable as used.
2566 VD->setReferenced();
2567 VD->markUsed(Context);
2568
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002569 QualType QType = VD->getType();
2570 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2571 // It will be analyzed later.
2572 Vars.push_back(DE);
2573 continue;
2574 }
2575
Alexey Bataeva769e072013-03-22 06:34:35 +00002576 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2577 // A threadprivate variable must not have an incomplete type.
2578 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002579 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002580 continue;
2581 }
2582
2583 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2584 // A threadprivate variable must not have a reference type.
2585 if (VD->getType()->isReferenceType()) {
2586 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002587 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2588 bool IsDecl =
2589 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2590 Diag(VD->getLocation(),
2591 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2592 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002593 continue;
2594 }
2595
Samuel Antaof8b50122015-07-13 22:54:53 +00002596 // Check if this is a TLS variable. If TLS is not being supported, produce
2597 // the corresponding diagnostic.
2598 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2599 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2600 getLangOpts().OpenMPUseTLS &&
2601 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002602 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2603 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002604 Diag(ILoc, diag::err_omp_var_thread_local)
2605 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002606 bool IsDecl =
2607 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2608 Diag(VD->getLocation(),
2609 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2610 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002611 continue;
2612 }
2613
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002614 // Check if initial value of threadprivate variable reference variable with
2615 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002616 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002617 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002618 if (Checker.Visit(Init))
2619 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002620 }
2621
Alexey Bataeved09d242014-05-28 05:53:51 +00002622 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002623 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002624 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2625 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002626 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002627 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002628 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002629 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002630 if (!Vars.empty()) {
2631 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2632 Vars);
2633 D->setAccess(AS_public);
2634 }
2635 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002636}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002637
Alexey Bataev27ef9512019-03-20 20:14:22 +00002638static OMPAllocateDeclAttr::AllocatorTypeTy
2639getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2640 if (!Allocator)
2641 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2642 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2643 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002644 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002645 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002646 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002647 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002648 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2649 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2650 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002651 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002652 llvm::FoldingSetNodeID AEId, DAEId;
2653 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2654 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2655 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002656 AllocatorKindRes = AllocatorKind;
2657 break;
2658 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002659 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002660 return AllocatorKindRes;
2661}
2662
Alexey Bataeve106f252019-04-01 14:25:31 +00002663static bool checkPreviousOMPAllocateAttribute(
2664 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2665 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2666 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2667 return false;
2668 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2669 Expr *PrevAllocator = A->getAllocator();
2670 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2671 getAllocatorKind(S, Stack, PrevAllocator);
2672 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2673 if (AllocatorsMatch &&
2674 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2675 Allocator && PrevAllocator) {
2676 const Expr *AE = Allocator->IgnoreParenImpCasts();
2677 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2678 llvm::FoldingSetNodeID AEId, PAEId;
2679 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2680 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2681 AllocatorsMatch = AEId == PAEId;
2682 }
2683 if (!AllocatorsMatch) {
2684 SmallString<256> AllocatorBuffer;
2685 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2686 if (Allocator)
2687 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2688 SmallString<256> PrevAllocatorBuffer;
2689 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2690 if (PrevAllocator)
2691 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2692 S.getPrintingPolicy());
2693
2694 SourceLocation AllocatorLoc =
2695 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2696 SourceRange AllocatorRange =
2697 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2698 SourceLocation PrevAllocatorLoc =
2699 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2700 SourceRange PrevAllocatorRange =
2701 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2702 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2703 << (Allocator ? 1 : 0) << AllocatorStream.str()
2704 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2705 << AllocatorRange;
2706 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2707 << PrevAllocatorRange;
2708 return true;
2709 }
2710 return false;
2711}
2712
2713static void
2714applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2715 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2716 Expr *Allocator, SourceRange SR) {
2717 if (VD->hasAttr<OMPAllocateDeclAttr>())
2718 return;
2719 if (Allocator &&
2720 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2721 Allocator->isInstantiationDependent() ||
2722 Allocator->containsUnexpandedParameterPack()))
2723 return;
2724 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2725 Allocator, SR);
2726 VD->addAttr(A);
2727 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2728 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2729}
2730
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002731Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2732 SourceLocation Loc, ArrayRef<Expr *> VarList,
2733 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2734 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2735 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002736 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002737 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2738 // allocate directives that appear in a target region must specify an
2739 // allocator clause unless a requires directive with the dynamic_allocators
2740 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002741 if (LangOpts.OpenMPIsDevice &&
2742 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002743 targetDiag(Loc, diag::err_expected_allocator_clause);
2744 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002745 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002746 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002747 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2748 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002749 SmallVector<Expr *, 8> Vars;
2750 for (Expr *RefExpr : VarList) {
2751 auto *DE = cast<DeclRefExpr>(RefExpr);
2752 auto *VD = cast<VarDecl>(DE->getDecl());
2753
2754 // Check if this is a TLS variable or global register.
2755 if (VD->getTLSKind() != VarDecl::TLS_None ||
2756 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2757 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2758 !VD->isLocalVarDecl()))
2759 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002760
Alexey Bataev282555a2019-03-19 20:33:44 +00002761 // If the used several times in the allocate directive, the same allocator
2762 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002763 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2764 AllocatorKind, Allocator))
2765 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002766
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002767 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2768 // If a list item has a static storage type, the allocator expression in the
2769 // allocator clause must be a constant expression that evaluates to one of
2770 // the predefined memory allocator values.
2771 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002772 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002773 Diag(Allocator->getExprLoc(),
2774 diag::err_omp_expected_predefined_allocator)
2775 << Allocator->getSourceRange();
2776 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2777 VarDecl::DeclarationOnly;
2778 Diag(VD->getLocation(),
2779 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2780 << VD;
2781 continue;
2782 }
2783 }
2784
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002785 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002786 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2787 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002788 }
2789 if (Vars.empty())
2790 return nullptr;
2791 if (!Owner)
2792 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002793 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002794 D->setAccess(AS_public);
2795 Owner->addDecl(D);
2796 return DeclGroupPtrTy::make(DeclGroupRef(D));
2797}
2798
2799Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002800Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2801 ArrayRef<OMPClause *> ClauseList) {
2802 OMPRequiresDecl *D = nullptr;
2803 if (!CurContext->isFileContext()) {
2804 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2805 } else {
2806 D = CheckOMPRequiresDecl(Loc, ClauseList);
2807 if (D) {
2808 CurContext->addDecl(D);
2809 DSAStack->addRequiresDecl(D);
2810 }
2811 }
2812 return DeclGroupPtrTy::make(DeclGroupRef(D));
2813}
2814
2815OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2816 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002817 /// For target specific clauses, the requires directive cannot be
2818 /// specified after the handling of any of the target regions in the
2819 /// current compilation unit.
2820 ArrayRef<SourceLocation> TargetLocations =
2821 DSAStack->getEncounteredTargetLocs();
2822 if (!TargetLocations.empty()) {
2823 for (const OMPClause *CNew : ClauseList) {
2824 // Check if any of the requires clauses affect target regions.
2825 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2826 isa<OMPUnifiedAddressClause>(CNew) ||
2827 isa<OMPReverseOffloadClause>(CNew) ||
2828 isa<OMPDynamicAllocatorsClause>(CNew)) {
2829 Diag(Loc, diag::err_omp_target_before_requires)
2830 << getOpenMPClauseName(CNew->getClauseKind());
2831 for (SourceLocation TargetLoc : TargetLocations) {
2832 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2833 }
2834 }
2835 }
2836 }
2837
Kelvin Li1408f912018-09-26 04:28:39 +00002838 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2839 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2840 ClauseList);
2841 return nullptr;
2842}
2843
Alexey Bataeve3727102018-04-18 15:57:46 +00002844static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2845 const ValueDecl *D,
2846 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002847 bool IsLoopIterVar = false) {
2848 if (DVar.RefExpr) {
2849 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2850 << getOpenMPClauseName(DVar.CKind);
2851 return;
2852 }
2853 enum {
2854 PDSA_StaticMemberShared,
2855 PDSA_StaticLocalVarShared,
2856 PDSA_LoopIterVarPrivate,
2857 PDSA_LoopIterVarLinear,
2858 PDSA_LoopIterVarLastprivate,
2859 PDSA_ConstVarShared,
2860 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002861 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002862 PDSA_LocalVarPrivate,
2863 PDSA_Implicit
2864 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002865 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002866 auto ReportLoc = D->getLocation();
2867 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002868 if (IsLoopIterVar) {
2869 if (DVar.CKind == OMPC_private)
2870 Reason = PDSA_LoopIterVarPrivate;
2871 else if (DVar.CKind == OMPC_lastprivate)
2872 Reason = PDSA_LoopIterVarLastprivate;
2873 else
2874 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002875 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2876 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002877 Reason = PDSA_TaskVarFirstprivate;
2878 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002879 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002880 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002881 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002882 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002883 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002884 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002885 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002886 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002887 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002888 ReportHint = true;
2889 Reason = PDSA_LocalVarPrivate;
2890 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002891 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002892 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002893 << Reason << ReportHint
2894 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2895 } else if (DVar.ImplicitDSALoc.isValid()) {
2896 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2897 << getOpenMPClauseName(DVar.CKind);
2898 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002899}
2900
cchene06f3e02019-11-15 13:02:06 -05002901static OpenMPMapClauseKind
2902getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
2903 bool IsAggregateOrDeclareTarget) {
2904 OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
2905 switch (M) {
2906 case OMPC_DEFAULTMAP_MODIFIER_alloc:
2907 Kind = OMPC_MAP_alloc;
2908 break;
2909 case OMPC_DEFAULTMAP_MODIFIER_to:
2910 Kind = OMPC_MAP_to;
2911 break;
2912 case OMPC_DEFAULTMAP_MODIFIER_from:
2913 Kind = OMPC_MAP_from;
2914 break;
2915 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
2916 Kind = OMPC_MAP_tofrom;
2917 break;
2918 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
2919 case OMPC_DEFAULTMAP_MODIFIER_last:
2920 llvm_unreachable("Unexpected defaultmap implicit behavior");
2921 case OMPC_DEFAULTMAP_MODIFIER_none:
2922 case OMPC_DEFAULTMAP_MODIFIER_default:
2923 case OMPC_DEFAULTMAP_MODIFIER_unknown:
2924 // IsAggregateOrDeclareTarget could be true if:
2925 // 1. the implicit behavior for aggregate is tofrom
2926 // 2. it's a declare target link
2927 if (IsAggregateOrDeclareTarget) {
2928 Kind = OMPC_MAP_tofrom;
2929 break;
2930 }
2931 llvm_unreachable("Unexpected defaultmap implicit behavior");
2932 }
2933 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
2934 return Kind;
2935}
2936
Alexey Bataev758e55e2013-09-06 18:03:48 +00002937namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002938class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002939 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002940 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002941 bool ErrorFound = false;
Alexey Bataevc09c0652019-10-29 10:06:11 -04002942 bool TryCaptureCXXThisMembers = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00002943 CapturedStmt *CS = nullptr;
2944 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
cchene06f3e02019-11-15 13:02:06 -05002945 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
Alexey Bataeve3727102018-04-18 15:57:46 +00002946 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2947 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002948
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002949 void VisitSubCaptures(OMPExecutableDirective *S) {
2950 // Check implicitly captured variables.
2951 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2952 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002953 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataevc09c0652019-10-29 10:06:11 -04002954 // Try to capture inner this->member references to generate correct mappings
2955 // and diagnostics.
2956 if (TryCaptureCXXThisMembers ||
2957 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2958 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2959 [](const CapturedStmt::Capture &C) {
2960 return C.capturesThis();
2961 }))) {
2962 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2963 TryCaptureCXXThisMembers = true;
2964 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2965 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2966 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002967 }
2968
Alexey Bataev758e55e2013-09-06 18:03:48 +00002969public:
2970 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataevc09c0652019-10-29 10:06:11 -04002971 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
2972 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
2973 E->isInstantiationDependent())
Alexey Bataev07b79c22016-04-29 09:56:11 +00002974 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002975 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002976 // Check the datasharing rules for the expressions in the clauses.
2977 if (!CS) {
2978 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2979 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2980 Visit(CED->getInit());
2981 return;
2982 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002983 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2984 // Do not analyze internal variables and do not enclose them into
2985 // implicit clauses.
2986 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002987 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002988 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002989 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002990 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002991
Alexey Bataeve3727102018-04-18 15:57:46 +00002992 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002993 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002994 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002995 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002996
Alexey Bataevafe50572017-10-06 17:00:28 +00002997 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002998 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002999 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00003000 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00003001 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3002 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00003003 return;
3004
Alexey Bataeve3727102018-04-18 15:57:46 +00003005 SourceLocation ELoc = E->getExprLoc();
3006 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003007 // The default(none) clause requires that each variable that is referenced
3008 // in the construct, and does not have a predetermined data-sharing
3009 // attribute, must have its data-sharing attribute explicitly determined
3010 // by being listed in a data-sharing attribute clause.
3011 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00003012 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00003013 VarsWithInheritedDSA.count(VD) == 0) {
3014 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003015 return;
3016 }
3017
cchene06f3e02019-11-15 13:02:06 -05003018 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3019 // If implicit-behavior is none, each variable referenced in the
3020 // construct that does not have a predetermined data-sharing attribute
3021 // and does not appear in a to or link clause on a declare target
3022 // directive must be listed in a data-mapping attribute clause, a
3023 // data-haring attribute clause (including a data-sharing attribute
3024 // clause on a combined construct where target. is one of the
3025 // constituent constructs), or an is_device_ptr clause.
Alexey Bataev6f7c8762019-11-22 11:09:33 -05003026 OpenMPDefaultmapClauseKind ClauseKind =
3027 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
cchene06f3e02019-11-15 13:02:06 -05003028 if (SemaRef.getLangOpts().OpenMP >= 50) {
3029 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3030 OMPC_DEFAULTMAP_MODIFIER_none;
3031 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3032 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3033 // Only check for data-mapping attribute and is_device_ptr here
3034 // since we have already make sure that the declaration does not
3035 // have a data-sharing attribute above
3036 if (!Stack->checkMappableExprComponentListsForDecl(
3037 VD, /*CurrentRegionOnly=*/true,
3038 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3039 MapExprComponents,
3040 OpenMPClauseKind) {
3041 auto MI = MapExprComponents.rbegin();
3042 auto ME = MapExprComponents.rend();
3043 return MI != ME && MI->getAssociatedDeclaration() == VD;
3044 })) {
3045 VarsWithInheritedDSA[VD] = E;
3046 return;
3047 }
3048 }
3049 }
3050
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003051 if (isOpenMPTargetExecutionDirective(DKind) &&
3052 !Stack->isLoopControlVariable(VD).first) {
3053 if (!Stack->checkMappableExprComponentListsForDecl(
3054 VD, /*CurrentRegionOnly=*/true,
3055 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3056 StackComponents,
3057 OpenMPClauseKind) {
3058 // Variable is used if it has been marked as an array, array
3059 // section or the variable iself.
3060 return StackComponents.size() == 1 ||
3061 std::all_of(
3062 std::next(StackComponents.rbegin()),
3063 StackComponents.rend(),
3064 [](const OMPClauseMappableExprCommon::
3065 MappableComponent &MC) {
3066 return MC.getAssociatedDeclaration() ==
3067 nullptr &&
3068 (isa<OMPArraySectionExpr>(
3069 MC.getAssociatedExpression()) ||
3070 isa<ArraySubscriptExpr>(
3071 MC.getAssociatedExpression()));
3072 });
3073 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003074 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003075 // By default lambdas are captured as firstprivates.
3076 if (const auto *RD =
3077 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003078 IsFirstprivate = RD->isLambda();
3079 IsFirstprivate =
cchene06f3e02019-11-15 13:02:06 -05003080 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3081 if (IsFirstprivate) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003082 ImplicitFirstprivate.emplace_back(E);
cchene06f3e02019-11-15 13:02:06 -05003083 } else {
3084 OpenMPDefaultmapClauseModifier M =
3085 Stack->getDefaultmapModifier(ClauseKind);
3086 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3087 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3088 ImplicitMap[Kind].emplace_back(E);
3089 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003090 return;
3091 }
3092 }
3093
Alexey Bataev758e55e2013-09-06 18:03:48 +00003094 // OpenMP [2.9.3.6, Restrictions, p.2]
3095 // A list item that appears in a reduction clause of the innermost
3096 // enclosing worksharing or parallel construct may not be accessed in an
3097 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003098 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003099 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3100 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003101 return isOpenMPParallelDirective(K) ||
3102 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3103 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00003104 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003105 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00003106 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00003107 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003108 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00003109 return;
3110 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003111
3112 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003113 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003114 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00003115 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003116 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00003117 return;
3118 }
3119
3120 // Store implicitly used globals with declare target link for parent
3121 // target.
3122 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3123 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3124 Stack->addToParentTargetRegionLinkGlobals(E);
3125 return;
3126 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003127 }
3128 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003129 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00003130 if (E->isTypeDependent() || E->isValueDependent() ||
3131 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3132 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003133 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003134 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00003135 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003136 if (!FD)
3137 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003138 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003139 // Check if the variable has explicit DSA set and stop analysis if it
3140 // so.
3141 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3142 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003143
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003144 if (isOpenMPTargetExecutionDirective(DKind) &&
3145 !Stack->isLoopControlVariable(FD).first &&
3146 !Stack->checkMappableExprComponentListsForDecl(
3147 FD, /*CurrentRegionOnly=*/true,
3148 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3149 StackComponents,
3150 OpenMPClauseKind) {
3151 return isa<CXXThisExpr>(
3152 cast<MemberExpr>(
3153 StackComponents.back().getAssociatedExpression())
3154 ->getBase()
3155 ->IgnoreParens());
3156 })) {
3157 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3158 // A bit-field cannot appear in a map clause.
3159 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003160 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003161 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00003162
3163 // Check to see if the member expression is referencing a class that
3164 // has already been explicitly mapped
3165 if (Stack->isClassPreviouslyMapped(TE->getType()))
3166 return;
3167
cchene06f3e02019-11-15 13:02:06 -05003168 OpenMPDefaultmapClauseModifier Modifier =
3169 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3170 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3171 Modifier, /*IsAggregateOrDeclareTarget*/ true);
3172 ImplicitMap[Kind].emplace_back(E);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003173 return;
3174 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003175
Alexey Bataeve3727102018-04-18 15:57:46 +00003176 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003177 // OpenMP [2.9.3.6, Restrictions, p.2]
3178 // A list item that appears in a reduction clause of the innermost
3179 // enclosing worksharing or parallel construct may not be accessed in
3180 // an explicit task.
3181 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003182 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3183 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003184 return isOpenMPParallelDirective(K) ||
3185 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3186 },
3187 /*FromParent=*/true);
3188 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3189 ErrorFound = true;
3190 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003191 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003192 return;
3193 }
3194
3195 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003196 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003197 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00003198 !Stack->isLoopControlVariable(FD).first) {
3199 // Check if there is a captured expression for the current field in the
3200 // region. Do not mark it as firstprivate unless there is no captured
3201 // expression.
3202 // TODO: try to make it firstprivate.
3203 if (DVar.CKind != OMPC_unknown)
3204 ImplicitFirstprivate.push_back(E);
3205 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003206 return;
3207 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003208 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003209 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00003210 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003211 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003212 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003213 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003214 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3215 if (!Stack->checkMappableExprComponentListsForDecl(
3216 VD, /*CurrentRegionOnly=*/true,
3217 [&CurComponents](
3218 OMPClauseMappableExprCommon::MappableExprComponentListRef
3219 StackComponents,
3220 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003221 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003222 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003223 for (const auto &SC : llvm::reverse(StackComponents)) {
3224 // Do both expressions have the same kind?
3225 if (CCI->getAssociatedExpression()->getStmtClass() !=
3226 SC.getAssociatedExpression()->getStmtClass())
3227 if (!(isa<OMPArraySectionExpr>(
3228 SC.getAssociatedExpression()) &&
3229 isa<ArraySubscriptExpr>(
3230 CCI->getAssociatedExpression())))
3231 return false;
3232
Alexey Bataeve3727102018-04-18 15:57:46 +00003233 const Decl *CCD = CCI->getAssociatedDeclaration();
3234 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003235 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3236 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3237 if (SCD != CCD)
3238 return false;
3239 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003240 if (CCI == CCE)
3241 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003242 }
3243 return true;
3244 })) {
3245 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003246 }
Alexey Bataevc09c0652019-10-29 10:06:11 -04003247 } else if (!TryCaptureCXXThisMembers) {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003248 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003249 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003251 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003252 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003253 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003254 // for task|target directives.
3255 // Skip analysis of arguments of implicitly defined map clause for target
3256 // directives.
3257 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3258 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003259 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003260 if (CC)
3261 Visit(CC);
3262 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003263 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003264 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003265 // Check implicitly captured variables.
3266 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003267 }
3268 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003269 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003270 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003271 // Check implicitly captured variables in the task-based directives to
3272 // check if they must be firstprivatized.
3273 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003274 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003275 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003276 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003277
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003278 void visitSubCaptures(CapturedStmt *S) {
3279 for (const CapturedStmt::Capture &Cap : S->captures()) {
3280 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3281 continue;
3282 VarDecl *VD = Cap.getCapturedVar();
3283 // Do not try to map the variable if it or its sub-component was mapped
3284 // already.
3285 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3286 Stack->checkMappableExprComponentListsForDecl(
3287 VD, /*CurrentRegionOnly=*/true,
3288 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3289 OpenMPClauseKind) { return true; }))
3290 continue;
3291 DeclRefExpr *DRE = buildDeclRefExpr(
3292 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3293 Cap.getLocation(), /*RefersToCapture=*/true);
3294 Visit(DRE);
3295 }
3296 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003297 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003298 ArrayRef<Expr *> getImplicitFirstprivate() const {
3299 return ImplicitFirstprivate;
3300 }
cchene06f3e02019-11-15 13:02:06 -05003301 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3302 return ImplicitMap[Kind];
3303 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003304 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003305 return VarsWithInheritedDSA;
3306 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003307
Alexey Bataev7ff55242014-06-19 09:13:45 +00003308 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003309 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3310 // Process declare target link variables for the target directives.
3311 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3312 for (DeclRefExpr *E : Stack->getLinkGlobals())
3313 Visit(E);
3314 }
3315 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003316};
Alexey Bataeved09d242014-05-28 05:53:51 +00003317} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003318
Alexey Bataevbae9a792014-06-27 10:37:06 +00003319void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003320 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003321 case OMPD_parallel:
3322 case OMPD_parallel_for:
3323 case OMPD_parallel_for_simd:
3324 case OMPD_parallel_sections:
cchen47d60942019-12-05 13:43:48 -05003325 case OMPD_parallel_master:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003326 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003327 case OMPD_teams_distribute:
3328 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003329 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003330 QualType KmpInt32PtrTy =
3331 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003332 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003333 std::make_pair(".global_tid.", KmpInt32PtrTy),
3334 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3335 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003336 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003337 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3338 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003339 break;
3340 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003341 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003342 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003343 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003344 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003345 case OMPD_target_teams_distribute:
3346 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003347 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3348 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3349 QualType KmpInt32PtrTy =
3350 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3351 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003352 FunctionProtoType::ExtProtoInfo EPI;
3353 EPI.Variadic = true;
3354 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3355 Sema::CapturedParamNameType Params[] = {
3356 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003357 std::make_pair(".part_id.", KmpInt32PtrTy),
3358 std::make_pair(".privates.", VoidPtrTy),
3359 std::make_pair(
3360 ".copy_fn.",
3361 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003362 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3363 std::make_pair(StringRef(), QualType()) // __context with shared vars
3364 };
3365 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003366 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003367 // Mark this captured region as inlined, because we don't use outlined
3368 // function directly.
3369 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3370 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003371 Context, {}, AttributeCommonInfo::AS_Keyword,
3372 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003373 Sema::CapturedParamNameType ParamsTarget[] = {
3374 std::make_pair(StringRef(), QualType()) // __context with shared vars
3375 };
3376 // Start a captured region for 'target' with no implicit parameters.
3377 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003378 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003379 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003380 std::make_pair(".global_tid.", KmpInt32PtrTy),
3381 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3382 std::make_pair(StringRef(), QualType()) // __context with shared vars
3383 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003384 // Start a captured region for 'teams' or 'parallel'. Both regions have
3385 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003386 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003387 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003388 break;
3389 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003390 case OMPD_target:
3391 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003392 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3393 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3394 QualType KmpInt32PtrTy =
3395 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3396 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003397 FunctionProtoType::ExtProtoInfo EPI;
3398 EPI.Variadic = true;
3399 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3400 Sema::CapturedParamNameType Params[] = {
3401 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003402 std::make_pair(".part_id.", KmpInt32PtrTy),
3403 std::make_pair(".privates.", VoidPtrTy),
3404 std::make_pair(
3405 ".copy_fn.",
3406 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003407 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3408 std::make_pair(StringRef(), QualType()) // __context with shared vars
3409 };
3410 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003411 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003412 // Mark this captured region as inlined, because we don't use outlined
3413 // function directly.
3414 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3415 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003416 Context, {}, AttributeCommonInfo::AS_Keyword,
3417 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003418 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003419 std::make_pair(StringRef(), QualType()),
3420 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003421 break;
3422 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003423 case OMPD_simd:
3424 case OMPD_for:
3425 case OMPD_for_simd:
3426 case OMPD_sections:
3427 case OMPD_section:
3428 case OMPD_single:
3429 case OMPD_master:
3430 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003431 case OMPD_taskgroup:
3432 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003433 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003434 case OMPD_ordered:
3435 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003436 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003437 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003438 std::make_pair(StringRef(), QualType()) // __context with shared vars
3439 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003440 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3441 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003442 break;
3443 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003444 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003445 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3446 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3447 QualType KmpInt32PtrTy =
3448 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3449 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003450 FunctionProtoType::ExtProtoInfo EPI;
3451 EPI.Variadic = true;
3452 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003453 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003454 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003455 std::make_pair(".part_id.", KmpInt32PtrTy),
3456 std::make_pair(".privates.", VoidPtrTy),
3457 std::make_pair(
3458 ".copy_fn.",
3459 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003460 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003461 std::make_pair(StringRef(), QualType()) // __context with shared vars
3462 };
3463 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3464 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003465 // Mark this captured region as inlined, because we don't use outlined
3466 // function directly.
3467 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3468 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003469 Context, {}, AttributeCommonInfo::AS_Keyword,
3470 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003471 break;
3472 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003473 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003474 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003475 case OMPD_master_taskloop:
3476 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003477 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003478 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3479 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003480 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003481 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3482 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003483 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003484 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3485 .withConst();
3486 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3487 QualType KmpInt32PtrTy =
3488 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3489 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003490 FunctionProtoType::ExtProtoInfo EPI;
3491 EPI.Variadic = true;
3492 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003493 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003494 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003495 std::make_pair(".part_id.", KmpInt32PtrTy),
3496 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003497 std::make_pair(
3498 ".copy_fn.",
3499 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3500 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3501 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003502 std::make_pair(".ub.", KmpUInt64Ty),
3503 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003504 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003505 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003506 std::make_pair(StringRef(), QualType()) // __context with shared vars
3507 };
3508 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3509 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003510 // Mark this captured region as inlined, because we don't use outlined
3511 // function directly.
3512 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3513 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003514 Context, {}, AttributeCommonInfo::AS_Keyword,
3515 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003516 break;
3517 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04003518 case OMPD_parallel_master_taskloop:
3519 case OMPD_parallel_master_taskloop_simd: {
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003520 QualType KmpInt32Ty =
3521 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3522 .withConst();
3523 QualType KmpUInt64Ty =
3524 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3525 .withConst();
3526 QualType KmpInt64Ty =
3527 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3528 .withConst();
3529 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3530 QualType KmpInt32PtrTy =
3531 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3532 Sema::CapturedParamNameType ParamsParallel[] = {
3533 std::make_pair(".global_tid.", KmpInt32PtrTy),
3534 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3535 std::make_pair(StringRef(), QualType()) // __context with shared vars
3536 };
3537 // Start a captured region for 'parallel'.
3538 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3539 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3540 QualType Args[] = {VoidPtrTy};
3541 FunctionProtoType::ExtProtoInfo EPI;
3542 EPI.Variadic = true;
3543 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3544 Sema::CapturedParamNameType Params[] = {
3545 std::make_pair(".global_tid.", KmpInt32Ty),
3546 std::make_pair(".part_id.", KmpInt32PtrTy),
3547 std::make_pair(".privates.", VoidPtrTy),
3548 std::make_pair(
3549 ".copy_fn.",
3550 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3551 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3552 std::make_pair(".lb.", KmpUInt64Ty),
3553 std::make_pair(".ub.", KmpUInt64Ty),
3554 std::make_pair(".st.", KmpInt64Ty),
3555 std::make_pair(".liter.", KmpInt32Ty),
3556 std::make_pair(".reductions.", VoidPtrTy),
3557 std::make_pair(StringRef(), QualType()) // __context with shared vars
3558 };
3559 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3560 Params, /*OpenMPCaptureLevel=*/2);
3561 // Mark this captured region as inlined, because we don't use outlined
3562 // function directly.
3563 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3564 AlwaysInlineAttr::CreateImplicit(
3565 Context, {}, AttributeCommonInfo::AS_Keyword,
3566 AlwaysInlineAttr::Keyword_forceinline));
3567 break;
3568 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003569 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003570 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003571 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003572 QualType KmpInt32PtrTy =
3573 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3574 Sema::CapturedParamNameType Params[] = {
3575 std::make_pair(".global_tid.", KmpInt32PtrTy),
3576 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003577 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3578 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003579 std::make_pair(StringRef(), QualType()) // __context with shared vars
3580 };
3581 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3582 Params);
3583 break;
3584 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003585 case OMPD_target_teams_distribute_parallel_for:
3586 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003587 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003588 QualType KmpInt32PtrTy =
3589 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003590 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003591
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003592 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003593 FunctionProtoType::ExtProtoInfo EPI;
3594 EPI.Variadic = true;
3595 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3596 Sema::CapturedParamNameType Params[] = {
3597 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003598 std::make_pair(".part_id.", KmpInt32PtrTy),
3599 std::make_pair(".privates.", VoidPtrTy),
3600 std::make_pair(
3601 ".copy_fn.",
3602 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003603 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3604 std::make_pair(StringRef(), QualType()) // __context with shared vars
3605 };
3606 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003607 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003608 // Mark this captured region as inlined, because we don't use outlined
3609 // function directly.
3610 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3611 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003612 Context, {}, AttributeCommonInfo::AS_Keyword,
3613 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003614 Sema::CapturedParamNameType ParamsTarget[] = {
3615 std::make_pair(StringRef(), QualType()) // __context with shared vars
3616 };
3617 // Start a captured region for 'target' with no implicit parameters.
3618 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003619 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003620
3621 Sema::CapturedParamNameType ParamsTeams[] = {
3622 std::make_pair(".global_tid.", KmpInt32PtrTy),
3623 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3624 std::make_pair(StringRef(), QualType()) // __context with shared vars
3625 };
3626 // Start a captured region for 'target' with no implicit parameters.
3627 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003628 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003629
3630 Sema::CapturedParamNameType ParamsParallel[] = {
3631 std::make_pair(".global_tid.", KmpInt32PtrTy),
3632 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003633 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3634 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003635 std::make_pair(StringRef(), QualType()) // __context with shared vars
3636 };
3637 // Start a captured region for 'teams' or 'parallel'. Both regions have
3638 // the same implicit parameters.
3639 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003640 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003641 break;
3642 }
3643
Alexey Bataev46506272017-12-05 17:41:34 +00003644 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003645 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003646 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003647 QualType KmpInt32PtrTy =
3648 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3649
3650 Sema::CapturedParamNameType ParamsTeams[] = {
3651 std::make_pair(".global_tid.", KmpInt32PtrTy),
3652 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3653 std::make_pair(StringRef(), QualType()) // __context with shared vars
3654 };
3655 // Start a captured region for 'target' with no implicit parameters.
3656 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003657 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003658
3659 Sema::CapturedParamNameType ParamsParallel[] = {
3660 std::make_pair(".global_tid.", KmpInt32PtrTy),
3661 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003662 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3663 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003664 std::make_pair(StringRef(), QualType()) // __context with shared vars
3665 };
3666 // Start a captured region for 'teams' or 'parallel'. Both regions have
3667 // the same implicit parameters.
3668 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003669 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003670 break;
3671 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003672 case OMPD_target_update:
3673 case OMPD_target_enter_data:
3674 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003675 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3676 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3677 QualType KmpInt32PtrTy =
3678 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3679 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003680 FunctionProtoType::ExtProtoInfo EPI;
3681 EPI.Variadic = true;
3682 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3683 Sema::CapturedParamNameType Params[] = {
3684 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003685 std::make_pair(".part_id.", KmpInt32PtrTy),
3686 std::make_pair(".privates.", VoidPtrTy),
3687 std::make_pair(
3688 ".copy_fn.",
3689 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003690 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3691 std::make_pair(StringRef(), QualType()) // __context with shared vars
3692 };
3693 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3694 Params);
3695 // Mark this captured region as inlined, because we don't use outlined
3696 // function directly.
3697 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3698 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003699 Context, {}, AttributeCommonInfo::AS_Keyword,
3700 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003701 break;
3702 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003703 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003704 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003705 case OMPD_taskyield:
3706 case OMPD_barrier:
3707 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003708 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003709 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003710 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003711 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003712 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003713 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003714 case OMPD_declare_target:
3715 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003716 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003717 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003718 llvm_unreachable("OpenMP Directive is not allowed");
3719 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003720 llvm_unreachable("Unknown OpenMP directive");
3721 }
3722}
3723
Alexey Bataev0e100032019-10-14 16:44:01 +00003724int Sema::getNumberOfConstructScopes(unsigned Level) const {
3725 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3726}
3727
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003728int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3729 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3730 getOpenMPCaptureRegions(CaptureRegions, DKind);
3731 return CaptureRegions.size();
3732}
3733
Alexey Bataev3392d762016-02-16 11:18:12 +00003734static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003735 Expr *CaptureExpr, bool WithInit,
3736 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003737 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003738 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003739 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003740 QualType Ty = Init->getType();
3741 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003742 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003743 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003744 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003745 Ty = C.getPointerType(Ty);
3746 ExprResult Res =
3747 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3748 if (!Res.isUsable())
3749 return nullptr;
3750 Init = Res.get();
3751 }
Alexey Bataev61205072016-03-02 04:57:40 +00003752 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003753 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003754 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003755 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003756 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003757 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003758 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003759 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003760 return CED;
3761}
3762
Alexey Bataev61205072016-03-02 04:57:40 +00003763static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3764 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003765 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003766 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003767 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003768 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003769 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3770 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003771 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003772 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003773}
3774
Alexey Bataev5a3af132016-03-29 08:58:54 +00003775static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003776 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003777 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003778 OMPCapturedExprDecl *CD = buildCaptureDecl(
3779 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3780 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003781 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3782 CaptureExpr->getExprLoc());
3783 }
3784 ExprResult Res = Ref;
3785 if (!S.getLangOpts().CPlusPlus &&
3786 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003787 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003788 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003789 if (!Res.isUsable())
3790 return ExprError();
3791 }
3792 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003793}
3794
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003795namespace {
3796// OpenMP directives parsed in this section are represented as a
3797// CapturedStatement with an associated statement. If a syntax error
3798// is detected during the parsing of the associated statement, the
3799// compiler must abort processing and close the CapturedStatement.
3800//
3801// Combined directives such as 'target parallel' have more than one
3802// nested CapturedStatements. This RAII ensures that we unwind out
3803// of all the nested CapturedStatements when an error is found.
3804class CaptureRegionUnwinderRAII {
3805private:
3806 Sema &S;
3807 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003808 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003809
3810public:
3811 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3812 OpenMPDirectiveKind DKind)
3813 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3814 ~CaptureRegionUnwinderRAII() {
3815 if (ErrorFound) {
3816 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3817 while (--ThisCaptureLevel >= 0)
3818 S.ActOnCapturedRegionError();
3819 }
3820 }
3821};
3822} // namespace
3823
Alexey Bataevb600ae32019-07-01 17:46:52 +00003824void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3825 // Capture variables captured by reference in lambdas for target-based
3826 // directives.
3827 if (!CurContext->isDependentContext() &&
3828 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3829 isOpenMPTargetDataManagementDirective(
3830 DSAStack->getCurrentDirective()))) {
3831 QualType Type = V->getType();
3832 if (const auto *RD = Type.getCanonicalType()
3833 .getNonReferenceType()
3834 ->getAsCXXRecordDecl()) {
3835 bool SavedForceCaptureByReferenceInTargetExecutable =
3836 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3837 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3838 /*V=*/true);
3839 if (RD->isLambda()) {
3840 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3841 FieldDecl *ThisCapture;
3842 RD->getCaptureFields(Captures, ThisCapture);
3843 for (const LambdaCapture &LC : RD->captures()) {
3844 if (LC.getCaptureKind() == LCK_ByRef) {
3845 VarDecl *VD = LC.getCapturedVar();
3846 DeclContext *VDC = VD->getDeclContext();
3847 if (!VDC->Encloses(CurContext))
3848 continue;
3849 MarkVariableReferenced(LC.getLocation(), VD);
3850 } else if (LC.getCaptureKind() == LCK_This) {
3851 QualType ThisTy = getCurrentThisType();
3852 if (!ThisTy.isNull() &&
3853 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3854 CheckCXXThisCapture(LC.getLocation());
3855 }
3856 }
3857 }
3858 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3859 SavedForceCaptureByReferenceInTargetExecutable);
3860 }
3861 }
3862}
3863
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003864StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3865 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003866 bool ErrorFound = false;
3867 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3868 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003869 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003870 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003871 return StmtError();
3872 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003873
Alexey Bataev2ba67042017-11-28 21:11:44 +00003874 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3875 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003876 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003877 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003878 SmallVector<const OMPLinearClause *, 4> LCs;
3879 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003880 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003881 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003882 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3883 Clause->getClauseKind() == OMPC_in_reduction) {
3884 // Capture taskgroup task_reduction descriptors inside the tasking regions
3885 // with the corresponding in_reduction items.
3886 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003887 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003888 if (E)
3889 MarkDeclarationsReferencedInExpr(E);
3890 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003891 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003892 Clause->getClauseKind() == OMPC_copyprivate ||
3893 (getLangOpts().OpenMPUseTLS &&
3894 getASTContext().getTargetInfo().isTLSSupported() &&
3895 Clause->getClauseKind() == OMPC_copyin)) {
3896 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003897 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003898 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003899 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003900 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003901 }
3902 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003903 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003904 } else if (CaptureRegions.size() > 1 ||
3905 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003906 if (auto *C = OMPClauseWithPreInit::get(Clause))
3907 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003908 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003909 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003910 MarkDeclarationsReferencedInExpr(E);
3911 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003912 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003913 if (Clause->getClauseKind() == OMPC_schedule)
3914 SC = cast<OMPScheduleClause>(Clause);
3915 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003916 OC = cast<OMPOrderedClause>(Clause);
3917 else if (Clause->getClauseKind() == OMPC_linear)
3918 LCs.push_back(cast<OMPLinearClause>(Clause));
3919 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003920 // OpenMP, 2.7.1 Loop Construct, Restrictions
3921 // The nonmonotonic modifier cannot be specified if an ordered clause is
3922 // specified.
3923 if (SC &&
3924 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3925 SC->getSecondScheduleModifier() ==
3926 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3927 OC) {
3928 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3929 ? SC->getFirstScheduleModifierLoc()
3930 : SC->getSecondScheduleModifierLoc(),
3931 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003932 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003933 ErrorFound = true;
3934 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003935 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003936 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003937 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003938 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003939 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003940 ErrorFound = true;
3941 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003942 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3943 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3944 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003945 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003946 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3947 ErrorFound = true;
3948 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003949 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003950 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003951 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003952 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003953 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003954 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003955 // Mark all variables in private list clauses as used in inner region.
3956 // Required for proper codegen of combined directives.
3957 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003958 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003959 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003960 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3961 // Find the particular capture region for the clause if the
3962 // directive is a combined one with multiple capture regions.
3963 // If the directive is not a combined one, the capture region
3964 // associated with the clause is OMPD_unknown and is generated
3965 // only once.
3966 if (CaptureRegion == ThisCaptureRegion ||
3967 CaptureRegion == OMPD_unknown) {
3968 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003969 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003970 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3971 }
3972 }
3973 }
3974 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003975 if (++CompletedRegions == CaptureRegions.size())
3976 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003977 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003978 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003979 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003980}
3981
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003982static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3983 OpenMPDirectiveKind CancelRegion,
3984 SourceLocation StartLoc) {
3985 // CancelRegion is only needed for cancel and cancellation_point.
3986 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3987 return false;
3988
3989 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3990 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3991 return false;
3992
3993 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3994 << getOpenMPDirectiveName(CancelRegion);
3995 return true;
3996}
3997
Alexey Bataeve3727102018-04-18 15:57:46 +00003998static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003999 OpenMPDirectiveKind CurrentRegion,
4000 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004001 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004002 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004003 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004004 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4005 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004006 bool NestingProhibited = false;
4007 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00004008 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004009 enum {
4010 NoRecommend,
4011 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00004012 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004013 ShouldBeInTargetRegion,
4014 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004015 } Recommend = NoRecommend;
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004016 if (isOpenMPSimdDirective(ParentRegion) &&
4017 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4018 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4019 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004020 // OpenMP [2.16, Nesting of Regions]
4021 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004022 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00004023 // An ordered construct with the simd clause is the only OpenMP
4024 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00004025 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00004026 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4027 // message.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004028 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4029 // The only OpenMP constructs that can be encountered during execution of
4030 // a simd region are the atomic construct, the loop construct, the simd
4031 // construct and the ordered construct with the simd clause.
Kelvin Lifd8b5742016-07-01 14:30:25 +00004032 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4033 ? diag::err_omp_prohibited_region_simd
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004034 : diag::warn_omp_nesting_simd)
4035 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
Kelvin Lifd8b5742016-07-01 14:30:25 +00004036 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00004037 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004038 if (ParentRegion == OMPD_atomic) {
4039 // OpenMP [2.16, Nesting of Regions]
4040 // OpenMP constructs may not be nested inside an atomic region.
4041 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4042 return true;
4043 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004044 if (CurrentRegion == OMPD_section) {
4045 // OpenMP [2.7.2, sections Construct, Restrictions]
4046 // Orphaned section directives are prohibited. That is, the section
4047 // directives must appear within the sections construct and must not be
4048 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004049 if (ParentRegion != OMPD_sections &&
4050 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004051 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4052 << (ParentRegion != OMPD_unknown)
4053 << getOpenMPDirectiveName(ParentRegion);
4054 return true;
4055 }
4056 return false;
4057 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00004058 // Allow some constructs (except teams and cancellation constructs) to be
4059 // orphaned (they could be used in functions, called from OpenMP regions
4060 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00004061 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00004062 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4063 CurrentRegion != OMPD_cancellation_point &&
4064 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004065 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00004066 if (CurrentRegion == OMPD_cancellation_point ||
4067 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004068 // OpenMP [2.16, Nesting of Regions]
4069 // A cancellation point construct for which construct-type-clause is
4070 // taskgroup must be nested inside a task construct. A cancellation
4071 // point construct for which construct-type-clause is not taskgroup must
4072 // be closely nested inside an OpenMP construct that matches the type
4073 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00004074 // A cancel construct for which construct-type-clause is taskgroup must be
4075 // nested inside a task construct. A cancel construct for which
4076 // construct-type-clause is not taskgroup must be closely nested inside an
4077 // OpenMP construct that matches the type specified in
4078 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004079 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004080 !((CancelRegion == OMPD_parallel &&
4081 (ParentRegion == OMPD_parallel ||
4082 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00004083 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004084 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004085 ParentRegion == OMPD_target_parallel_for ||
4086 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004087 ParentRegion == OMPD_teams_distribute_parallel_for ||
4088 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004089 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
4090 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00004091 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4092 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00004093 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004094 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00004095 // OpenMP [2.16, Nesting of Regions]
4096 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004097 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00004098 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004099 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004100 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4101 // OpenMP [2.16, Nesting of Regions]
4102 // A critical region may not be nested (closely or otherwise) inside a
4103 // critical region with the same name. Note that this restriction is not
4104 // sufficient to prevent deadlock.
4105 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00004106 bool DeadLock = Stack->hasDirective(
4107 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4108 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00004109 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00004110 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4111 PreviousCriticalLoc = Loc;
4112 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004113 }
4114 return false;
David Majnemer9d168222016-08-05 17:44:54 +00004115 },
4116 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004117 if (DeadLock) {
4118 SemaRef.Diag(StartLoc,
4119 diag::err_omp_prohibited_region_critical_same_name)
4120 << CurrentName.getName();
4121 if (PreviousCriticalLoc.isValid())
4122 SemaRef.Diag(PreviousCriticalLoc,
4123 diag::note_omp_previous_critical_region);
4124 return true;
4125 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004126 } else if (CurrentRegion == OMPD_barrier) {
4127 // OpenMP [2.16, Nesting of Regions]
4128 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004129 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004130 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4131 isOpenMPTaskingDirective(ParentRegion) ||
4132 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004133 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004134 ParentRegion == OMPD_critical ||
4135 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00004136 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00004137 !isOpenMPParallelDirective(CurrentRegion) &&
4138 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004139 // OpenMP [2.16, Nesting of Regions]
4140 // A worksharing region may not be closely nested inside a worksharing,
4141 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004142 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4143 isOpenMPTaskingDirective(ParentRegion) ||
4144 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004145 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004146 ParentRegion == OMPD_critical ||
4147 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004148 Recommend = ShouldBeInParallelRegion;
4149 } else if (CurrentRegion == OMPD_ordered) {
4150 // OpenMP [2.16, Nesting of Regions]
4151 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00004152 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004153 // An ordered region must be closely nested inside a loop region (or
4154 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004155 // OpenMP [2.8.1,simd Construct, Restrictions]
4156 // An ordered construct with the simd clause is the only OpenMP construct
4157 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004158 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004159 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004160 !(isOpenMPSimdDirective(ParentRegion) ||
4161 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004162 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00004163 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004164 // OpenMP [2.16, Nesting of Regions]
4165 // If specified, a teams construct must be contained within a target
4166 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00004167 NestingProhibited =
4168 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4169 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4170 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00004171 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004172 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004173 }
Kelvin Libf594a52016-12-17 05:48:59 +00004174 if (!NestingProhibited &&
4175 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4176 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4177 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004178 // OpenMP [2.16, Nesting of Regions]
4179 // distribute, parallel, parallel sections, parallel workshare, and the
4180 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4181 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004182 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4183 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00004184 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004185 }
David Majnemer9d168222016-08-05 17:44:54 +00004186 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00004187 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004188 // OpenMP 4.5 [2.17 Nesting of Regions]
4189 // The region associated with the distribute construct must be strictly
4190 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00004191 NestingProhibited =
4192 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004193 Recommend = ShouldBeInTeamsRegion;
4194 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004195 if (!NestingProhibited &&
4196 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4197 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4198 // OpenMP 4.5 [2.17 Nesting of Regions]
4199 // If a target, target update, target data, target enter data, or
4200 // target exit data construct is encountered during execution of a
4201 // target region, the behavior is unspecified.
4202 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004203 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00004204 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004205 if (isOpenMPTargetExecutionDirective(K)) {
4206 OffendingRegion = K;
4207 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004208 }
4209 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004210 },
4211 false /* don't skip top directive */);
4212 CloseNesting = false;
4213 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004214 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00004215 if (OrphanSeen) {
4216 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4217 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4218 } else {
4219 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4220 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4221 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4222 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004223 return true;
4224 }
4225 }
4226 return false;
4227}
4228
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004229struct Kind2Unsigned {
4230 using argument_type = OpenMPDirectiveKind;
4231 unsigned operator()(argument_type DK) { return unsigned(DK); }
4232};
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004233static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4234 ArrayRef<OMPClause *> Clauses,
4235 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4236 bool ErrorFound = false;
4237 unsigned NamedModifiersNumber = 0;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004238 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4239 FoundNameModifiers.resize(unsigned(OMPD_unknown) + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004240 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004241 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004242 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4243 // At most one if clause without a directive-name-modifier can appear on
4244 // the directive.
4245 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4246 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004247 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004248 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4249 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4250 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004251 } else if (CurNM != OMPD_unknown) {
4252 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004253 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004254 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004255 FoundNameModifiers[CurNM] = IC;
4256 if (CurNM == OMPD_unknown)
4257 continue;
4258 // Check if the specified name modifier is allowed for the current
4259 // directive.
4260 // At most one if clause with the particular directive-name-modifier can
4261 // appear on the directive.
4262 bool MatchFound = false;
4263 for (auto NM : AllowedNameModifiers) {
4264 if (CurNM == NM) {
4265 MatchFound = true;
4266 break;
4267 }
4268 }
4269 if (!MatchFound) {
4270 S.Diag(IC->getNameModifierLoc(),
4271 diag::err_omp_wrong_if_directive_name_modifier)
4272 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4273 ErrorFound = true;
4274 }
4275 }
4276 }
4277 // If any if clause on the directive includes a directive-name-modifier then
4278 // all if clauses on the directive must include a directive-name-modifier.
4279 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4280 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004281 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004282 diag::err_omp_no_more_if_clause);
4283 } else {
4284 std::string Values;
4285 std::string Sep(", ");
4286 unsigned AllowedCnt = 0;
4287 unsigned TotalAllowedNum =
4288 AllowedNameModifiers.size() - NamedModifiersNumber;
4289 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4290 ++Cnt) {
4291 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4292 if (!FoundNameModifiers[NM]) {
4293 Values += "'";
4294 Values += getOpenMPDirectiveName(NM);
4295 Values += "'";
4296 if (AllowedCnt + 2 == TotalAllowedNum)
4297 Values += " or ";
4298 else if (AllowedCnt + 1 != TotalAllowedNum)
4299 Values += Sep;
4300 ++AllowedCnt;
4301 }
4302 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004303 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004304 diag::err_omp_unnamed_if_clause)
4305 << (TotalAllowedNum > 1) << Values;
4306 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004307 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004308 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4309 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004310 ErrorFound = true;
4311 }
4312 return ErrorFound;
4313}
4314
Alexey Bataev0860db92019-12-19 10:01:10 -05004315static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4316 SourceLocation &ELoc,
4317 SourceRange &ERange,
4318 bool AllowArraySection) {
Alexey Bataeve106f252019-04-01 14:25:31 +00004319 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4320 RefExpr->containsUnexpandedParameterPack())
4321 return std::make_pair(nullptr, true);
4322
4323 // OpenMP [3.1, C/C++]
4324 // A list item is a variable name.
4325 // OpenMP [2.9.3.3, Restrictions, p.1]
4326 // A variable that is part of another variable (as an array or
4327 // structure element) cannot appear in a private clause.
4328 RefExpr = RefExpr->IgnoreParens();
4329 enum {
4330 NoArrayExpr = -1,
4331 ArraySubscript = 0,
4332 OMPArraySection = 1
4333 } IsArrayExpr = NoArrayExpr;
4334 if (AllowArraySection) {
4335 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4336 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4337 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4338 Base = TempASE->getBase()->IgnoreParenImpCasts();
4339 RefExpr = Base;
4340 IsArrayExpr = ArraySubscript;
4341 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4342 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4343 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4344 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4345 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4346 Base = TempASE->getBase()->IgnoreParenImpCasts();
4347 RefExpr = Base;
4348 IsArrayExpr = OMPArraySection;
4349 }
4350 }
4351 ELoc = RefExpr->getExprLoc();
4352 ERange = RefExpr->getSourceRange();
4353 RefExpr = RefExpr->IgnoreParenImpCasts();
4354 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4355 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4356 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4357 (S.getCurrentThisType().isNull() || !ME ||
4358 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4359 !isa<FieldDecl>(ME->getMemberDecl()))) {
4360 if (IsArrayExpr != NoArrayExpr) {
4361 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4362 << ERange;
4363 } else {
4364 S.Diag(ELoc,
4365 AllowArraySection
4366 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4367 : diag::err_omp_expected_var_name_member_expr)
4368 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4369 }
4370 return std::make_pair(nullptr, false);
4371 }
4372 return std::make_pair(
4373 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4374}
4375
4376static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004377 ArrayRef<OMPClause *> Clauses) {
4378 assert(!S.CurContext->isDependentContext() &&
4379 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004380 auto AllocateRange =
4381 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004382 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4383 DeclToCopy;
4384 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4385 return isOpenMPPrivate(C->getClauseKind());
4386 });
4387 for (OMPClause *Cl : PrivateRange) {
4388 MutableArrayRef<Expr *>::iterator I, It, Et;
4389 if (Cl->getClauseKind() == OMPC_private) {
4390 auto *PC = cast<OMPPrivateClause>(Cl);
4391 I = PC->private_copies().begin();
4392 It = PC->varlist_begin();
4393 Et = PC->varlist_end();
4394 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4395 auto *PC = cast<OMPFirstprivateClause>(Cl);
4396 I = PC->private_copies().begin();
4397 It = PC->varlist_begin();
4398 Et = PC->varlist_end();
4399 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4400 auto *PC = cast<OMPLastprivateClause>(Cl);
4401 I = PC->private_copies().begin();
4402 It = PC->varlist_begin();
4403 Et = PC->varlist_end();
4404 } else if (Cl->getClauseKind() == OMPC_linear) {
4405 auto *PC = cast<OMPLinearClause>(Cl);
4406 I = PC->privates().begin();
4407 It = PC->varlist_begin();
4408 Et = PC->varlist_end();
4409 } else if (Cl->getClauseKind() == OMPC_reduction) {
4410 auto *PC = cast<OMPReductionClause>(Cl);
4411 I = PC->privates().begin();
4412 It = PC->varlist_begin();
4413 Et = PC->varlist_end();
4414 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4415 auto *PC = cast<OMPTaskReductionClause>(Cl);
4416 I = PC->privates().begin();
4417 It = PC->varlist_begin();
4418 Et = PC->varlist_end();
4419 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4420 auto *PC = cast<OMPInReductionClause>(Cl);
4421 I = PC->privates().begin();
4422 It = PC->varlist_begin();
4423 Et = PC->varlist_end();
4424 } else {
4425 llvm_unreachable("Expected private clause.");
4426 }
4427 for (Expr *E : llvm::make_range(It, Et)) {
4428 if (!*I) {
4429 ++I;
4430 continue;
4431 }
4432 SourceLocation ELoc;
4433 SourceRange ERange;
4434 Expr *SimpleRefExpr = E;
4435 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4436 /*AllowArraySection=*/true);
4437 DeclToCopy.try_emplace(Res.first,
4438 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4439 ++I;
4440 }
4441 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004442 for (OMPClause *C : AllocateRange) {
4443 auto *AC = cast<OMPAllocateClause>(C);
4444 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4445 getAllocatorKind(S, Stack, AC->getAllocator());
4446 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4447 // For task, taskloop or target directives, allocation requests to memory
4448 // allocators with the trait access set to thread result in unspecified
4449 // behavior.
4450 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4451 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4452 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4453 S.Diag(AC->getAllocator()->getExprLoc(),
4454 diag::warn_omp_allocate_thread_on_task_target_directive)
4455 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004456 }
4457 for (Expr *E : AC->varlists()) {
4458 SourceLocation ELoc;
4459 SourceRange ERange;
4460 Expr *SimpleRefExpr = E;
4461 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4462 ValueDecl *VD = Res.first;
4463 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4464 if (!isOpenMPPrivate(Data.CKind)) {
4465 S.Diag(E->getExprLoc(),
4466 diag::err_omp_expected_private_copy_for_allocate);
4467 continue;
4468 }
4469 VarDecl *PrivateVD = DeclToCopy[VD];
4470 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4471 AllocatorKind, AC->getAllocator()))
4472 continue;
4473 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4474 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004475 }
4476 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004477}
4478
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004479StmtResult Sema::ActOnOpenMPExecutableDirective(
4480 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4481 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4482 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004483 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004484 // First check CancelRegion which is then used in checkNestingOfRegions.
4485 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4486 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004487 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004488 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004489
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004490 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004491 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004492 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004493 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004494 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004495 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4496
4497 // Check default data sharing attributes for referenced variables.
4498 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004499 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4500 Stmt *S = AStmt;
4501 while (--ThisCaptureLevel >= 0)
4502 S = cast<CapturedStmt>(S)->getCapturedStmt();
4503 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004504 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4505 !isOpenMPTaskingDirective(Kind)) {
4506 // Visit subcaptures to generate implicit clauses for captured vars.
4507 auto *CS = cast<CapturedStmt>(AStmt);
4508 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4509 getOpenMPCaptureRegions(CaptureRegions, Kind);
4510 // Ignore outer tasking regions for target directives.
4511 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4512 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4513 DSAChecker.visitSubCaptures(CS);
4514 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004515 if (DSAChecker.isErrorFound())
4516 return StmtError();
4517 // Generate list of implicitly defined firstprivate variables.
4518 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004519
Alexey Bataev88202be2017-07-27 13:20:36 +00004520 SmallVector<Expr *, 4> ImplicitFirstprivates(
4521 DSAChecker.getImplicitFirstprivate().begin(),
4522 DSAChecker.getImplicitFirstprivate().end());
cchene06f3e02019-11-15 13:02:06 -05004523 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4524 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4525 ArrayRef<Expr *> ImplicitMap =
4526 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4527 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4528 }
Alexey Bataev88202be2017-07-27 13:20:36 +00004529 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004530 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004531 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004532 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004533 if (E)
4534 ImplicitFirstprivates.emplace_back(E);
4535 }
4536 }
4537 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004538 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004539 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4540 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004541 ClausesWithImplicit.push_back(Implicit);
4542 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004543 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004544 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004545 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004546 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004547 }
cchene06f3e02019-11-15 13:02:06 -05004548 int ClauseKindCnt = -1;
4549 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4550 ++ClauseKindCnt;
4551 if (ImplicitMap.empty())
4552 continue;
Michael Kruse4304e9d2019-02-19 16:38:20 +00004553 CXXScopeSpec MapperIdScopeSpec;
4554 DeclarationNameInfo MapperId;
cchene06f3e02019-11-15 13:02:06 -05004555 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004556 if (OMPClause *Implicit = ActOnOpenMPMapClause(
cchene06f3e02019-11-15 13:02:06 -05004557 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4558 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4559 ImplicitMap, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004560 ClausesWithImplicit.emplace_back(Implicit);
4561 ErrorFound |=
cchene06f3e02019-11-15 13:02:06 -05004562 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004563 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004564 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004565 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004566 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004567 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004568
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004569 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004570 switch (Kind) {
4571 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004572 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4573 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004574 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004575 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004576 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004577 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4578 VarsWithInheritedDSA);
Alexey Bataevd08c0562019-11-19 12:07:54 -05004579 if (LangOpts.OpenMP >= 50)
4580 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004581 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004582 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004583 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4584 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004585 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004586 case OMPD_for_simd:
4587 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4588 EndLoc, VarsWithInheritedDSA);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05004589 if (LangOpts.OpenMP >= 50)
4590 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004591 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004592 case OMPD_sections:
4593 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4594 EndLoc);
4595 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004596 case OMPD_section:
4597 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004598 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004599 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4600 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004601 case OMPD_single:
4602 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4603 EndLoc);
4604 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004605 case OMPD_master:
4606 assert(ClausesWithImplicit.empty() &&
4607 "No clauses are allowed for 'omp master' directive");
4608 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4609 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004610 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004611 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4612 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004613 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004614 case OMPD_parallel_for:
4615 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4616 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004617 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004618 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004619 case OMPD_parallel_for_simd:
4620 Res = ActOnOpenMPParallelForSimdDirective(
4621 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004622 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevf59614d2019-11-21 10:00:56 -05004623 if (LangOpts.OpenMP >= 50)
4624 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004625 break;
cchen47d60942019-12-05 13:43:48 -05004626 case OMPD_parallel_master:
4627 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
4628 StartLoc, EndLoc);
4629 AllowedNameModifiers.push_back(OMPD_parallel);
4630 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004631 case OMPD_parallel_sections:
4632 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4633 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004634 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004635 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004636 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004637 Res =
4638 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004639 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004640 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004641 case OMPD_taskyield:
4642 assert(ClausesWithImplicit.empty() &&
4643 "No clauses are allowed for 'omp taskyield' directive");
4644 assert(AStmt == nullptr &&
4645 "No associated statement allowed for 'omp taskyield' directive");
4646 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4647 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004648 case OMPD_barrier:
4649 assert(ClausesWithImplicit.empty() &&
4650 "No clauses are allowed for 'omp barrier' directive");
4651 assert(AStmt == nullptr &&
4652 "No associated statement allowed for 'omp barrier' directive");
4653 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4654 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004655 case OMPD_taskwait:
4656 assert(ClausesWithImplicit.empty() &&
4657 "No clauses are allowed for 'omp taskwait' directive");
4658 assert(AStmt == nullptr &&
4659 "No associated statement allowed for 'omp taskwait' directive");
4660 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4661 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004662 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004663 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4664 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004665 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004666 case OMPD_flush:
4667 assert(AStmt == nullptr &&
4668 "No associated statement allowed for 'omp flush' directive");
4669 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4670 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004671 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004672 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4673 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004674 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004675 case OMPD_atomic:
4676 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4677 EndLoc);
4678 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004679 case OMPD_teams:
4680 Res =
4681 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4682 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004683 case OMPD_target:
4684 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4685 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004686 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004687 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004688 case OMPD_target_parallel:
4689 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4690 StartLoc, EndLoc);
4691 AllowedNameModifiers.push_back(OMPD_target);
4692 AllowedNameModifiers.push_back(OMPD_parallel);
4693 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004694 case OMPD_target_parallel_for:
4695 Res = ActOnOpenMPTargetParallelForDirective(
4696 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4697 AllowedNameModifiers.push_back(OMPD_target);
4698 AllowedNameModifiers.push_back(OMPD_parallel);
4699 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004700 case OMPD_cancellation_point:
4701 assert(ClausesWithImplicit.empty() &&
4702 "No clauses are allowed for 'omp cancellation point' directive");
4703 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4704 "cancellation point' directive");
4705 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4706 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004707 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004708 assert(AStmt == nullptr &&
4709 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004710 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4711 CancelRegion);
4712 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004713 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004714 case OMPD_target_data:
4715 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4716 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004717 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004718 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004719 case OMPD_target_enter_data:
4720 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004721 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004722 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4723 break;
Samuel Antao72590762016-01-19 20:04:50 +00004724 case OMPD_target_exit_data:
4725 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004726 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004727 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4728 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004729 case OMPD_taskloop:
4730 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4731 EndLoc, VarsWithInheritedDSA);
4732 AllowedNameModifiers.push_back(OMPD_taskloop);
4733 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004734 case OMPD_taskloop_simd:
4735 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4736 EndLoc, VarsWithInheritedDSA);
4737 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev61205822019-12-04 09:50:21 -05004738 if (LangOpts.OpenMP >= 50)
4739 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004740 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004741 case OMPD_master_taskloop:
4742 Res = ActOnOpenMPMasterTaskLoopDirective(
4743 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4744 AllowedNameModifiers.push_back(OMPD_taskloop);
4745 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004746 case OMPD_master_taskloop_simd:
4747 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4748 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4749 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev853961f2019-12-05 09:50:18 -05004750 if (LangOpts.OpenMP >= 50)
4751 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004752 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004753 case OMPD_parallel_master_taskloop:
4754 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4755 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4756 AllowedNameModifiers.push_back(OMPD_taskloop);
4757 AllowedNameModifiers.push_back(OMPD_parallel);
4758 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004759 case OMPD_parallel_master_taskloop_simd:
4760 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4761 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4762 AllowedNameModifiers.push_back(OMPD_taskloop);
4763 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5c517a62019-12-05 11:31:45 -05004764 if (LangOpts.OpenMP >= 50)
4765 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev14a388f2019-10-25 10:27:13 -04004766 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004767 case OMPD_distribute:
4768 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4769 EndLoc, VarsWithInheritedDSA);
4770 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004771 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004772 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4773 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004774 AllowedNameModifiers.push_back(OMPD_target_update);
4775 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004776 case OMPD_distribute_parallel_for:
4777 Res = ActOnOpenMPDistributeParallelForDirective(
4778 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4779 AllowedNameModifiers.push_back(OMPD_parallel);
4780 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004781 case OMPD_distribute_parallel_for_simd:
4782 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4783 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4784 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev52812f22019-12-05 13:22:15 -05004785 if (LangOpts.OpenMP >= 50)
4786 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4a39add2016-07-05 05:00:15 +00004787 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004788 case OMPD_distribute_simd:
4789 Res = ActOnOpenMPDistributeSimdDirective(
4790 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev779a1802019-12-06 12:21:31 -05004791 if (LangOpts.OpenMP >= 50)
4792 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li787f3fc2016-07-06 04:45:38 +00004793 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004794 case OMPD_target_parallel_for_simd:
4795 Res = ActOnOpenMPTargetParallelForSimdDirective(
4796 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4797 AllowedNameModifiers.push_back(OMPD_target);
4798 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevda17a532019-12-10 11:37:03 -05004799 if (LangOpts.OpenMP >= 50)
4800 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lia579b912016-07-14 02:54:56 +00004801 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004802 case OMPD_target_simd:
4803 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4804 EndLoc, VarsWithInheritedDSA);
4805 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataevef94cd12019-12-10 12:44:45 -05004806 if (LangOpts.OpenMP >= 50)
4807 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li986330c2016-07-20 22:57:10 +00004808 break;
Kelvin Li02532872016-08-05 14:37:37 +00004809 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004810 Res = ActOnOpenMPTeamsDistributeDirective(
4811 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004812 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004813 case OMPD_teams_distribute_simd:
4814 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4815 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev7b774b72019-12-11 11:20:47 -05004816 if (LangOpts.OpenMP >= 50)
4817 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4e325f72016-10-25 12:50:55 +00004818 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004819 case OMPD_teams_distribute_parallel_for_simd:
4820 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4821 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4822 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev0b978942019-12-11 15:26:38 -05004823 if (LangOpts.OpenMP >= 50)
4824 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li579e41c2016-11-30 23:51:03 +00004825 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004826 case OMPD_teams_distribute_parallel_for:
4827 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4828 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4829 AllowedNameModifiers.push_back(OMPD_parallel);
4830 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004831 case OMPD_target_teams:
4832 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4833 EndLoc);
4834 AllowedNameModifiers.push_back(OMPD_target);
4835 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004836 case OMPD_target_teams_distribute:
4837 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4838 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4839 AllowedNameModifiers.push_back(OMPD_target);
4840 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004841 case OMPD_target_teams_distribute_parallel_for:
4842 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4843 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4844 AllowedNameModifiers.push_back(OMPD_target);
4845 AllowedNameModifiers.push_back(OMPD_parallel);
4846 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004847 case OMPD_target_teams_distribute_parallel_for_simd:
4848 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4849 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4850 AllowedNameModifiers.push_back(OMPD_target);
4851 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevfd0c91b2019-12-16 10:27:39 -05004852 if (LangOpts.OpenMP >= 50)
4853 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li1851df52017-01-03 05:23:48 +00004854 break;
Kelvin Lida681182017-01-10 18:08:18 +00004855 case OMPD_target_teams_distribute_simd:
4856 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4857 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4858 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev411e81a2019-12-16 11:16:46 -05004859 if (LangOpts.OpenMP >= 50)
4860 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lida681182017-01-10 18:08:18 +00004861 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004862 case OMPD_declare_target:
4863 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004864 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004865 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004866 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004867 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004868 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004869 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004870 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004871 llvm_unreachable("OpenMP Directive is not allowed");
4872 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004873 llvm_unreachable("Unknown OpenMP directive");
4874 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004875
Roman Lebedevb5700602019-03-20 16:32:36 +00004876 ErrorFound = Res.isInvalid() || ErrorFound;
4877
Alexey Bataev412254a2019-05-09 18:44:53 +00004878 // Check variables in the clauses if default(none) was specified.
4879 if (DSAStack->getDefaultDSA() == DSA_none) {
4880 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4881 for (OMPClause *C : Clauses) {
4882 switch (C->getClauseKind()) {
4883 case OMPC_num_threads:
4884 case OMPC_dist_schedule:
4885 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004886 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004887 break;
4888 continue;
4889 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004890 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004891 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4892 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004893 if (isOpenMPParallelDirective(Kind) &&
4894 isOpenMPTaskLoopDirective(Kind) &&
4895 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4896 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004897 continue;
4898 case OMPC_schedule:
4899 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004900 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004901 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004902 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004903 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004904 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004905 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004906 break;
4907 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004908 case OMPC_ordered:
4909 case OMPC_device:
4910 case OMPC_num_teams:
4911 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004912 case OMPC_hint:
4913 case OMPC_collapse:
4914 case OMPC_safelen:
4915 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004916 case OMPC_default:
4917 case OMPC_proc_bind:
4918 case OMPC_private:
4919 case OMPC_firstprivate:
4920 case OMPC_lastprivate:
4921 case OMPC_shared:
4922 case OMPC_reduction:
4923 case OMPC_task_reduction:
4924 case OMPC_in_reduction:
4925 case OMPC_linear:
4926 case OMPC_aligned:
4927 case OMPC_copyin:
4928 case OMPC_copyprivate:
4929 case OMPC_nowait:
4930 case OMPC_untied:
4931 case OMPC_mergeable:
4932 case OMPC_allocate:
4933 case OMPC_read:
4934 case OMPC_write:
4935 case OMPC_update:
4936 case OMPC_capture:
4937 case OMPC_seq_cst:
4938 case OMPC_depend:
4939 case OMPC_threads:
4940 case OMPC_simd:
4941 case OMPC_map:
4942 case OMPC_nogroup:
4943 case OMPC_defaultmap:
4944 case OMPC_to:
4945 case OMPC_from:
4946 case OMPC_use_device_ptr:
4947 case OMPC_is_device_ptr:
Alexey Bataevb6e70842019-12-16 15:54:17 -05004948 case OMPC_nontemporal:
Alexey Bataev412254a2019-05-09 18:44:53 +00004949 continue;
4950 case OMPC_allocator:
4951 case OMPC_flush:
4952 case OMPC_threadprivate:
4953 case OMPC_uniform:
4954 case OMPC_unknown:
4955 case OMPC_unified_address:
4956 case OMPC_unified_shared_memory:
4957 case OMPC_reverse_offload:
4958 case OMPC_dynamic_allocators:
4959 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004960 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004961 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004962 llvm_unreachable("Unexpected clause");
4963 }
4964 for (Stmt *CC : C->children()) {
4965 if (CC)
4966 DSAChecker.Visit(CC);
4967 }
4968 }
4969 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4970 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4971 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004972 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004973 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4974 continue;
4975 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05004976 if (DSAStack->getDefaultDSA() == DSA_none) {
4977 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4978 << P.first << P.second->getSourceRange();
4979 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4980 } else if (getLangOpts().OpenMP >= 50) {
4981 Diag(P.second->getExprLoc(),
4982 diag::err_omp_defaultmap_no_attr_for_variable)
4983 << P.first << P.second->getSourceRange();
4984 Diag(DSAStack->getDefaultDSALocation(),
4985 diag::note_omp_defaultmap_attr_none);
4986 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00004987 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004988
4989 if (!AllowedNameModifiers.empty())
4990 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4991 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004992
Alexey Bataeved09d242014-05-28 05:53:51 +00004993 if (ErrorFound)
4994 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004995
4996 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4997 Res.getAs<OMPExecutableDirective>()
4998 ->getStructuredBlock()
4999 ->setIsOMPStructuredBlock(true);
5000 }
5001
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00005002 if (!CurContext->isDependentContext() &&
5003 isOpenMPTargetExecutionDirective(Kind) &&
5004 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
5005 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
5006 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
5007 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
5008 // Register target to DSA Stack.
5009 DSAStack->addTargetDirLocation(StartLoc);
5010 }
5011
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005012 return Res;
5013}
5014
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005015Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
5016 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00005017 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00005018 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
5019 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005020 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00005021 assert(Linears.size() == LinModifiers.size());
5022 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00005023 if (!DG || DG.get().isNull())
5024 return DeclGroupPtrTy();
5025
Alexey Bataevd158cf62019-09-13 20:18:17 +00005026 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005027 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005028 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5029 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005030 return DG;
5031 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005032 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00005033 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5034 ADecl = FTD->getTemplatedDecl();
5035
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005036 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5037 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005038 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005039 return DeclGroupPtrTy();
5040 }
5041
Alexey Bataev2af33e32016-04-07 12:45:37 +00005042 // OpenMP [2.8.2, declare simd construct, Description]
5043 // The parameter of the simdlen clause must be a constant positive integer
5044 // expression.
5045 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005046 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00005047 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005048 // OpenMP [2.8.2, declare simd construct, Description]
5049 // The special this pointer can be used as if was one of the arguments to the
5050 // function in any of the linear, aligned, or uniform clauses.
5051 // The uniform clause declares one or more arguments to have an invariant
5052 // value for all concurrent invocations of the function in the execution of a
5053 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00005054 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5055 const Expr *UniformedLinearThis = nullptr;
5056 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005057 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005058 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5059 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005060 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5061 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00005062 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00005063 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005064 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005065 }
5066 if (isa<CXXThisExpr>(E)) {
5067 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005068 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005069 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005070 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5071 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00005072 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00005073 // OpenMP [2.8.2, declare simd construct, Description]
5074 // The aligned clause declares that the object to which each list item points
5075 // is aligned to the number of bytes expressed in the optional parameter of
5076 // the aligned clause.
5077 // The special this pointer can be used as if was one of the arguments to the
5078 // function in any of the linear, aligned, or uniform clauses.
5079 // The type of list items appearing in the aligned clause must be array,
5080 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00005081 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5082 const Expr *AlignedThis = nullptr;
5083 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005084 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005085 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5086 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5087 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005088 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5089 FD->getParamDecl(PVD->getFunctionScopeIndex())
5090 ->getCanonicalDecl() == CanonPVD) {
5091 // OpenMP [2.8.1, simd construct, Restrictions]
5092 // A list-item cannot appear in more than one aligned clause.
5093 if (AlignedArgs.count(CanonPVD) > 0) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005094 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5095 << 1 << getOpenMPClauseName(OMPC_aligned)
5096 << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005097 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5098 diag::note_omp_explicit_dsa)
5099 << getOpenMPClauseName(OMPC_aligned);
5100 continue;
5101 }
5102 AlignedArgs[CanonPVD] = E;
5103 QualType QTy = PVD->getType()
5104 .getNonReferenceType()
5105 .getUnqualifiedType()
5106 .getCanonicalType();
5107 const Type *Ty = QTy.getTypePtrOrNull();
5108 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5109 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5110 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5111 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5112 }
5113 continue;
5114 }
5115 }
5116 if (isa<CXXThisExpr>(E)) {
5117 if (AlignedThis) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005118 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5119 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005120 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5121 << getOpenMPClauseName(OMPC_aligned);
5122 }
5123 AlignedThis = E;
5124 continue;
5125 }
5126 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5127 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5128 }
5129 // The optional parameter of the aligned clause, alignment, must be a constant
5130 // positive integer expression. If no optional parameter is specified,
5131 // implementation-defined default alignments for SIMD instructions on the
5132 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005133 SmallVector<const Expr *, 4> NewAligns;
5134 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005135 ExprResult Align;
5136 if (E)
5137 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5138 NewAligns.push_back(Align.get());
5139 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005140 // OpenMP [2.8.2, declare simd construct, Description]
5141 // The linear clause declares one or more list items to be private to a SIMD
5142 // lane and to have a linear relationship with respect to the iteration space
5143 // of a loop.
5144 // The special this pointer can be used as if was one of the arguments to the
5145 // function in any of the linear, aligned, or uniform clauses.
5146 // When a linear-step expression is specified in a linear clause it must be
5147 // either a constant integer expression or an integer-typed parameter that is
5148 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005149 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005150 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5151 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005152 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005153 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5154 ++MI;
5155 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005156 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5157 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5158 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005159 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5160 FD->getParamDecl(PVD->getFunctionScopeIndex())
5161 ->getCanonicalDecl() == CanonPVD) {
5162 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5163 // A list-item cannot appear in more than one linear clause.
5164 if (LinearArgs.count(CanonPVD) > 0) {
5165 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5166 << getOpenMPClauseName(OMPC_linear)
5167 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5168 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5169 diag::note_omp_explicit_dsa)
5170 << getOpenMPClauseName(OMPC_linear);
5171 continue;
5172 }
5173 // Each argument can appear in at most one uniform or linear clause.
5174 if (UniformedArgs.count(CanonPVD) > 0) {
5175 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5176 << getOpenMPClauseName(OMPC_linear)
5177 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5178 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5179 diag::note_omp_explicit_dsa)
5180 << getOpenMPClauseName(OMPC_uniform);
5181 continue;
5182 }
5183 LinearArgs[CanonPVD] = E;
5184 if (E->isValueDependent() || E->isTypeDependent() ||
5185 E->isInstantiationDependent() ||
5186 E->containsUnexpandedParameterPack())
5187 continue;
5188 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5189 PVD->getOriginalType());
5190 continue;
5191 }
5192 }
5193 if (isa<CXXThisExpr>(E)) {
5194 if (UniformedLinearThis) {
5195 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5196 << getOpenMPClauseName(OMPC_linear)
5197 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5198 << E->getSourceRange();
5199 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5200 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5201 : OMPC_linear);
5202 continue;
5203 }
5204 UniformedLinearThis = E;
5205 if (E->isValueDependent() || E->isTypeDependent() ||
5206 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5207 continue;
5208 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5209 E->getType());
5210 continue;
5211 }
5212 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5213 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5214 }
5215 Expr *Step = nullptr;
5216 Expr *NewStep = nullptr;
5217 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005218 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005219 // Skip the same step expression, it was checked already.
5220 if (Step == E || !E) {
5221 NewSteps.push_back(E ? NewStep : nullptr);
5222 continue;
5223 }
5224 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005225 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5226 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5227 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005228 if (UniformedArgs.count(CanonPVD) == 0) {
5229 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5230 << Step->getSourceRange();
5231 } else if (E->isValueDependent() || E->isTypeDependent() ||
5232 E->isInstantiationDependent() ||
5233 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005234 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005235 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005236 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005237 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5238 << Step->getSourceRange();
5239 }
5240 continue;
5241 }
5242 NewStep = Step;
5243 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5244 !Step->isInstantiationDependent() &&
5245 !Step->containsUnexpandedParameterPack()) {
5246 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5247 .get();
5248 if (NewStep)
5249 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5250 }
5251 NewSteps.push_back(NewStep);
5252 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005253 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5254 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005255 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005256 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5257 const_cast<Expr **>(Linears.data()), Linears.size(),
5258 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5259 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005260 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005261 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005262}
5263
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005264static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5265 QualType NewType) {
5266 assert(NewType->isFunctionProtoType() &&
5267 "Expected function type with prototype.");
5268 assert(FD->getType()->isFunctionNoProtoType() &&
5269 "Expected function with type with no prototype.");
5270 assert(FDWithProto->getType()->isFunctionProtoType() &&
5271 "Expected function with prototype.");
5272 // Synthesize parameters with the same types.
5273 FD->setType(NewType);
5274 SmallVector<ParmVarDecl *, 16> Params;
5275 for (const ParmVarDecl *P : FDWithProto->parameters()) {
5276 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5277 SourceLocation(), nullptr, P->getType(),
5278 /*TInfo=*/nullptr, SC_None, nullptr);
5279 Param->setScopeInfo(0, Params.size());
5280 Param->setImplicit();
5281 Params.push_back(Param);
5282 }
5283
5284 FD->setParams(Params);
5285}
5286
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005287Optional<std::pair<FunctionDecl *, Expr *>>
5288Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5289 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005290 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005291 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005292
5293 const int VariantId = 1;
5294 // Must be applied only to single decl.
5295 if (!DG.get().isSingleDecl()) {
5296 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5297 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005298 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005299 }
5300 Decl *ADecl = DG.get().getSingleDecl();
5301 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5302 ADecl = FTD->getTemplatedDecl();
5303
5304 // Decl must be a function.
5305 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5306 if (!FD) {
5307 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5308 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005309 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005310 }
5311
5312 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5313 return FD->hasAttrs() &&
5314 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5315 FD->hasAttr<TargetAttr>());
5316 };
5317 // OpenMP is not compatible with CPU-specific attributes.
5318 if (HasMultiVersionAttributes(FD)) {
5319 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5320 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005321 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005322 }
5323
5324 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005325 if (FD->isUsed(false))
5326 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005327 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005328
5329 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005330 const FunctionDecl *Definition;
5331 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5332 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005333 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5334 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005335
5336 // The VariantRef must point to function.
5337 if (!VariantRef) {
5338 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005339 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005340 }
5341
5342 // Do not check templates, wait until instantiation.
5343 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5344 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005345 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5346 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005347
5348 // Convert VariantRef expression to the type of the original function to
5349 // resolve possible conflicts.
5350 ExprResult VariantRefCast;
5351 if (LangOpts.CPlusPlus) {
5352 QualType FnPtrType;
5353 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5354 if (Method && !Method->isStatic()) {
5355 const Type *ClassType =
5356 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5357 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5358 ExprResult ER;
5359 {
5360 // Build adrr_of unary op to correctly handle type checks for member
5361 // functions.
5362 Sema::TentativeAnalysisScope Trap(*this);
5363 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5364 VariantRef);
5365 }
5366 if (!ER.isUsable()) {
5367 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5368 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005369 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005370 }
5371 VariantRef = ER.get();
5372 } else {
5373 FnPtrType = Context.getPointerType(FD->getType());
5374 }
5375 ImplicitConversionSequence ICS =
5376 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5377 /*SuppressUserConversions=*/false,
5378 /*AllowExplicit=*/false,
5379 /*InOverloadResolution=*/false,
5380 /*CStyle=*/false,
5381 /*AllowObjCWritebackConversion=*/false);
5382 if (ICS.isFailure()) {
5383 Diag(VariantRef->getExprLoc(),
5384 diag::err_omp_declare_variant_incompat_types)
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005385 << VariantRef->getType()
5386 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
5387 << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005388 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005389 }
5390 VariantRefCast = PerformImplicitConversion(
5391 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5392 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005393 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005394 // Drop previously built artificial addr_of unary op for member functions.
5395 if (Method && !Method->isStatic()) {
5396 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5397 if (auto *UO = dyn_cast<UnaryOperator>(
5398 PossibleAddrOfVariantRef->IgnoreImplicit()))
5399 VariantRefCast = UO->getSubExpr();
5400 }
5401 } else {
5402 VariantRefCast = VariantRef;
5403 }
5404
5405 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5406 if (!ER.isUsable() ||
5407 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5408 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5409 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005410 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005411 }
5412
5413 // The VariantRef must point to function.
5414 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5415 if (!DRE) {
5416 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5417 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005418 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005419 }
5420 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5421 if (!NewFD) {
5422 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5423 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005424 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005425 }
5426
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005427 // Check if function types are compatible in C.
5428 if (!LangOpts.CPlusPlus) {
5429 QualType NewType =
5430 Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
5431 if (NewType.isNull()) {
5432 Diag(VariantRef->getExprLoc(),
5433 diag::err_omp_declare_variant_incompat_types)
5434 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
5435 return None;
5436 }
5437 if (NewType->isFunctionProtoType()) {
5438 if (FD->getType()->isFunctionNoProtoType())
5439 setPrototype(*this, FD, NewFD, NewType);
5440 else if (NewFD->getType()->isFunctionNoProtoType())
5441 setPrototype(*this, NewFD, FD, NewType);
5442 }
5443 }
5444
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005445 // Check if variant function is not marked with declare variant directive.
5446 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5447 Diag(VariantRef->getExprLoc(),
5448 diag::warn_omp_declare_variant_marked_as_declare_variant)
5449 << VariantRef->getSourceRange();
5450 SourceRange SR =
5451 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5452 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005453 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005454 }
5455
Alexey Bataevd158cf62019-09-13 20:18:17 +00005456 enum DoesntSupport {
5457 VirtFuncs = 1,
5458 Constructors = 3,
5459 Destructors = 4,
5460 DeletedFuncs = 5,
5461 DefaultedFuncs = 6,
5462 ConstexprFuncs = 7,
5463 ConstevalFuncs = 8,
5464 };
5465 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5466 if (CXXFD->isVirtual()) {
5467 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5468 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005469 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005470 }
5471
5472 if (isa<CXXConstructorDecl>(FD)) {
5473 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5474 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005475 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005476 }
5477
5478 if (isa<CXXDestructorDecl>(FD)) {
5479 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5480 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005481 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005482 }
5483 }
5484
5485 if (FD->isDeleted()) {
5486 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5487 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005488 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005489 }
5490
5491 if (FD->isDefaulted()) {
5492 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5493 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005494 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005495 }
5496
5497 if (FD->isConstexpr()) {
5498 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5499 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005500 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005501 }
5502
5503 // Check general compatibility.
5504 if (areMultiversionVariantFunctionsCompatible(
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005505 FD, NewFD, PartialDiagnostic::NullDiagnostic(),
5506 PartialDiagnosticAt(SourceLocation(),
5507 PartialDiagnostic::NullDiagnostic()),
Alexey Bataevd158cf62019-09-13 20:18:17 +00005508 PartialDiagnosticAt(
5509 VariantRef->getExprLoc(),
5510 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5511 PartialDiagnosticAt(VariantRef->getExprLoc(),
5512 PDiag(diag::err_omp_declare_variant_diff)
5513 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005514 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5515 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005516 return None;
5517 return std::make_pair(FD, cast<Expr>(DRE));
5518}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005519
Alexey Bataev9ff34742019-09-25 19:43:37 +00005520void Sema::ActOnOpenMPDeclareVariantDirective(
5521 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005522 ArrayRef<OMPCtxSelectorData> Data) {
5523 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005524 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005525 SmallVector<Expr *, 4> CtxScores;
5526 SmallVector<unsigned, 4> CtxSets;
5527 SmallVector<unsigned, 4> Ctxs;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005528 SmallVector<StringRef, 4> ImplVendors, DeviceKinds;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005529 bool IsError = false;
5530 for (const OMPCtxSelectorData &D : Data) {
5531 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5532 OpenMPContextSelectorKind Ctx = D.Ctx;
5533 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5534 return;
5535 Expr *Score = nullptr;
5536 if (D.Score.isUsable()) {
5537 Score = D.Score.get();
5538 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5539 !Score->isInstantiationDependent() &&
5540 !Score->containsUnexpandedParameterPack()) {
5541 Score =
5542 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5543 .get();
5544 if (Score)
5545 Score = VerifyIntegerConstantExpression(Score).get();
5546 }
5547 } else {
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005548 // OpenMP 5.0, 2.3.3 Matching and Scoring Context Selectors.
5549 // The kind, arch, and isa selectors are given the values 2^l, 2^(l+1) and
5550 // 2^(l+2), respectively, where l is the number of traits in the construct
5551 // set.
5552 // TODO: implement correct logic for isa and arch traits.
5553 // TODO: take the construct context set into account when it is
5554 // implemented.
5555 int L = 0; // Currently set the number of traits in construct set to 0,
5556 // since the construct trait set in not supported yet.
5557 if (CtxSet == OMP_CTX_SET_device && Ctx == OMP_CTX_kind)
5558 Score = ActOnIntegerConstant(SourceLocation(), std::pow(2, L)).get();
5559 else
5560 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005561 }
Alexey Bataev5459a902019-11-22 11:42:08 -05005562 switch (Ctx) {
5563 case OMP_CTX_vendor:
5564 assert(CtxSet == OMP_CTX_SET_implementation &&
5565 "Expected implementation context selector set.");
5566 ImplVendors.append(D.Names.begin(), D.Names.end());
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005567 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005568 case OMP_CTX_kind:
5569 assert(CtxSet == OMP_CTX_SET_device &&
5570 "Expected device context selector set.");
5571 DeviceKinds.append(D.Names.begin(), D.Names.end());
Alexey Bataevfde11e92019-11-07 11:03:10 -05005572 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005573 case OMP_CTX_unknown:
5574 llvm_unreachable("Unknown context selector kind.");
Alexey Bataevfde11e92019-11-07 11:03:10 -05005575 }
5576 IsError = IsError || !Score;
5577 CtxSets.push_back(CtxSet);
5578 Ctxs.push_back(Ctx);
5579 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005580 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005581 if (!IsError) {
5582 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5583 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5584 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005585 ImplVendors.begin(), ImplVendors.size(), DeviceKinds.begin(),
5586 DeviceKinds.size(), SR);
Alexey Bataevfde11e92019-11-07 11:03:10 -05005587 FD->addAttr(NewAttr);
5588 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005589}
5590
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005591void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5592 FunctionDecl *Func,
5593 bool MightBeOdrUse) {
5594 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5595
5596 if (!Func->isDependentContext() && Func->hasAttrs()) {
5597 for (OMPDeclareVariantAttr *A :
5598 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5599 // TODO: add checks for active OpenMP context where possible.
5600 Expr *VariantRef = A->getVariantFuncRef();
Alexey Bataevf17a1d82019-12-02 14:15:38 -05005601 auto *DRE = cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005602 auto *F = cast<FunctionDecl>(DRE->getDecl());
5603 if (!F->isDefined() && F->isTemplateInstantiation())
5604 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5605 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5606 }
5607 }
5608}
5609
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005610StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5611 Stmt *AStmt,
5612 SourceLocation StartLoc,
5613 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005614 if (!AStmt)
5615 return StmtError();
5616
Alexey Bataeve3727102018-04-18 15:57:46 +00005617 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005618 // 1.2.2 OpenMP Language Terminology
5619 // Structured block - An executable statement with a single entry at the
5620 // top and a single exit at the bottom.
5621 // The point of exit cannot be a branch out of the structured block.
5622 // longjmp() and throw() must not violate the entry/exit criteria.
5623 CS->getCapturedDecl()->setNothrow();
5624
Reid Kleckner87a31802018-03-12 21:43:02 +00005625 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005626
Alexey Bataev25e5b442015-09-15 12:52:43 +00005627 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5628 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005629}
5630
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005631namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005632/// Iteration space of a single for loop.
5633struct LoopIterationSpace final {
5634 /// True if the condition operator is the strict compare operator (<, > or
5635 /// !=).
5636 bool IsStrictCompare = false;
5637 /// Condition of the loop.
5638 Expr *PreCond = nullptr;
5639 /// This expression calculates the number of iterations in the loop.
5640 /// It is always possible to calculate it before starting the loop.
5641 Expr *NumIterations = nullptr;
5642 /// The loop counter variable.
5643 Expr *CounterVar = nullptr;
5644 /// Private loop counter variable.
5645 Expr *PrivateCounterVar = nullptr;
5646 /// This is initializer for the initial value of #CounterVar.
5647 Expr *CounterInit = nullptr;
5648 /// This is step for the #CounterVar used to generate its update:
5649 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5650 Expr *CounterStep = nullptr;
5651 /// Should step be subtracted?
5652 bool Subtract = false;
5653 /// Source range of the loop init.
5654 SourceRange InitSrcRange;
5655 /// Source range of the loop condition.
5656 SourceRange CondSrcRange;
5657 /// Source range of the loop increment.
5658 SourceRange IncSrcRange;
5659 /// Minimum value that can have the loop control variable. Used to support
5660 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5661 /// since only such variables can be used in non-loop invariant expressions.
5662 Expr *MinValue = nullptr;
5663 /// Maximum value that can have the loop control variable. Used to support
5664 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5665 /// since only such variables can be used in non-loop invariant expressions.
5666 Expr *MaxValue = nullptr;
5667 /// true, if the lower bound depends on the outer loop control var.
5668 bool IsNonRectangularLB = false;
5669 /// true, if the upper bound depends on the outer loop control var.
5670 bool IsNonRectangularUB = false;
5671 /// Index of the loop this loop depends on and forms non-rectangular loop
5672 /// nest.
5673 unsigned LoopDependentIdx = 0;
5674 /// Final condition for the non-rectangular loop nest support. It is used to
5675 /// check that the number of iterations for this particular counter must be
5676 /// finished.
5677 Expr *FinalCondition = nullptr;
5678};
5679
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005680/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005681/// extracting iteration space of each loop in the loop nest, that will be used
5682/// for IR generation.
5683class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005684 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005685 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005686 /// Data-sharing stack.
5687 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005688 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005689 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005690 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005691 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005692 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005693 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005694 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005695 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005696 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005697 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005698 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005699 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005700 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005701 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005702 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005703 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005704 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005705 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005706 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005707 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005708 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005709 /// Var < UB
5710 /// Var <= UB
5711 /// UB > Var
5712 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005713 /// This will have no value when the condition is !=
5714 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005715 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005716 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005717 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005718 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005719 /// The outer loop counter this loop depends on (if any).
5720 const ValueDecl *DepDecl = nullptr;
5721 /// Contains number of loop (starts from 1) on which loop counter init
5722 /// expression of this loop depends on.
5723 Optional<unsigned> InitDependOnLC;
5724 /// Contains number of loop (starts from 1) on which loop counter condition
5725 /// expression of this loop depends on.
5726 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005727 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005728 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005729 /// Original condition required for checking of the exit condition for
5730 /// non-rectangular loop.
5731 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005732
5733public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005734 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5735 SourceLocation DefaultLoc)
5736 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5737 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005738 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005739 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005740 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005741 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005742 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005743 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005744 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005745 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005746 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005747 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005748 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005749 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005750 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005751 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005752 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005753 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005754 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005755 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005756 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005757 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005758 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005759 /// True, if the compare operator is strict (<, > or !=).
5760 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005761 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005762 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005763 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005764 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005765 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005766 Expr *
5767 buildPreCond(Scope *S, Expr *Cond,
5768 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005769 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005770 DeclRefExpr *
5771 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5772 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005773 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005774 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005775 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005776 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005777 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005778 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005779 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005780 /// Build loop data with counter value for depend clauses in ordered
5781 /// directives.
5782 Expr *
5783 buildOrderedLoopData(Scope *S, Expr *Counter,
5784 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5785 SourceLocation Loc, Expr *Inc = nullptr,
5786 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005787 /// Builds the minimum value for the loop counter.
5788 std::pair<Expr *, Expr *> buildMinMaxValues(
5789 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5790 /// Builds final condition for the non-rectangular loops.
5791 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005792 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005793 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005794 /// Returns true if the initializer forms non-rectangular loop.
5795 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5796 /// Returns true if the condition forms non-rectangular loop.
5797 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5798 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5799 unsigned getLoopDependentIdx() const {
5800 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5801 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005802
5803private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005804 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005805 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005806 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005807 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005808 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5809 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005810 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005811 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5812 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005813 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005814 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005815};
5816
Alexey Bataeve3727102018-04-18 15:57:46 +00005817bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005818 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005819 assert(!LB && !UB && !Step);
5820 return false;
5821 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005822 return LCDecl->getType()->isDependentType() ||
5823 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5824 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005825}
5826
Alexey Bataeve3727102018-04-18 15:57:46 +00005827bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005828 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005829 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005830 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005831 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005832 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005833 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005834 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005835 LCDecl = getCanonicalDecl(NewLCDecl);
5836 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005837 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5838 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005839 if ((Ctor->isCopyOrMoveConstructor() ||
5840 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5841 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005842 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005843 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005844 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005845 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005846 return false;
5847}
5848
Alexey Bataev316ccf62019-01-29 18:51:58 +00005849bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5850 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005851 bool StrictOp, SourceRange SR,
5852 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005853 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005854 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5855 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005856 if (!NewUB)
5857 return true;
5858 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005859 if (LessOp)
5860 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005861 TestIsStrictOp = StrictOp;
5862 ConditionSrcRange = SR;
5863 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005864 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005865 return false;
5866}
5867
Alexey Bataeve3727102018-04-18 15:57:46 +00005868bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005869 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005870 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005871 if (!NewStep)
5872 return true;
5873 if (!NewStep->isValueDependent()) {
5874 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005875 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005876 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5877 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005878 if (Val.isInvalid())
5879 return true;
5880 NewStep = Val.get();
5881
5882 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5883 // If test-expr is of form var relational-op b and relational-op is < or
5884 // <= then incr-expr must cause var to increase on each iteration of the
5885 // loop. If test-expr is of form var relational-op b and relational-op is
5886 // > or >= then incr-expr must cause var to decrease on each iteration of
5887 // the loop.
5888 // If test-expr is of form b relational-op var and relational-op is < or
5889 // <= then incr-expr must cause var to decrease on each iteration of the
5890 // loop. If test-expr is of form b relational-op var and relational-op is
5891 // > or >= then incr-expr must cause var to increase on each iteration of
5892 // the loop.
5893 llvm::APSInt Result;
5894 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5895 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5896 bool IsConstNeg =
5897 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005898 bool IsConstPos =
5899 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005900 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005901
5902 // != with increment is treated as <; != with decrement is treated as >
5903 if (!TestIsLessOp.hasValue())
5904 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005905 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005906 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005907 (IsConstNeg || (IsUnsigned && Subtract)) :
5908 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005909 SemaRef.Diag(NewStep->getExprLoc(),
5910 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005911 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005912 SemaRef.Diag(ConditionLoc,
5913 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005914 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005915 return true;
5916 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005917 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005918 NewStep =
5919 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5920 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005921 Subtract = !Subtract;
5922 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005923 }
5924
5925 Step = NewStep;
5926 SubtractStep = Subtract;
5927 return false;
5928}
5929
Alexey Bataev622af1d2019-04-24 19:58:30 +00005930namespace {
5931/// Checker for the non-rectangular loops. Checks if the initializer or
5932/// condition expression references loop counter variable.
5933class LoopCounterRefChecker final
5934 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5935 Sema &SemaRef;
5936 DSAStackTy &Stack;
5937 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005938 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005939 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005940 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005941 unsigned BaseLoopId = 0;
5942 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5943 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5944 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5945 << (IsInitializer ? 0 : 1);
5946 return false;
5947 }
5948 const auto &&Data = Stack.isLoopControlVariable(VD);
5949 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5950 // The type of the loop iterator on which we depend may not have a random
5951 // access iterator type.
5952 if (Data.first && VD->getType()->isRecordType()) {
5953 SmallString<128> Name;
5954 llvm::raw_svector_ostream OS(Name);
5955 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5956 /*Qualified=*/true);
5957 SemaRef.Diag(E->getExprLoc(),
5958 diag::err_omp_wrong_dependency_iterator_type)
5959 << OS.str();
5960 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5961 return false;
5962 }
5963 if (Data.first &&
5964 (DepDecl || (PrevDepDecl &&
5965 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5966 if (!DepDecl && PrevDepDecl)
5967 DepDecl = PrevDepDecl;
5968 SmallString<128> Name;
5969 llvm::raw_svector_ostream OS(Name);
5970 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5971 /*Qualified=*/true);
5972 SemaRef.Diag(E->getExprLoc(),
5973 diag::err_omp_invariant_or_linear_dependency)
5974 << OS.str();
5975 return false;
5976 }
5977 if (Data.first) {
5978 DepDecl = VD;
5979 BaseLoopId = Data.first;
5980 }
5981 return Data.first;
5982 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005983
5984public:
5985 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5986 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005987 if (isa<VarDecl>(VD))
5988 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005989 return false;
5990 }
5991 bool VisitMemberExpr(const MemberExpr *E) {
5992 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5993 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005994 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5995 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005996 }
5997 return false;
5998 }
5999 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006000 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006001 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00006002 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006003 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006004 }
6005 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006006 const ValueDecl *CurLCDecl, bool IsInitializer,
6007 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00006008 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006009 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
6010 unsigned getBaseLoopId() const {
6011 assert(CurLCDecl && "Expected loop dependency.");
6012 return BaseLoopId;
6013 }
6014 const ValueDecl *getDepDecl() const {
6015 assert(CurLCDecl && "Expected loop dependency.");
6016 return DepDecl;
6017 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00006018};
6019} // namespace
6020
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006021Optional<unsigned>
6022OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6023 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00006024 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006025 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6026 DepDecl);
6027 if (LoopStmtChecker.Visit(S)) {
6028 DepDecl = LoopStmtChecker.getDepDecl();
6029 return LoopStmtChecker.getBaseLoopId();
6030 }
6031 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006032}
6033
Alexey Bataeve3727102018-04-18 15:57:46 +00006034bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006035 // Check init-expr for canonical loop form and save loop counter
6036 // variable - #Var and its initialization value - #LB.
6037 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6038 // var = lb
6039 // integer-type var = lb
6040 // random-access-iterator-type var = lb
6041 // pointer-type var = lb
6042 //
6043 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00006044 if (EmitDiags) {
6045 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6046 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006047 return true;
6048 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006049 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6050 if (!ExprTemp->cleanupsHaveSideEffects())
6051 S = ExprTemp->getSubExpr();
6052
Alexander Musmana5f070a2014-10-01 06:03:56 +00006053 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006054 if (Expr *E = dyn_cast<Expr>(S))
6055 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006056 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006057 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006058 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006059 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6060 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6061 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006062 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6063 EmitDiags);
6064 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006065 }
6066 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6067 if (ME->isArrow() &&
6068 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006069 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6070 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006071 }
6072 }
David Majnemer9d168222016-08-05 17:44:54 +00006073 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006074 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00006075 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00006076 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006077 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00006078 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006079 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006080 diag::ext_omp_loop_not_canonical_init)
6081 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00006082 return setLCDeclAndLB(
6083 Var,
6084 buildDeclRefExpr(SemaRef, Var,
6085 Var->getType().getNonReferenceType(),
6086 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00006087 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006088 }
6089 }
6090 }
David Majnemer9d168222016-08-05 17:44:54 +00006091 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006092 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006093 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00006094 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006095 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6096 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006097 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6098 EmitDiags);
6099 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006100 }
6101 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6102 if (ME->isArrow() &&
6103 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006104 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6105 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006106 }
6107 }
6108 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006109
Alexey Bataeve3727102018-04-18 15:57:46 +00006110 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006111 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00006112 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006113 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00006114 << S->getSourceRange();
6115 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006116 return true;
6117}
6118
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006119/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006120/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00006121static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006122 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00006123 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006124 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00006125 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006126 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00006127 if ((Ctor->isCopyOrMoveConstructor() ||
6128 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6129 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006130 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00006131 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6132 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006133 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006134 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006135 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006136 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6137 return getCanonicalDecl(ME->getMemberDecl());
6138 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006139}
6140
Alexey Bataeve3727102018-04-18 15:57:46 +00006141bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006142 // Check test-expr for canonical form, save upper-bound UB, flags for
6143 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00006144 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006145 // var relational-op b
6146 // b relational-op var
6147 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006148 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006149 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006150 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6151 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006152 return true;
6153 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006154 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006155 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006156 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006157 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006158 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006159 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6160 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006161 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6162 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6163 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006164 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6165 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006166 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6167 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6168 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006169 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6170 return setUB(
6171 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6172 /*LessOp=*/llvm::None,
6173 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006174 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006175 if (CE->getNumArgs() == 2) {
6176 auto Op = CE->getOperator();
6177 switch (Op) {
6178 case OO_Greater:
6179 case OO_GreaterEqual:
6180 case OO_Less:
6181 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006182 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6183 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006184 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6185 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006186 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6187 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006188 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6189 CE->getOperatorLoc());
6190 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006191 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006192 if (IneqCondIsCanonical)
6193 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6194 : CE->getArg(0),
6195 /*LessOp=*/llvm::None,
6196 /*StrictOp=*/true, CE->getSourceRange(),
6197 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006198 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006199 default:
6200 break;
6201 }
6202 }
6203 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006204 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006205 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006206 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006207 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006208 return true;
6209}
6210
Alexey Bataeve3727102018-04-18 15:57:46 +00006211bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006212 // RHS of canonical loop form increment can be:
6213 // var + incr
6214 // incr + var
6215 // var - incr
6216 //
6217 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006218 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006219 if (BO->isAdditiveOp()) {
6220 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006221 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6222 return setStep(BO->getRHS(), !IsAdd);
6223 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6224 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006225 }
David Majnemer9d168222016-08-05 17:44:54 +00006226 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006227 bool IsAdd = CE->getOperator() == OO_Plus;
6228 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006229 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6230 return setStep(CE->getArg(1), !IsAdd);
6231 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6232 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006233 }
6234 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006235 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006236 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006237 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006238 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006239 return true;
6240}
6241
Alexey Bataeve3727102018-04-18 15:57:46 +00006242bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006243 // Check incr-expr for canonical loop form and return true if it
6244 // does not conform.
6245 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6246 // ++var
6247 // var++
6248 // --var
6249 // var--
6250 // var += incr
6251 // var -= incr
6252 // var = var + incr
6253 // var = incr + var
6254 // var = var - incr
6255 //
6256 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006257 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006258 return true;
6259 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006260 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6261 if (!ExprTemp->cleanupsHaveSideEffects())
6262 S = ExprTemp->getSubExpr();
6263
Alexander Musmana5f070a2014-10-01 06:03:56 +00006264 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006265 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006266 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006267 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006268 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6269 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006270 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006271 (UO->isDecrementOp() ? -1 : 1))
6272 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006273 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006274 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006275 switch (BO->getOpcode()) {
6276 case BO_AddAssign:
6277 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006278 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6279 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006280 break;
6281 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006282 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6283 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006284 break;
6285 default:
6286 break;
6287 }
David Majnemer9d168222016-08-05 17:44:54 +00006288 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006289 switch (CE->getOperator()) {
6290 case OO_PlusPlus:
6291 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006292 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6293 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006294 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006295 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006296 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6297 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006298 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006299 break;
6300 case OO_PlusEqual:
6301 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006302 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6303 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006304 break;
6305 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006306 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6307 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006308 break;
6309 default:
6310 break;
6311 }
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(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006316 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006317 return true;
6318}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006319
Alexey Bataev5a3af132016-03-29 08:58:54 +00006320static ExprResult
6321tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006322 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006323 if (SemaRef.CurContext->isDependentContext())
6324 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006325 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6326 return SemaRef.PerformImplicitConversion(
6327 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6328 /*AllowExplicit=*/true);
6329 auto I = Captures.find(Capture);
6330 if (I != Captures.end())
6331 return buildCapture(SemaRef, Capture, I->second);
6332 DeclRefExpr *Ref = nullptr;
6333 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6334 Captures[Capture] = Ref;
6335 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006336}
6337
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006338/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006339Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006340 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006341 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006342 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006343 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006344 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006345 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006346 Expr *LBVal = LB;
6347 Expr *UBVal = UB;
6348 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6349 // max(LB(MinVal), LB(MaxVal))
6350 if (InitDependOnLC) {
6351 const LoopIterationSpace &IS =
6352 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6353 InitDependOnLC.getValueOr(
6354 CondDependOnLC.getValueOr(0))];
6355 if (!IS.MinValue || !IS.MaxValue)
6356 return nullptr;
6357 // OuterVar = Min
6358 ExprResult MinValue =
6359 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6360 if (!MinValue.isUsable())
6361 return nullptr;
6362
6363 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6364 IS.CounterVar, MinValue.get());
6365 if (!LBMinVal.isUsable())
6366 return nullptr;
6367 // OuterVar = Min, LBVal
6368 LBMinVal =
6369 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6370 if (!LBMinVal.isUsable())
6371 return nullptr;
6372 // (OuterVar = Min, LBVal)
6373 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6374 if (!LBMinVal.isUsable())
6375 return nullptr;
6376
6377 // OuterVar = Max
6378 ExprResult MaxValue =
6379 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6380 if (!MaxValue.isUsable())
6381 return nullptr;
6382
6383 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6384 IS.CounterVar, MaxValue.get());
6385 if (!LBMaxVal.isUsable())
6386 return nullptr;
6387 // OuterVar = Max, LBVal
6388 LBMaxVal =
6389 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6390 if (!LBMaxVal.isUsable())
6391 return nullptr;
6392 // (OuterVar = Max, LBVal)
6393 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6394 if (!LBMaxVal.isUsable())
6395 return nullptr;
6396
6397 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6398 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6399 if (!LBMin || !LBMax)
6400 return nullptr;
6401 // LB(MinVal) < LB(MaxVal)
6402 ExprResult MinLessMaxRes =
6403 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6404 if (!MinLessMaxRes.isUsable())
6405 return nullptr;
6406 Expr *MinLessMax =
6407 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6408 if (!MinLessMax)
6409 return nullptr;
6410 if (TestIsLessOp.getValue()) {
6411 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6412 // LB(MaxVal))
6413 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6414 MinLessMax, LBMin, LBMax);
6415 if (!MinLB.isUsable())
6416 return nullptr;
6417 LBVal = MinLB.get();
6418 } else {
6419 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6420 // LB(MaxVal))
6421 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6422 MinLessMax, LBMax, LBMin);
6423 if (!MaxLB.isUsable())
6424 return nullptr;
6425 LBVal = MaxLB.get();
6426 }
6427 }
6428 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6429 // min(UB(MinVal), UB(MaxVal))
6430 if (CondDependOnLC) {
6431 const LoopIterationSpace &IS =
6432 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6433 InitDependOnLC.getValueOr(
6434 CondDependOnLC.getValueOr(0))];
6435 if (!IS.MinValue || !IS.MaxValue)
6436 return nullptr;
6437 // OuterVar = Min
6438 ExprResult MinValue =
6439 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6440 if (!MinValue.isUsable())
6441 return nullptr;
6442
6443 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6444 IS.CounterVar, MinValue.get());
6445 if (!UBMinVal.isUsable())
6446 return nullptr;
6447 // OuterVar = Min, UBVal
6448 UBMinVal =
6449 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6450 if (!UBMinVal.isUsable())
6451 return nullptr;
6452 // (OuterVar = Min, UBVal)
6453 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6454 if (!UBMinVal.isUsable())
6455 return nullptr;
6456
6457 // OuterVar = Max
6458 ExprResult MaxValue =
6459 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6460 if (!MaxValue.isUsable())
6461 return nullptr;
6462
6463 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6464 IS.CounterVar, MaxValue.get());
6465 if (!UBMaxVal.isUsable())
6466 return nullptr;
6467 // OuterVar = Max, UBVal
6468 UBMaxVal =
6469 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6470 if (!UBMaxVal.isUsable())
6471 return nullptr;
6472 // (OuterVar = Max, UBVal)
6473 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6474 if (!UBMaxVal.isUsable())
6475 return nullptr;
6476
6477 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6478 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6479 if (!UBMin || !UBMax)
6480 return nullptr;
6481 // UB(MinVal) > UB(MaxVal)
6482 ExprResult MinGreaterMaxRes =
6483 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6484 if (!MinGreaterMaxRes.isUsable())
6485 return nullptr;
6486 Expr *MinGreaterMax =
6487 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6488 if (!MinGreaterMax)
6489 return nullptr;
6490 if (TestIsLessOp.getValue()) {
6491 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6492 // UB(MaxVal))
6493 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6494 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6495 if (!MaxUB.isUsable())
6496 return nullptr;
6497 UBVal = MaxUB.get();
6498 } else {
6499 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6500 // UB(MaxVal))
6501 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6502 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6503 if (!MinUB.isUsable())
6504 return nullptr;
6505 UBVal = MinUB.get();
6506 }
6507 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006508 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006509 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6510 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006511 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6512 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006513 if (!Upper || !Lower)
6514 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006515
6516 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6517
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006518 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006519 // BuildBinOp already emitted error, this one is to point user to upper
6520 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006521 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006522 << Upper->getSourceRange() << Lower->getSourceRange();
6523 return nullptr;
6524 }
6525 }
6526
6527 if (!Diff.isUsable())
6528 return nullptr;
6529
6530 // Upper - Lower [- 1]
6531 if (TestIsStrictOp)
6532 Diff = SemaRef.BuildBinOp(
6533 S, DefaultLoc, BO_Sub, Diff.get(),
6534 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6535 if (!Diff.isUsable())
6536 return nullptr;
6537
6538 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006539 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006540 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006541 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006542 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006543 if (!Diff.isUsable())
6544 return nullptr;
6545
6546 // Parentheses (for dumping/debugging purposes only).
6547 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6548 if (!Diff.isUsable())
6549 return nullptr;
6550
6551 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006552 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006553 if (!Diff.isUsable())
6554 return nullptr;
6555
Alexander Musman174b3ca2014-10-06 11:16:29 +00006556 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006557 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006558 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006559 bool UseVarType = VarType->hasIntegerRepresentation() &&
6560 C.getTypeSize(Type) > C.getTypeSize(VarType);
6561 if (!Type->isIntegerType() || UseVarType) {
6562 unsigned NewSize =
6563 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6564 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6565 : Type->hasSignedIntegerRepresentation();
6566 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006567 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6568 Diff = SemaRef.PerformImplicitConversion(
6569 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6570 if (!Diff.isUsable())
6571 return nullptr;
6572 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006573 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006574 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006575 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6576 if (NewSize != C.getTypeSize(Type)) {
6577 if (NewSize < C.getTypeSize(Type)) {
6578 assert(NewSize == 64 && "incorrect loop var size");
6579 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6580 << InitSrcRange << ConditionSrcRange;
6581 }
6582 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006583 NewSize, Type->hasSignedIntegerRepresentation() ||
6584 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006585 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6586 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6587 Sema::AA_Converting, true);
6588 if (!Diff.isUsable())
6589 return nullptr;
6590 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006591 }
6592 }
6593
Alexander Musmana5f070a2014-10-01 06:03:56 +00006594 return Diff.get();
6595}
6596
Alexey Bataevf8be4762019-08-14 19:30:06 +00006597std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6598 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6599 // Do not build for iterators, they cannot be used in non-rectangular loop
6600 // nests.
6601 if (LCDecl->getType()->isRecordType())
6602 return std::make_pair(nullptr, nullptr);
6603 // If we subtract, the min is in the condition, otherwise the min is in the
6604 // init value.
6605 Expr *MinExpr = nullptr;
6606 Expr *MaxExpr = nullptr;
6607 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6608 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6609 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6610 : CondDependOnLC.hasValue();
6611 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6612 : InitDependOnLC.hasValue();
6613 Expr *Lower =
6614 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6615 Expr *Upper =
6616 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6617 if (!Upper || !Lower)
6618 return std::make_pair(nullptr, nullptr);
6619
6620 if (TestIsLessOp.getValue())
6621 MinExpr = Lower;
6622 else
6623 MaxExpr = Upper;
6624
6625 // Build minimum/maximum value based on number of iterations.
6626 ExprResult Diff;
6627 QualType VarType = LCDecl->getType().getNonReferenceType();
6628
6629 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6630 if (!Diff.isUsable())
6631 return std::make_pair(nullptr, nullptr);
6632
6633 // Upper - Lower [- 1]
6634 if (TestIsStrictOp)
6635 Diff = SemaRef.BuildBinOp(
6636 S, DefaultLoc, BO_Sub, Diff.get(),
6637 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6638 if (!Diff.isUsable())
6639 return std::make_pair(nullptr, nullptr);
6640
6641 // Upper - Lower [- 1] + Step
6642 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6643 if (!NewStep.isUsable())
6644 return std::make_pair(nullptr, nullptr);
6645
6646 // Parentheses (for dumping/debugging purposes only).
6647 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6648 if (!Diff.isUsable())
6649 return std::make_pair(nullptr, nullptr);
6650
6651 // (Upper - Lower [- 1]) / Step
6652 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6653 if (!Diff.isUsable())
6654 return std::make_pair(nullptr, nullptr);
6655
6656 // ((Upper - Lower [- 1]) / Step) * Step
6657 // Parentheses (for dumping/debugging purposes only).
6658 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6659 if (!Diff.isUsable())
6660 return std::make_pair(nullptr, nullptr);
6661
6662 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6663 if (!Diff.isUsable())
6664 return std::make_pair(nullptr, nullptr);
6665
6666 // Convert to the original type or ptrdiff_t, if original type is pointer.
6667 if (!VarType->isAnyPointerType() &&
6668 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6669 Diff = SemaRef.PerformImplicitConversion(
6670 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6671 } else if (VarType->isAnyPointerType() &&
6672 !SemaRef.Context.hasSameType(
6673 Diff.get()->getType(),
6674 SemaRef.Context.getUnsignedPointerDiffType())) {
6675 Diff = SemaRef.PerformImplicitConversion(
6676 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6677 Sema::AA_Converting, /*AllowExplicit=*/true);
6678 }
6679 if (!Diff.isUsable())
6680 return std::make_pair(nullptr, nullptr);
6681
6682 // Parentheses (for dumping/debugging purposes only).
6683 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6684 if (!Diff.isUsable())
6685 return std::make_pair(nullptr, nullptr);
6686
6687 if (TestIsLessOp.getValue()) {
6688 // MinExpr = Lower;
6689 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6690 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6691 if (!Diff.isUsable())
6692 return std::make_pair(nullptr, nullptr);
6693 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6694 if (!Diff.isUsable())
6695 return std::make_pair(nullptr, nullptr);
6696 MaxExpr = Diff.get();
6697 } else {
6698 // MaxExpr = Upper;
6699 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6700 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6701 if (!Diff.isUsable())
6702 return std::make_pair(nullptr, nullptr);
6703 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6704 if (!Diff.isUsable())
6705 return std::make_pair(nullptr, nullptr);
6706 MinExpr = Diff.get();
6707 }
6708
6709 return std::make_pair(MinExpr, MaxExpr);
6710}
6711
6712Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6713 if (InitDependOnLC || CondDependOnLC)
6714 return Condition;
6715 return nullptr;
6716}
6717
Alexey Bataeve3727102018-04-18 15:57:46 +00006718Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006719 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006720 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006721 // Do not build a precondition when the condition/initialization is dependent
6722 // to prevent pessimistic early loop exit.
6723 // TODO: this can be improved by calculating min/max values but not sure that
6724 // it will be very effective.
6725 if (CondDependOnLC || InitDependOnLC)
6726 return SemaRef.PerformImplicitConversion(
6727 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6728 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6729 /*AllowExplicit=*/true).get();
6730
Alexey Bataev62dbb972015-04-22 11:59:37 +00006731 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006732 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006733
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006734 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6735 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006736 if (!NewLB.isUsable() || !NewUB.isUsable())
6737 return nullptr;
6738
Alexey Bataeve3727102018-04-18 15:57:46 +00006739 ExprResult CondExpr =
6740 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006741 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006742 (TestIsStrictOp ? BO_LT : BO_LE) :
6743 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006744 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006745 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006746 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6747 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006748 CondExpr = SemaRef.PerformImplicitConversion(
6749 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6750 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006751 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006752
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006753 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006754 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6755}
6756
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006757/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006758DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006759 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6760 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006761 auto *VD = dyn_cast<VarDecl>(LCDecl);
6762 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006763 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6764 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006765 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006766 const DSAStackTy::DSAVarData Data =
6767 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006768 // If the loop control decl is explicitly marked as private, do not mark it
6769 // as captured again.
6770 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6771 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006772 return Ref;
6773 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006774 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006775}
6776
Alexey Bataeve3727102018-04-18 15:57:46 +00006777Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006778 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006779 QualType Type = LCDecl->getType().getNonReferenceType();
6780 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006781 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6782 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6783 isa<VarDecl>(LCDecl)
6784 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6785 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006786 if (PrivateVar->isInvalidDecl())
6787 return nullptr;
6788 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6789 }
6790 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006791}
6792
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006793/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006794Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006795
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006796/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006797Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006798
Alexey Bataevf138fda2018-08-13 19:04:24 +00006799Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6800 Scope *S, Expr *Counter,
6801 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6802 Expr *Inc, OverloadedOperatorKind OOK) {
6803 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6804 if (!Cnt)
6805 return nullptr;
6806 if (Inc) {
6807 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6808 "Expected only + or - operations for depend clauses.");
6809 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6810 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6811 if (!Cnt)
6812 return nullptr;
6813 }
6814 ExprResult Diff;
6815 QualType VarType = LCDecl->getType().getNonReferenceType();
6816 if (VarType->isIntegerType() || VarType->isPointerType() ||
6817 SemaRef.getLangOpts().CPlusPlus) {
6818 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006819 Expr *Upper = TestIsLessOp.getValue()
6820 ? Cnt
6821 : tryBuildCapture(SemaRef, UB, Captures).get();
6822 Expr *Lower = TestIsLessOp.getValue()
6823 ? tryBuildCapture(SemaRef, LB, Captures).get()
6824 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006825 if (!Upper || !Lower)
6826 return nullptr;
6827
6828 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6829
6830 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6831 // BuildBinOp already emitted error, this one is to point user to upper
6832 // and lower bound, and to tell what is passed to 'operator-'.
6833 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6834 << Upper->getSourceRange() << Lower->getSourceRange();
6835 return nullptr;
6836 }
6837 }
6838
6839 if (!Diff.isUsable())
6840 return nullptr;
6841
6842 // Parentheses (for dumping/debugging purposes only).
6843 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6844 if (!Diff.isUsable())
6845 return nullptr;
6846
6847 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6848 if (!NewStep.isUsable())
6849 return nullptr;
6850 // (Upper - Lower) / Step
6851 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6852 if (!Diff.isUsable())
6853 return nullptr;
6854
6855 return Diff.get();
6856}
Alexey Bataev23b69422014-06-18 07:08:49 +00006857} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006858
Alexey Bataev9c821032015-04-30 04:23:23 +00006859void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6860 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6861 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006862 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6863 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006864 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006865 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006866 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006867 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6868 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006869 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006870 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006871 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006872 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006873 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006874 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006875 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6876 /*WithInit=*/false);
6877 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006878 }
6879 }
6880 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006881 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6882 if (LD != D->getCanonicalDecl()) {
6883 DSAStack->resetPossibleLoopCounter();
6884 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6885 MarkDeclarationsReferencedInExpr(
6886 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6887 Var->getType().getNonLValueExprType(Context),
6888 ForLoc, /*RefersToCapture=*/true));
6889 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006890 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6891 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6892 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6893 // associated for-loop of a simd construct with just one associated
6894 // for-loop may be listed in a linear clause with a constant-linear-step
6895 // that is the increment of the associated for-loop. The loop iteration
6896 // variable(s) in the associated for-loop(s) of a for or parallel for
6897 // construct may be listed in a private or lastprivate clause.
6898 DSAStackTy::DSAVarData DVar =
6899 DSAStack->getTopDSA(D, /*FromParent=*/false);
6900 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6901 // is declared in the loop and it is predetermined as a private.
6902 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6903 OpenMPClauseKind PredeterminedCKind =
6904 isOpenMPSimdDirective(DKind)
6905 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6906 : OMPC_private;
6907 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6908 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6909 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6910 DVar.CKind != OMPC_private))) ||
6911 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006912 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006913 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006914 isOpenMPDistributeDirective(DKind)) &&
6915 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6916 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6917 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6918 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6919 << getOpenMPClauseName(DVar.CKind)
6920 << getOpenMPDirectiveName(DKind)
6921 << getOpenMPClauseName(PredeterminedCKind);
6922 if (DVar.RefExpr == nullptr)
6923 DVar.CKind = PredeterminedCKind;
6924 reportOriginalDsa(*this, DSAStack, D, DVar,
6925 /*IsLoopIterVar=*/true);
6926 } else if (LoopDeclRefExpr) {
6927 // Make the loop iteration variable private (for worksharing
6928 // constructs), linear (for simd directives with the only one
6929 // associated loop) or lastprivate (for simd directives with several
6930 // collapsed or ordered loops).
6931 if (DVar.CKind == OMPC_unknown)
6932 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6933 PrivateRef);
6934 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006935 }
6936 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006937 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006938 }
6939}
6940
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006941/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006942/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006943static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006944 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6945 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006946 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6947 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006948 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006949 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006950 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006951 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006952 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006953 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006954 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006955 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6956 // Ranged for is supported only in OpenMP 5.0.
6957 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006958 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006959 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006960 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006961 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006962 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006963 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6964 SemaRef.Diag(DSA.getConstructLoc(),
6965 diag::note_omp_collapse_ordered_expr)
6966 << 2 << CollapseLoopCountExpr->getSourceRange()
6967 << OrderedLoopCountExpr->getSourceRange();
6968 else if (CollapseLoopCountExpr)
6969 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6970 diag::note_omp_collapse_ordered_expr)
6971 << 0 << CollapseLoopCountExpr->getSourceRange();
6972 else
6973 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6974 diag::note_omp_collapse_ordered_expr)
6975 << 1 << OrderedLoopCountExpr->getSourceRange();
6976 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006977 return true;
6978 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006979 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6980 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006981
Alexey Bataevbef93a92019-10-07 18:54:57 +00006982 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6983 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006984
6985 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006986 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00006987 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006988 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006989
6990 bool HasErrors = false;
6991
6992 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006993 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006994 // OpenMP [2.6, Canonical Loop Form]
6995 // Var is one of the following:
6996 // A variable of signed or unsigned integer type.
6997 // For C++, a variable of a random access iterator type.
6998 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006999 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007000 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
7001 !VarType->isPointerType() &&
7002 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007003 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007004 << SemaRef.getLangOpts().CPlusPlus;
7005 HasErrors = true;
7006 }
7007
7008 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
7009 // a Construct
7010 // The loop iteration variable(s) in the associated for-loop(s) of a for or
7011 // parallel for construct is (are) private.
7012 // The loop iteration variable in the associated for-loop of a simd
7013 // construct with just one associated for-loop is linear with a
7014 // constant-linear-step that is the increment of the associated for-loop.
7015 // Exclude loop var from the list of variables with implicitly defined data
7016 // sharing attributes.
7017 VarsWithImplicitDSA.erase(LCDecl);
7018
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007019 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
7020
7021 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007022 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007023
7024 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007025 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007026 }
7027
Alexey Bataeve3727102018-04-18 15:57:46 +00007028 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007029 return HasErrors;
7030
Alexander Musmana5f070a2014-10-01 06:03:56 +00007031 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007032 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
7033 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007034 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
7035 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
7036 (isOpenMPWorksharingDirective(DKind) ||
7037 isOpenMPTaskLoopDirective(DKind) ||
7038 isOpenMPDistributeDirective(DKind)),
7039 Captures);
7040 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
7041 ISC.buildCounterVar(Captures, DSA);
7042 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
7043 ISC.buildPrivateCounterVar();
7044 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
7045 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
7046 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
7047 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
7048 ISC.getConditionSrcRange();
7049 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
7050 ISC.getIncrementSrcRange();
7051 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
7052 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
7053 ISC.isStrictTestOp();
7054 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
7055 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
7056 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
7057 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
7058 ISC.buildFinalCondition(DSA.getCurScope());
7059 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
7060 ISC.doesInitDependOnLC();
7061 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
7062 ISC.doesCondDependOnLC();
7063 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
7064 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007065
Alexey Bataevf8be4762019-08-14 19:30:06 +00007066 HasErrors |=
7067 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
7068 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
7069 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
7070 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
7071 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
7072 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007073 if (!HasErrors && DSA.isOrderedRegion()) {
7074 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7075 if (CurrentNestedLoopCount <
7076 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7077 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007078 CurrentNestedLoopCount,
7079 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007080 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007081 CurrentNestedLoopCount,
7082 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007083 }
7084 }
7085 for (auto &Pair : DSA.getDoacrossDependClauses()) {
7086 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7087 // Erroneous case - clause has some problems.
7088 continue;
7089 }
7090 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7091 Pair.second.size() <= CurrentNestedLoopCount) {
7092 // Erroneous case - clause has some problems.
7093 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7094 continue;
7095 }
7096 Expr *CntValue;
7097 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7098 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007099 DSA.getCurScope(),
7100 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007101 Pair.first->getDependencyLoc());
7102 else
7103 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007104 DSA.getCurScope(),
7105 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007106 Pair.first->getDependencyLoc(),
7107 Pair.second[CurrentNestedLoopCount].first,
7108 Pair.second[CurrentNestedLoopCount].second);
7109 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7110 }
7111 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007112
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007113 return HasErrors;
7114}
7115
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007116/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00007117static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00007118buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007119 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007120 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007121 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007122 ExprResult NewStart = IsNonRectangularLB
7123 ? Start.get()
7124 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00007125 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007126 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00007127 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00007128 VarRef.get()->getType())) {
7129 NewStart = SemaRef.PerformImplicitConversion(
7130 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7131 /*AllowExplicit=*/true);
7132 if (!NewStart.isUsable())
7133 return ExprError();
7134 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007135
Alexey Bataeve3727102018-04-18 15:57:46 +00007136 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007137 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7138 return Init;
7139}
7140
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007141/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00007142static ExprResult buildCounterUpdate(
7143 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7144 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007145 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007146 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007147 // Add parentheses (for debugging purposes only).
7148 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7149 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7150 !Step.isUsable())
7151 return ExprError();
7152
Alexey Bataev5a3af132016-03-29 08:58:54 +00007153 ExprResult NewStep = Step;
7154 if (Captures)
7155 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007156 if (NewStep.isInvalid())
7157 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007158 ExprResult Update =
7159 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007160 if (!Update.isUsable())
7161 return ExprError();
7162
Alexey Bataevc0214e02016-02-16 12:13:49 +00007163 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7164 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007165 if (!Start.isUsable())
7166 return ExprError();
7167 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7168 if (!NewStart.isUsable())
7169 return ExprError();
7170 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007171 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007172 if (NewStart.isInvalid())
7173 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007174
Alexey Bataevc0214e02016-02-16 12:13:49 +00007175 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7176 ExprResult SavedUpdate = Update;
7177 ExprResult UpdateVal;
7178 if (VarRef.get()->getType()->isOverloadableType() ||
7179 NewStart.get()->getType()->isOverloadableType() ||
7180 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007181 Sema::TentativeAnalysisScope Trap(SemaRef);
7182
Alexey Bataevc0214e02016-02-16 12:13:49 +00007183 Update =
7184 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7185 if (Update.isUsable()) {
7186 UpdateVal =
7187 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7188 VarRef.get(), SavedUpdate.get());
7189 if (UpdateVal.isUsable()) {
7190 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7191 UpdateVal.get());
7192 }
7193 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007194 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007195
Alexey Bataevc0214e02016-02-16 12:13:49 +00007196 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7197 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7198 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7199 NewStart.get(), SavedUpdate.get());
7200 if (!Update.isUsable())
7201 return ExprError();
7202
Alexey Bataev11481f52016-02-17 10:29:05 +00007203 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7204 VarRef.get()->getType())) {
7205 Update = SemaRef.PerformImplicitConversion(
7206 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7207 if (!Update.isUsable())
7208 return ExprError();
7209 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007210
7211 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7212 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007213 return Update;
7214}
7215
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007216/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007217/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007218static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007219 if (E == nullptr)
7220 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007221 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007222 QualType OldType = E->getType();
7223 unsigned HasBits = C.getTypeSize(OldType);
7224 if (HasBits >= Bits)
7225 return ExprResult(E);
7226 // OK to convert to signed, because new type has more bits than old.
7227 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7228 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7229 true);
7230}
7231
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007232/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007233/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007234static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007235 if (E == nullptr)
7236 return false;
7237 llvm::APSInt Result;
7238 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7239 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7240 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007241}
7242
Alexey Bataev5a3af132016-03-29 08:58:54 +00007243/// Build preinits statement for the given declarations.
7244static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007245 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007246 if (!PreInits.empty()) {
7247 return new (Context) DeclStmt(
7248 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7249 SourceLocation(), SourceLocation());
7250 }
7251 return nullptr;
7252}
7253
7254/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007255static Stmt *
7256buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007257 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007258 if (!Captures.empty()) {
7259 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007260 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007261 PreInits.push_back(Pair.second->getDecl());
7262 return buildPreInits(Context, PreInits);
7263 }
7264 return nullptr;
7265}
7266
7267/// Build postupdate expression for the given list of postupdates expressions.
7268static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7269 Expr *PostUpdate = nullptr;
7270 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007271 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007272 Expr *ConvE = S.BuildCStyleCastExpr(
7273 E->getExprLoc(),
7274 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7275 E->getExprLoc(), E)
7276 .get();
7277 PostUpdate = PostUpdate
7278 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7279 PostUpdate, ConvE)
7280 .get()
7281 : ConvE;
7282 }
7283 }
7284 return PostUpdate;
7285}
7286
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007287/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007288/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7289/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007290static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007291checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007292 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7293 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007294 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007295 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007296 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007297 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007298 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007299 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007300 if (!CollapseLoopCountExpr->isValueDependent() &&
7301 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007302 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007303 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007304 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007305 return 1;
7306 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007307 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007308 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007309 if (OrderedLoopCountExpr) {
7310 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007311 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007312 if (!OrderedLoopCountExpr->isValueDependent() &&
7313 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7314 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007315 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007316 if (Result.getLimitedValue() < NestedLoopCount) {
7317 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7318 diag::err_omp_wrong_ordered_loop_count)
7319 << OrderedLoopCountExpr->getSourceRange();
7320 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7321 diag::note_collapse_loop_count)
7322 << CollapseLoopCountExpr->getSourceRange();
7323 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007324 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007325 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007326 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007327 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007328 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007329 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007330 // This is helper routine for loop directives (e.g., 'for', 'simd',
7331 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007332 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007333 SmallVector<LoopIterationSpace, 4> IterSpaces(
7334 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007335 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007336 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007337 if (checkOpenMPIterationSpace(
7338 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7339 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007340 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007341 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007342 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007343 // OpenMP [2.8.1, simd construct, Restrictions]
7344 // All loops associated with the construct must be perfectly nested; that
7345 // is, there must be no intervening code nor any OpenMP directive between
7346 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007347 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7348 CurStmt = For->getBody();
7349 } else {
7350 assert(isa<CXXForRangeStmt>(CurStmt) &&
7351 "Expected canonical for or range-based for loops.");
7352 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7353 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007354 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7355 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007356 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007357 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7358 if (checkOpenMPIterationSpace(
7359 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7360 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007361 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007362 return 0;
7363 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7364 // Handle initialization of captured loop iterator variables.
7365 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7366 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7367 Captures[DRE] = DRE;
7368 }
7369 }
7370 // Move on to the next nested for loop, or to the loop body.
7371 // OpenMP [2.8.1, simd construct, Restrictions]
7372 // All loops associated with the construct must be perfectly nested; that
7373 // is, there must be no intervening code nor any OpenMP directive between
7374 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007375 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7376 CurStmt = For->getBody();
7377 } else {
7378 assert(isa<CXXForRangeStmt>(CurStmt) &&
7379 "Expected canonical for or range-based for loops.");
7380 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7381 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007382 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7383 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007384 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007385
Alexander Musmana5f070a2014-10-01 06:03:56 +00007386 Built.clear(/* size */ NestedLoopCount);
7387
7388 if (SemaRef.CurContext->isDependentContext())
7389 return NestedLoopCount;
7390
7391 // An example of what is generated for the following code:
7392 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007393 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007394 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007395 // for (k = 0; k < NK; ++k)
7396 // for (j = J0; j < NJ; j+=2) {
7397 // <loop body>
7398 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007399 //
7400 // We generate the code below.
7401 // Note: the loop body may be outlined in CodeGen.
7402 // Note: some counters may be C++ classes, operator- is used to find number of
7403 // iterations and operator+= to calculate counter value.
7404 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7405 // or i64 is currently supported).
7406 //
7407 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7408 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7409 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7410 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7411 // // similar updates for vars in clauses (e.g. 'linear')
7412 // <loop body (using local i and j)>
7413 // }
7414 // i = NI; // assign final values of counters
7415 // j = NJ;
7416 //
7417
7418 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7419 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007420 // Precondition tests if there is at least one iteration (all conditions are
7421 // true).
7422 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007423 Expr *N0 = IterSpaces[0].NumIterations;
7424 ExprResult LastIteration32 =
7425 widenIterationCount(/*Bits=*/32,
7426 SemaRef
7427 .PerformImplicitConversion(
7428 N0->IgnoreImpCasts(), N0->getType(),
7429 Sema::AA_Converting, /*AllowExplicit=*/true)
7430 .get(),
7431 SemaRef);
7432 ExprResult LastIteration64 = widenIterationCount(
7433 /*Bits=*/64,
7434 SemaRef
7435 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7436 Sema::AA_Converting,
7437 /*AllowExplicit=*/true)
7438 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007439 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007440
7441 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7442 return NestedLoopCount;
7443
Alexey Bataeve3727102018-04-18 15:57:46 +00007444 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007445 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7446
7447 Scope *CurScope = DSA.getCurScope();
7448 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007449 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007450 PreCond =
7451 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7452 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007453 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007454 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007455 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007456 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7457 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007458 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007459 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007460 SemaRef
7461 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7462 Sema::AA_Converting,
7463 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007464 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007465 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007466 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007467 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007468 SemaRef
7469 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7470 Sema::AA_Converting,
7471 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007472 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007473 }
7474
7475 // Choose either the 32-bit or 64-bit version.
7476 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007477 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7478 (LastIteration32.isUsable() &&
7479 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7480 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7481 fitsInto(
7482 /*Bits=*/32,
7483 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7484 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007485 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007486 QualType VType = LastIteration.get()->getType();
7487 QualType RealVType = VType;
7488 QualType StrideVType = VType;
7489 if (isOpenMPTaskLoopDirective(DKind)) {
7490 VType =
7491 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7492 StrideVType =
7493 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7494 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007495
7496 if (!LastIteration.isUsable())
7497 return 0;
7498
7499 // Save the number of iterations.
7500 ExprResult NumIterations = LastIteration;
7501 {
7502 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007503 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7504 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007505 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7506 if (!LastIteration.isUsable())
7507 return 0;
7508 }
7509
7510 // Calculate the last iteration number beforehand instead of doing this on
7511 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7512 llvm::APSInt Result;
7513 bool IsConstant =
7514 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7515 ExprResult CalcLastIteration;
7516 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007517 ExprResult SaveRef =
7518 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007519 LastIteration = SaveRef;
7520
7521 // Prepare SaveRef + 1.
7522 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007523 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007524 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7525 if (!NumIterations.isUsable())
7526 return 0;
7527 }
7528
7529 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7530
David Majnemer9d168222016-08-05 17:44:54 +00007531 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007532 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007533 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7534 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007535 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007536 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7537 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007538 SemaRef.AddInitializerToDecl(LBDecl,
7539 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7540 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007541
7542 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007543 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7544 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007545 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007546 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007547
7548 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7549 // This will be used to implement clause 'lastprivate'.
7550 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007551 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7552 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007553 SemaRef.AddInitializerToDecl(ILDecl,
7554 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7555 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007556
7557 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007558 VarDecl *STDecl =
7559 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7560 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007561 SemaRef.AddInitializerToDecl(STDecl,
7562 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7563 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007564
7565 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007566 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007567 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7568 UB.get(), LastIteration.get());
7569 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007570 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7571 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007572 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7573 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007574 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007575
7576 // If we have a combined directive that combines 'distribute', 'for' or
7577 // 'simd' we need to be able to access the bounds of the schedule of the
7578 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7579 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7580 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007581 // Lower bound variable, initialized with zero.
7582 VarDecl *CombLBDecl =
7583 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7584 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7585 SemaRef.AddInitializerToDecl(
7586 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7587 /*DirectInit*/ false);
7588
7589 // Upper bound variable, initialized with last iteration number.
7590 VarDecl *CombUBDecl =
7591 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7592 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7593 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7594 /*DirectInit*/ false);
7595
7596 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7597 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7598 ExprResult CombCondOp =
7599 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7600 LastIteration.get(), CombUB.get());
7601 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7602 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007603 CombEUB =
7604 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007605
Alexey Bataeve3727102018-04-18 15:57:46 +00007606 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007607 // We expect to have at least 2 more parameters than the 'parallel'
7608 // directive does - the lower and upper bounds of the previous schedule.
7609 assert(CD->getNumParams() >= 4 &&
7610 "Unexpected number of parameters in loop combined directive");
7611
7612 // Set the proper type for the bounds given what we learned from the
7613 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007614 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7615 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007616
7617 // Previous lower and upper bounds are obtained from the region
7618 // parameters.
7619 PrevLB =
7620 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7621 PrevUB =
7622 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7623 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007624 }
7625
7626 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007627 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007628 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007629 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007630 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7631 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007632 Expr *RHS =
7633 (isOpenMPWorksharingDirective(DKind) ||
7634 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7635 ? LB.get()
7636 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007637 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007638 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007639
7640 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7641 Expr *CombRHS =
7642 (isOpenMPWorksharingDirective(DKind) ||
7643 isOpenMPTaskLoopDirective(DKind) ||
7644 isOpenMPDistributeDirective(DKind))
7645 ? CombLB.get()
7646 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7647 CombInit =
7648 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007649 CombInit =
7650 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007651 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007652 }
7653
Alexey Bataev316ccf62019-01-29 18:51:58 +00007654 bool UseStrictCompare =
7655 RealVType->hasUnsignedIntegerRepresentation() &&
7656 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7657 return LIS.IsStrictCompare;
7658 });
7659 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7660 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007661 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007662 Expr *BoundUB = UB.get();
7663 if (UseStrictCompare) {
7664 BoundUB =
7665 SemaRef
7666 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7667 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7668 .get();
7669 BoundUB =
7670 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7671 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007672 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007673 (isOpenMPWorksharingDirective(DKind) ||
7674 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007675 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7676 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7677 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007678 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7679 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007680 ExprResult CombDistCond;
7681 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007682 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7683 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007684 }
7685
Carlo Bertolliffafe102017-04-20 00:39:39 +00007686 ExprResult CombCond;
7687 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007688 Expr *BoundCombUB = CombUB.get();
7689 if (UseStrictCompare) {
7690 BoundCombUB =
7691 SemaRef
7692 .BuildBinOp(
7693 CurScope, CondLoc, BO_Add, BoundCombUB,
7694 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7695 .get();
7696 BoundCombUB =
7697 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7698 .get();
7699 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007700 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007701 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7702 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007703 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007704 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007705 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007706 ExprResult Inc =
7707 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7708 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7709 if (!Inc.isUsable())
7710 return 0;
7711 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007712 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007713 if (!Inc.isUsable())
7714 return 0;
7715
7716 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7717 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007718 // In combined construct, add combined version that use CombLB and CombUB
7719 // base variables for the update
7720 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007721 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7722 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007723 // LB + ST
7724 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7725 if (!NextLB.isUsable())
7726 return 0;
7727 // LB = LB + ST
7728 NextLB =
7729 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007730 NextLB =
7731 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007732 if (!NextLB.isUsable())
7733 return 0;
7734 // UB + ST
7735 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7736 if (!NextUB.isUsable())
7737 return 0;
7738 // UB = UB + ST
7739 NextUB =
7740 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007741 NextUB =
7742 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007743 if (!NextUB.isUsable())
7744 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007745 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7746 CombNextLB =
7747 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7748 if (!NextLB.isUsable())
7749 return 0;
7750 // LB = LB + ST
7751 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7752 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007753 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7754 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007755 if (!CombNextLB.isUsable())
7756 return 0;
7757 // UB + ST
7758 CombNextUB =
7759 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7760 if (!CombNextUB.isUsable())
7761 return 0;
7762 // UB = UB + ST
7763 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7764 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007765 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7766 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007767 if (!CombNextUB.isUsable())
7768 return 0;
7769 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007770 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007771
Carlo Bertolliffafe102017-04-20 00:39:39 +00007772 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007773 // directive with for as IV = IV + ST; ensure upper bound expression based
7774 // on PrevUB instead of NumIterations - used to implement 'for' when found
7775 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007776 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007777 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007778 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007779 DistCond = SemaRef.BuildBinOp(
7780 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007781 assert(DistCond.isUsable() && "distribute cond expr was not built");
7782
7783 DistInc =
7784 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7785 assert(DistInc.isUsable() && "distribute inc expr was not built");
7786 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7787 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007788 DistInc =
7789 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007790 assert(DistInc.isUsable() && "distribute inc expr was not built");
7791
7792 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7793 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007794 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007795 ExprResult IsUBGreater =
7796 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7797 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7798 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7799 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7800 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007801 PrevEUB =
7802 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007803
Alexey Bataev316ccf62019-01-29 18:51:58 +00007804 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7805 // parallel for is in combination with a distribute directive with
7806 // schedule(static, 1)
7807 Expr *BoundPrevUB = PrevUB.get();
7808 if (UseStrictCompare) {
7809 BoundPrevUB =
7810 SemaRef
7811 .BuildBinOp(
7812 CurScope, CondLoc, BO_Add, BoundPrevUB,
7813 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7814 .get();
7815 BoundPrevUB =
7816 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7817 .get();
7818 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007819 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007820 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7821 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007822 }
7823
Alexander Musmana5f070a2014-10-01 06:03:56 +00007824 // Build updates and final values of the loop counters.
7825 bool HasErrors = false;
7826 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007827 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007828 Built.Updates.resize(NestedLoopCount);
7829 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007830 Built.DependentCounters.resize(NestedLoopCount);
7831 Built.DependentInits.resize(NestedLoopCount);
7832 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007833 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007834 // We implement the following algorithm for obtaining the
7835 // original loop iteration variable values based on the
7836 // value of the collapsed loop iteration variable IV.
7837 //
7838 // Let n+1 be the number of collapsed loops in the nest.
7839 // Iteration variables (I0, I1, .... In)
7840 // Iteration counts (N0, N1, ... Nn)
7841 //
7842 // Acc = IV;
7843 //
7844 // To compute Ik for loop k, 0 <= k <= n, generate:
7845 // Prod = N(k+1) * N(k+2) * ... * Nn;
7846 // Ik = Acc / Prod;
7847 // Acc -= Ik * Prod;
7848 //
7849 ExprResult Acc = IV;
7850 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007851 LoopIterationSpace &IS = IterSpaces[Cnt];
7852 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007853 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007854
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007855 // Compute prod
7856 ExprResult Prod =
7857 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7858 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7859 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7860 IterSpaces[K].NumIterations);
7861
7862 // Iter = Acc / Prod
7863 // If there is at least one more inner loop to avoid
7864 // multiplication by 1.
7865 if (Cnt + 1 < NestedLoopCount)
7866 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7867 Acc.get(), Prod.get());
7868 else
7869 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007870 if (!Iter.isUsable()) {
7871 HasErrors = true;
7872 break;
7873 }
7874
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007875 // Update Acc:
7876 // Acc -= Iter * Prod
7877 // Check if there is at least one more inner loop to avoid
7878 // multiplication by 1.
7879 if (Cnt + 1 < NestedLoopCount)
7880 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7881 Iter.get(), Prod.get());
7882 else
7883 Prod = Iter;
7884 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7885 Acc.get(), Prod.get());
7886
Alexey Bataev39f915b82015-05-08 10:41:21 +00007887 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007888 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007889 DeclRefExpr *CounterVar = buildDeclRefExpr(
7890 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7891 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007892 ExprResult Init =
7893 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7894 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007895 if (!Init.isUsable()) {
7896 HasErrors = true;
7897 break;
7898 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007899 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007900 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007901 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007902 if (!Update.isUsable()) {
7903 HasErrors = true;
7904 break;
7905 }
7906
7907 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007908 ExprResult Final =
7909 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7910 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7911 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007912 if (!Final.isUsable()) {
7913 HasErrors = true;
7914 break;
7915 }
7916
Alexander Musmana5f070a2014-10-01 06:03:56 +00007917 if (!Update.isUsable() || !Final.isUsable()) {
7918 HasErrors = true;
7919 break;
7920 }
7921 // Save results
7922 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007923 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007924 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007925 Built.Updates[Cnt] = Update.get();
7926 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007927 Built.DependentCounters[Cnt] = nullptr;
7928 Built.DependentInits[Cnt] = nullptr;
7929 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007930 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007931 Built.DependentCounters[Cnt] =
7932 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7933 Built.DependentInits[Cnt] =
7934 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7935 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7936 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007937 }
7938 }
7939
7940 if (HasErrors)
7941 return 0;
7942
7943 // Save results
7944 Built.IterationVarRef = IV.get();
7945 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007946 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007947 Built.CalcLastIteration = SemaRef
7948 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007949 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007950 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007951 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007952 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007953 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007954 Built.Init = Init.get();
7955 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007956 Built.LB = LB.get();
7957 Built.UB = UB.get();
7958 Built.IL = IL.get();
7959 Built.ST = ST.get();
7960 Built.EUB = EUB.get();
7961 Built.NLB = NextLB.get();
7962 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007963 Built.PrevLB = PrevLB.get();
7964 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007965 Built.DistInc = DistInc.get();
7966 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007967 Built.DistCombinedFields.LB = CombLB.get();
7968 Built.DistCombinedFields.UB = CombUB.get();
7969 Built.DistCombinedFields.EUB = CombEUB.get();
7970 Built.DistCombinedFields.Init = CombInit.get();
7971 Built.DistCombinedFields.Cond = CombCond.get();
7972 Built.DistCombinedFields.NLB = CombNextLB.get();
7973 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007974 Built.DistCombinedFields.DistCond = CombDistCond.get();
7975 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007976
Alexey Bataevabfc0692014-06-25 06:52:00 +00007977 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007978}
7979
Alexey Bataev10e775f2015-07-30 11:36:16 +00007980static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007981 auto CollapseClauses =
7982 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7983 if (CollapseClauses.begin() != CollapseClauses.end())
7984 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007985 return nullptr;
7986}
7987
Alexey Bataev10e775f2015-07-30 11:36:16 +00007988static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007989 auto OrderedClauses =
7990 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7991 if (OrderedClauses.begin() != OrderedClauses.end())
7992 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007993 return nullptr;
7994}
7995
Kelvin Lic5609492016-07-15 04:39:07 +00007996static bool checkSimdlenSafelenSpecified(Sema &S,
7997 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007998 const OMPSafelenClause *Safelen = nullptr;
7999 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00008000
Alexey Bataeve3727102018-04-18 15:57:46 +00008001 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00008002 if (Clause->getClauseKind() == OMPC_safelen)
8003 Safelen = cast<OMPSafelenClause>(Clause);
8004 else if (Clause->getClauseKind() == OMPC_simdlen)
8005 Simdlen = cast<OMPSimdlenClause>(Clause);
8006 if (Safelen && Simdlen)
8007 break;
8008 }
8009
8010 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008011 const Expr *SimdlenLength = Simdlen->getSimdlen();
8012 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00008013 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
8014 SimdlenLength->isInstantiationDependent() ||
8015 SimdlenLength->containsUnexpandedParameterPack())
8016 return false;
8017 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
8018 SafelenLength->isInstantiationDependent() ||
8019 SafelenLength->containsUnexpandedParameterPack())
8020 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008021 Expr::EvalResult SimdlenResult, SafelenResult;
8022 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
8023 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
8024 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
8025 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00008026 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
8027 // If both simdlen and safelen clauses are specified, the value of the
8028 // simdlen parameter must be less than or equal to the value of the safelen
8029 // parameter.
8030 if (SimdlenRes > SafelenRes) {
8031 S.Diag(SimdlenLength->getExprLoc(),
8032 diag::err_omp_wrong_simdlen_safelen_values)
8033 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
8034 return true;
8035 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00008036 }
8037 return false;
8038}
8039
Alexey Bataeve3727102018-04-18 15:57:46 +00008040StmtResult
8041Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8042 SourceLocation StartLoc, SourceLocation EndLoc,
8043 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008044 if (!AStmt)
8045 return StmtError();
8046
8047 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008048 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008049 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8050 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008051 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008052 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8053 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008054 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008055 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008056
Alexander Musmana5f070a2014-10-01 06:03:56 +00008057 assert((CurContext->isDependentContext() || B.builtAll()) &&
8058 "omp simd loop exprs were not built");
8059
Alexander Musman3276a272015-03-21 10:12:56 +00008060 if (!CurContext->isDependentContext()) {
8061 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008062 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008063 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00008064 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008065 B.NumIterations, *this, CurScope,
8066 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00008067 return StmtError();
8068 }
8069 }
8070
Kelvin Lic5609492016-07-15 04:39:07 +00008071 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008072 return StmtError();
8073
Reid Kleckner87a31802018-03-12 21:43:02 +00008074 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008075 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8076 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008077}
8078
Alexey Bataeve3727102018-04-18 15:57:46 +00008079StmtResult
8080Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8081 SourceLocation StartLoc, SourceLocation EndLoc,
8082 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008083 if (!AStmt)
8084 return StmtError();
8085
8086 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008087 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008088 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8089 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008090 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008091 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8092 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008093 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00008094 return StmtError();
8095
Alexander Musmana5f070a2014-10-01 06:03:56 +00008096 assert((CurContext->isDependentContext() || B.builtAll()) &&
8097 "omp for loop exprs were not built");
8098
Alexey Bataev54acd402015-08-04 11:18:19 +00008099 if (!CurContext->isDependentContext()) {
8100 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008101 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008102 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008103 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008104 B.NumIterations, *this, CurScope,
8105 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008106 return StmtError();
8107 }
8108 }
8109
Reid Kleckner87a31802018-03-12 21:43:02 +00008110 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008111 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008112 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00008113}
8114
Alexander Musmanf82886e2014-09-18 05:12:34 +00008115StmtResult Sema::ActOnOpenMPForSimdDirective(
8116 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008117 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008118 if (!AStmt)
8119 return StmtError();
8120
8121 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008122 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008123 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8124 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00008125 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008126 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008127 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8128 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008129 if (NestedLoopCount == 0)
8130 return StmtError();
8131
Alexander Musmanc6388682014-12-15 07:07:06 +00008132 assert((CurContext->isDependentContext() || B.builtAll()) &&
8133 "omp for simd loop exprs were not built");
8134
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008135 if (!CurContext->isDependentContext()) {
8136 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008137 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008138 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008139 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008140 B.NumIterations, *this, CurScope,
8141 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008142 return StmtError();
8143 }
8144 }
8145
Kelvin Lic5609492016-07-15 04:39:07 +00008146 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008147 return StmtError();
8148
Reid Kleckner87a31802018-03-12 21:43:02 +00008149 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008150 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8151 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008152}
8153
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008154StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8155 Stmt *AStmt,
8156 SourceLocation StartLoc,
8157 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008158 if (!AStmt)
8159 return StmtError();
8160
8161 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008162 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008163 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008164 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008165 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008166 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008167 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008168 return StmtError();
8169 // All associated statements must be '#pragma omp section' except for
8170 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008171 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008172 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8173 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008174 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008175 diag::err_omp_sections_substmt_not_section);
8176 return StmtError();
8177 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008178 cast<OMPSectionDirective>(SectionStmt)
8179 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008180 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008181 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008182 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008183 return StmtError();
8184 }
8185
Reid Kleckner87a31802018-03-12 21:43:02 +00008186 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008187
Alexey Bataev25e5b442015-09-15 12:52:43 +00008188 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8189 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008190}
8191
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008192StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8193 SourceLocation StartLoc,
8194 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008195 if (!AStmt)
8196 return StmtError();
8197
8198 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008199
Reid Kleckner87a31802018-03-12 21:43:02 +00008200 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008201 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008202
Alexey Bataev25e5b442015-09-15 12:52:43 +00008203 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8204 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008205}
8206
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008207StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8208 Stmt *AStmt,
8209 SourceLocation StartLoc,
8210 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008211 if (!AStmt)
8212 return StmtError();
8213
8214 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008215
Reid Kleckner87a31802018-03-12 21:43:02 +00008216 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008217
Alexey Bataev3255bf32015-01-19 05:20:46 +00008218 // OpenMP [2.7.3, single Construct, Restrictions]
8219 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008220 const OMPClause *Nowait = nullptr;
8221 const OMPClause *Copyprivate = nullptr;
8222 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008223 if (Clause->getClauseKind() == OMPC_nowait)
8224 Nowait = Clause;
8225 else if (Clause->getClauseKind() == OMPC_copyprivate)
8226 Copyprivate = Clause;
8227 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008228 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008229 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008230 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008231 return StmtError();
8232 }
8233 }
8234
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008235 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8236}
8237
Alexander Musman80c22892014-07-17 08:54:58 +00008238StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8239 SourceLocation StartLoc,
8240 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008241 if (!AStmt)
8242 return StmtError();
8243
8244 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008245
Reid Kleckner87a31802018-03-12 21:43:02 +00008246 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008247
8248 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8249}
8250
Alexey Bataev28c75412015-12-15 08:19:24 +00008251StmtResult Sema::ActOnOpenMPCriticalDirective(
8252 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8253 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008254 if (!AStmt)
8255 return StmtError();
8256
8257 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008258
Alexey Bataev28c75412015-12-15 08:19:24 +00008259 bool ErrorFound = false;
8260 llvm::APSInt Hint;
8261 SourceLocation HintLoc;
8262 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008263 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008264 if (C->getClauseKind() == OMPC_hint) {
8265 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008266 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008267 ErrorFound = true;
8268 }
8269 Expr *E = cast<OMPHintClause>(C)->getHint();
8270 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008271 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008272 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008273 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008274 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008275 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008276 }
8277 }
8278 }
8279 if (ErrorFound)
8280 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008281 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008282 if (Pair.first && DirName.getName() && !DependentHint) {
8283 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8284 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008285 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008286 Diag(HintLoc, diag::note_omp_critical_hint_here)
8287 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008288 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008289 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008290 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008291 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008292 << 1
8293 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8294 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008295 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008296 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008297 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008298 }
8299 }
8300
Reid Kleckner87a31802018-03-12 21:43:02 +00008301 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008302
Alexey Bataev28c75412015-12-15 08:19:24 +00008303 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8304 Clauses, AStmt);
8305 if (!Pair.first && DirName.getName() && !DependentHint)
8306 DSAStack->addCriticalWithHint(Dir, Hint);
8307 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008308}
8309
Alexey Bataev4acb8592014-07-07 13:01:15 +00008310StmtResult Sema::ActOnOpenMPParallelForDirective(
8311 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008312 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008313 if (!AStmt)
8314 return StmtError();
8315
Alexey Bataeve3727102018-04-18 15:57:46 +00008316 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008317 // 1.2.2 OpenMP Language Terminology
8318 // Structured block - An executable statement with a single entry at the
8319 // top and a single exit at the bottom.
8320 // The point of exit cannot be a branch out of the structured block.
8321 // longjmp() and throw() must not violate the entry/exit criteria.
8322 CS->getCapturedDecl()->setNothrow();
8323
Alexander Musmanc6388682014-12-15 07:07:06 +00008324 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008325 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8326 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008327 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008328 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008329 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8330 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008331 if (NestedLoopCount == 0)
8332 return StmtError();
8333
Alexander Musmana5f070a2014-10-01 06:03:56 +00008334 assert((CurContext->isDependentContext() || B.builtAll()) &&
8335 "omp parallel for loop exprs were not built");
8336
Alexey Bataev54acd402015-08-04 11:18:19 +00008337 if (!CurContext->isDependentContext()) {
8338 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008339 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008340 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008341 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008342 B.NumIterations, *this, CurScope,
8343 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008344 return StmtError();
8345 }
8346 }
8347
Reid Kleckner87a31802018-03-12 21:43:02 +00008348 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008349 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008350 NestedLoopCount, Clauses, AStmt, B,
8351 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008352}
8353
Alexander Musmane4e893b2014-09-23 09:33:00 +00008354StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8355 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008356 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008357 if (!AStmt)
8358 return StmtError();
8359
Alexey Bataeve3727102018-04-18 15:57:46 +00008360 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008361 // 1.2.2 OpenMP Language Terminology
8362 // Structured block - An executable statement with a single entry at the
8363 // top and a single exit at the bottom.
8364 // The point of exit cannot be a branch out of the structured block.
8365 // longjmp() and throw() must not violate the entry/exit criteria.
8366 CS->getCapturedDecl()->setNothrow();
8367
Alexander Musmanc6388682014-12-15 07:07:06 +00008368 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008369 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8370 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008371 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008372 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008373 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8374 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008375 if (NestedLoopCount == 0)
8376 return StmtError();
8377
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008378 if (!CurContext->isDependentContext()) {
8379 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008380 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008381 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008382 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008383 B.NumIterations, *this, CurScope,
8384 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008385 return StmtError();
8386 }
8387 }
8388
Kelvin Lic5609492016-07-15 04:39:07 +00008389 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008390 return StmtError();
8391
Reid Kleckner87a31802018-03-12 21:43:02 +00008392 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008393 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008394 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008395}
8396
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008397StmtResult
cchen47d60942019-12-05 13:43:48 -05008398Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
8399 Stmt *AStmt, SourceLocation StartLoc,
8400 SourceLocation EndLoc) {
8401 if (!AStmt)
8402 return StmtError();
8403
8404 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8405 auto *CS = cast<CapturedStmt>(AStmt);
8406 // 1.2.2 OpenMP Language Terminology
8407 // Structured block - An executable statement with a single entry at the
8408 // top and a single exit at the bottom.
8409 // The point of exit cannot be a branch out of the structured block.
8410 // longjmp() and throw() must not violate the entry/exit criteria.
8411 CS->getCapturedDecl()->setNothrow();
8412
8413 setFunctionHasBranchProtectedScope();
8414
8415 return OMPParallelMasterDirective::Create(Context, StartLoc, EndLoc, Clauses,
8416 AStmt);
8417}
8418
8419StmtResult
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008420Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8421 Stmt *AStmt, SourceLocation StartLoc,
8422 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008423 if (!AStmt)
8424 return StmtError();
8425
8426 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008427 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008428 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008429 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008430 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008431 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008432 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008433 return StmtError();
8434 // All associated statements must be '#pragma omp section' except for
8435 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008436 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008437 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8438 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008439 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008440 diag::err_omp_parallel_sections_substmt_not_section);
8441 return StmtError();
8442 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008443 cast<OMPSectionDirective>(SectionStmt)
8444 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008445 }
8446 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008447 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008448 diag::err_omp_parallel_sections_not_compound_stmt);
8449 return StmtError();
8450 }
8451
Reid Kleckner87a31802018-03-12 21:43:02 +00008452 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008453
Alexey Bataev25e5b442015-09-15 12:52:43 +00008454 return OMPParallelSectionsDirective::Create(
8455 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008456}
8457
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008458StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8459 Stmt *AStmt, SourceLocation StartLoc,
8460 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008461 if (!AStmt)
8462 return StmtError();
8463
David Majnemer9d168222016-08-05 17:44:54 +00008464 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008465 // 1.2.2 OpenMP Language Terminology
8466 // Structured block - An executable statement with a single entry at the
8467 // top and a single exit at the bottom.
8468 // The point of exit cannot be a branch out of the structured block.
8469 // longjmp() and throw() must not violate the entry/exit criteria.
8470 CS->getCapturedDecl()->setNothrow();
8471
Reid Kleckner87a31802018-03-12 21:43:02 +00008472 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008473
Alexey Bataev25e5b442015-09-15 12:52:43 +00008474 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8475 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008476}
8477
Alexey Bataev68446b72014-07-18 07:47:19 +00008478StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8479 SourceLocation EndLoc) {
8480 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8481}
8482
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008483StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8484 SourceLocation EndLoc) {
8485 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8486}
8487
Alexey Bataev2df347a2014-07-18 10:17:07 +00008488StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8489 SourceLocation EndLoc) {
8490 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8491}
8492
Alexey Bataev169d96a2017-07-18 20:17:46 +00008493StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8494 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008495 SourceLocation StartLoc,
8496 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008497 if (!AStmt)
8498 return StmtError();
8499
8500 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008501
Reid Kleckner87a31802018-03-12 21:43:02 +00008502 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008503
Alexey Bataev169d96a2017-07-18 20:17:46 +00008504 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008505 AStmt,
8506 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008507}
8508
Alexey Bataev6125da92014-07-21 11:26:11 +00008509StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8510 SourceLocation StartLoc,
8511 SourceLocation EndLoc) {
8512 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8513 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8514}
8515
Alexey Bataev346265e2015-09-25 10:37:12 +00008516StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8517 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008518 SourceLocation StartLoc,
8519 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008520 const OMPClause *DependFound = nullptr;
8521 const OMPClause *DependSourceClause = nullptr;
8522 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008523 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008524 const OMPThreadsClause *TC = nullptr;
8525 const OMPSIMDClause *SC = nullptr;
8526 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008527 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8528 DependFound = C;
8529 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8530 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008531 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008532 << getOpenMPDirectiveName(OMPD_ordered)
8533 << getOpenMPClauseName(OMPC_depend) << 2;
8534 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008535 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008536 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008537 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008538 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008539 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008540 << 0;
8541 ErrorFound = true;
8542 }
8543 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8544 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008545 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008546 << 1;
8547 ErrorFound = true;
8548 }
8549 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008550 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008551 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008552 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008553 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008554 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008555 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008556 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008557 if (!ErrorFound && !SC &&
8558 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008559 // OpenMP [2.8.1,simd Construct, Restrictions]
8560 // An ordered construct with the simd clause is the only OpenMP construct
8561 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008562 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8563 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008564 ErrorFound = true;
8565 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008566 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008567 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8568 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008569 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008570 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008571 diag::err_omp_ordered_directive_without_param);
8572 ErrorFound = true;
8573 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008574 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008575 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008576 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8577 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008578 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008579 ErrorFound = true;
8580 }
8581 }
8582 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008583 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008584
8585 if (AStmt) {
8586 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8587
Reid Kleckner87a31802018-03-12 21:43:02 +00008588 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008589 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008590
8591 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008592}
8593
Alexey Bataev1d160b12015-03-13 12:27:31 +00008594namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008595/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008596/// construct.
8597class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008598 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008599 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008600 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008601 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008602 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008603 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008604 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008605 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008606 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008607 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008608 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008609 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008610 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008611 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008612 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008613 /// expression.
8614 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008615 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008616 /// part.
8617 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008618 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008619 NoError
8620 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008621 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008622 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008623 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008624 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008625 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008626 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008627 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008628 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008629 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008630 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8631 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8632 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008633 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008634 /// important for non-associative operations.
8635 bool IsXLHSInRHSPart;
8636 BinaryOperatorKind Op;
8637 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008638 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008639 /// if it is a prefix unary operation.
8640 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008641
8642public:
8643 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008644 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008645 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008646 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008647 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008648 /// expression. If DiagId and NoteId == 0, then only check is performed
8649 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008650 /// \param DiagId Diagnostic which should be emitted if error is found.
8651 /// \param NoteId Diagnostic note for the main error message.
8652 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008653 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008654 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008655 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008656 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008657 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008658 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008659 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8660 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8661 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008662 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008663 /// false otherwise.
8664 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8665
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008666 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008667 /// if it is a prefix unary operation.
8668 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8669
Alexey Bataev1d160b12015-03-13 12:27:31 +00008670private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008671 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8672 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008673};
8674} // namespace
8675
8676bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8677 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8678 ExprAnalysisErrorCode ErrorFound = NoError;
8679 SourceLocation ErrorLoc, NoteLoc;
8680 SourceRange ErrorRange, NoteRange;
8681 // Allowed constructs are:
8682 // x = x binop expr;
8683 // x = expr binop x;
8684 if (AtomicBinOp->getOpcode() == BO_Assign) {
8685 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008686 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008687 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8688 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8689 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8690 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008691 Op = AtomicInnerBinOp->getOpcode();
8692 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008693 Expr *LHS = AtomicInnerBinOp->getLHS();
8694 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008695 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8696 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8697 /*Canonical=*/true);
8698 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8699 /*Canonical=*/true);
8700 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8701 /*Canonical=*/true);
8702 if (XId == LHSId) {
8703 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008704 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008705 } else if (XId == RHSId) {
8706 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008707 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008708 } else {
8709 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8710 ErrorRange = AtomicInnerBinOp->getSourceRange();
8711 NoteLoc = X->getExprLoc();
8712 NoteRange = X->getSourceRange();
8713 ErrorFound = NotAnUpdateExpression;
8714 }
8715 } else {
8716 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8717 ErrorRange = AtomicInnerBinOp->getSourceRange();
8718 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8719 NoteRange = SourceRange(NoteLoc, NoteLoc);
8720 ErrorFound = NotABinaryOperator;
8721 }
8722 } else {
8723 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8724 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8725 ErrorFound = NotABinaryExpression;
8726 }
8727 } else {
8728 ErrorLoc = AtomicBinOp->getExprLoc();
8729 ErrorRange = AtomicBinOp->getSourceRange();
8730 NoteLoc = AtomicBinOp->getOperatorLoc();
8731 NoteRange = SourceRange(NoteLoc, NoteLoc);
8732 ErrorFound = NotAnAssignmentOp;
8733 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008734 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008735 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8736 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8737 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008738 }
8739 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008740 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008741 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008742}
8743
8744bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8745 unsigned NoteId) {
8746 ExprAnalysisErrorCode ErrorFound = NoError;
8747 SourceLocation ErrorLoc, NoteLoc;
8748 SourceRange ErrorRange, NoteRange;
8749 // Allowed constructs are:
8750 // x++;
8751 // x--;
8752 // ++x;
8753 // --x;
8754 // x binop= expr;
8755 // x = x binop expr;
8756 // x = expr binop x;
8757 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8758 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8759 if (AtomicBody->getType()->isScalarType() ||
8760 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008761 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008762 AtomicBody->IgnoreParenImpCasts())) {
8763 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008764 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008765 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008766 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008767 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008768 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008769 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008770 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8771 AtomicBody->IgnoreParenImpCasts())) {
8772 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008773 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008774 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008775 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008776 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008777 // Check for Unary Operation
8778 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008779 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008780 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8781 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008782 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008783 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8784 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008785 } else {
8786 ErrorFound = NotAnUnaryIncDecExpression;
8787 ErrorLoc = AtomicUnaryOp->getExprLoc();
8788 ErrorRange = AtomicUnaryOp->getSourceRange();
8789 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8790 NoteRange = SourceRange(NoteLoc, NoteLoc);
8791 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008792 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008793 ErrorFound = NotABinaryOrUnaryExpression;
8794 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8795 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8796 }
8797 } else {
8798 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008799 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008800 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8801 }
8802 } else {
8803 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008804 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008805 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8806 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008807 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008808 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8809 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8810 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008811 }
8812 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008813 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008814 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008815 // Build an update expression of form 'OpaqueValueExpr(x) binop
8816 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8817 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8818 auto *OVEX = new (SemaRef.getASTContext())
8819 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8820 auto *OVEExpr = new (SemaRef.getASTContext())
8821 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008822 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008823 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8824 IsXLHSInRHSPart ? OVEExpr : OVEX);
8825 if (Update.isInvalid())
8826 return true;
8827 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8828 Sema::AA_Casting);
8829 if (Update.isInvalid())
8830 return true;
8831 UpdateExpr = Update.get();
8832 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008833 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008834}
8835
Alexey Bataev0162e452014-07-22 10:10:35 +00008836StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8837 Stmt *AStmt,
8838 SourceLocation StartLoc,
8839 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008840 if (!AStmt)
8841 return StmtError();
8842
David Majnemer9d168222016-08-05 17:44:54 +00008843 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008844 // 1.2.2 OpenMP Language Terminology
8845 // Structured block - An executable statement with a single entry at the
8846 // top and a single exit at the bottom.
8847 // The point of exit cannot be a branch out of the structured block.
8848 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008849 OpenMPClauseKind AtomicKind = OMPC_unknown;
8850 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008851 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008852 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008853 C->getClauseKind() == OMPC_update ||
8854 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008855 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008856 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008857 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008858 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8859 << getOpenMPClauseName(AtomicKind);
8860 } else {
8861 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008862 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008863 }
8864 }
8865 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008866
Alexey Bataeve3727102018-04-18 15:57:46 +00008867 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008868 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8869 Body = EWC->getSubExpr();
8870
Alexey Bataev62cec442014-11-18 10:14:22 +00008871 Expr *X = nullptr;
8872 Expr *V = nullptr;
8873 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008874 Expr *UE = nullptr;
8875 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008876 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008877 // OpenMP [2.12.6, atomic Construct]
8878 // In the next expressions:
8879 // * x and v (as applicable) are both l-value expressions with scalar type.
8880 // * During the execution of an atomic region, multiple syntactic
8881 // occurrences of x must designate the same storage location.
8882 // * Neither of v and expr (as applicable) may access the storage location
8883 // designated by x.
8884 // * Neither of x and expr (as applicable) may access the storage location
8885 // designated by v.
8886 // * expr is an expression with scalar type.
8887 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8888 // * binop, binop=, ++, and -- are not overloaded operators.
8889 // * The expression x binop expr must be numerically equivalent to x binop
8890 // (expr). This requirement is satisfied if the operators in expr have
8891 // precedence greater than binop, or by using parentheses around expr or
8892 // subexpressions of expr.
8893 // * The expression expr binop x must be numerically equivalent to (expr)
8894 // binop x. This requirement is satisfied if the operators in expr have
8895 // precedence equal to or greater than binop, or by using parentheses around
8896 // expr or subexpressions of expr.
8897 // * For forms that allow multiple occurrences of x, the number of times
8898 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008899 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008900 enum {
8901 NotAnExpression,
8902 NotAnAssignmentOp,
8903 NotAScalarType,
8904 NotAnLValue,
8905 NoError
8906 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008907 SourceLocation ErrorLoc, NoteLoc;
8908 SourceRange ErrorRange, NoteRange;
8909 // If clause is read:
8910 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008911 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8912 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008913 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8914 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8915 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8916 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8917 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8918 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8919 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008920 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008921 ErrorFound = NotAnLValue;
8922 ErrorLoc = AtomicBinOp->getExprLoc();
8923 ErrorRange = AtomicBinOp->getSourceRange();
8924 NoteLoc = NotLValueExpr->getExprLoc();
8925 NoteRange = NotLValueExpr->getSourceRange();
8926 }
8927 } else if (!X->isInstantiationDependent() ||
8928 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008929 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008930 (X->isInstantiationDependent() || X->getType()->isScalarType())
8931 ? V
8932 : X;
8933 ErrorFound = NotAScalarType;
8934 ErrorLoc = AtomicBinOp->getExprLoc();
8935 ErrorRange = AtomicBinOp->getSourceRange();
8936 NoteLoc = NotScalarExpr->getExprLoc();
8937 NoteRange = NotScalarExpr->getSourceRange();
8938 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008939 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008940 ErrorFound = NotAnAssignmentOp;
8941 ErrorLoc = AtomicBody->getExprLoc();
8942 ErrorRange = AtomicBody->getSourceRange();
8943 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8944 : AtomicBody->getExprLoc();
8945 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8946 : AtomicBody->getSourceRange();
8947 }
8948 } else {
8949 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008950 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008951 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008952 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008953 if (ErrorFound != NoError) {
8954 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8955 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008956 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8957 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008958 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008959 }
8960 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008961 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008962 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008963 enum {
8964 NotAnExpression,
8965 NotAnAssignmentOp,
8966 NotAScalarType,
8967 NotAnLValue,
8968 NoError
8969 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008970 SourceLocation ErrorLoc, NoteLoc;
8971 SourceRange ErrorRange, NoteRange;
8972 // If clause is write:
8973 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008974 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8975 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008976 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8977 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008978 X = AtomicBinOp->getLHS();
8979 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008980 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8981 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8982 if (!X->isLValue()) {
8983 ErrorFound = NotAnLValue;
8984 ErrorLoc = AtomicBinOp->getExprLoc();
8985 ErrorRange = AtomicBinOp->getSourceRange();
8986 NoteLoc = X->getExprLoc();
8987 NoteRange = X->getSourceRange();
8988 }
8989 } else if (!X->isInstantiationDependent() ||
8990 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008991 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008992 (X->isInstantiationDependent() || X->getType()->isScalarType())
8993 ? E
8994 : X;
8995 ErrorFound = NotAScalarType;
8996 ErrorLoc = AtomicBinOp->getExprLoc();
8997 ErrorRange = AtomicBinOp->getSourceRange();
8998 NoteLoc = NotScalarExpr->getExprLoc();
8999 NoteRange = NotScalarExpr->getSourceRange();
9000 }
Alexey Bataev5a195472015-09-04 12:55:50 +00009001 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00009002 ErrorFound = NotAnAssignmentOp;
9003 ErrorLoc = AtomicBody->getExprLoc();
9004 ErrorRange = AtomicBody->getSourceRange();
9005 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9006 : AtomicBody->getExprLoc();
9007 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9008 : AtomicBody->getSourceRange();
9009 }
9010 } else {
9011 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009012 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00009013 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00009014 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00009015 if (ErrorFound != NoError) {
9016 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
9017 << ErrorRange;
9018 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9019 << NoteRange;
9020 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00009021 }
9022 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00009023 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009024 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00009025 // If clause is update:
9026 // x++;
9027 // x--;
9028 // ++x;
9029 // --x;
9030 // x binop= expr;
9031 // x = x binop expr;
9032 // x = expr binop x;
9033 OpenMPAtomicUpdateChecker Checker(*this);
9034 if (Checker.checkStatement(
9035 Body, (AtomicKind == OMPC_update)
9036 ? diag::err_omp_atomic_update_not_expression_statement
9037 : diag::err_omp_atomic_not_expression_statement,
9038 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00009039 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00009040 if (!CurContext->isDependentContext()) {
9041 E = Checker.getExpr();
9042 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00009043 UE = Checker.getUpdateExpr();
9044 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00009045 }
Alexey Bataev459dec02014-07-24 06:46:57 +00009046 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009047 enum {
9048 NotAnAssignmentOp,
9049 NotACompoundStatement,
9050 NotTwoSubstatements,
9051 NotASpecificExpression,
9052 NoError
9053 } ErrorFound = NoError;
9054 SourceLocation ErrorLoc, NoteLoc;
9055 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009056 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009057 // If clause is a capture:
9058 // v = x++;
9059 // v = x--;
9060 // v = ++x;
9061 // v = --x;
9062 // v = x binop= expr;
9063 // v = x = x binop expr;
9064 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00009065 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00009066 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9067 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9068 V = AtomicBinOp->getLHS();
9069 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9070 OpenMPAtomicUpdateChecker Checker(*this);
9071 if (Checker.checkStatement(
9072 Body, diag::err_omp_atomic_capture_not_expression_statement,
9073 diag::note_omp_atomic_update))
9074 return StmtError();
9075 E = Checker.getExpr();
9076 X = Checker.getX();
9077 UE = Checker.getUpdateExpr();
9078 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9079 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00009080 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009081 ErrorLoc = AtomicBody->getExprLoc();
9082 ErrorRange = AtomicBody->getSourceRange();
9083 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9084 : AtomicBody->getExprLoc();
9085 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9086 : AtomicBody->getSourceRange();
9087 ErrorFound = NotAnAssignmentOp;
9088 }
9089 if (ErrorFound != NoError) {
9090 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9091 << ErrorRange;
9092 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9093 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009094 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009095 if (CurContext->isDependentContext())
9096 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009097 } else {
9098 // If clause is a capture:
9099 // { v = x; x = expr; }
9100 // { v = x; x++; }
9101 // { v = x; x--; }
9102 // { v = x; ++x; }
9103 // { v = x; --x; }
9104 // { v = x; x binop= expr; }
9105 // { v = x; x = x binop expr; }
9106 // { v = x; x = expr binop x; }
9107 // { x++; v = x; }
9108 // { x--; v = x; }
9109 // { ++x; v = x; }
9110 // { --x; v = x; }
9111 // { x binop= expr; v = x; }
9112 // { x = x binop expr; v = x; }
9113 // { x = expr binop x; v = x; }
9114 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9115 // Check that this is { expr1; expr2; }
9116 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009117 Stmt *First = CS->body_front();
9118 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009119 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9120 First = EWC->getSubExpr()->IgnoreParenImpCasts();
9121 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9122 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9123 // Need to find what subexpression is 'v' and what is 'x'.
9124 OpenMPAtomicUpdateChecker Checker(*this);
9125 bool IsUpdateExprFound = !Checker.checkStatement(Second);
9126 BinaryOperator *BinOp = nullptr;
9127 if (IsUpdateExprFound) {
9128 BinOp = dyn_cast<BinaryOperator>(First);
9129 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9130 }
9131 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9132 // { v = x; x++; }
9133 // { v = x; x--; }
9134 // { v = x; ++x; }
9135 // { v = x; --x; }
9136 // { v = x; x binop= expr; }
9137 // { v = x; x = x binop expr; }
9138 // { v = x; x = expr binop x; }
9139 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009140 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009141 llvm::FoldingSetNodeID XId, PossibleXId;
9142 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9143 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9144 IsUpdateExprFound = XId == PossibleXId;
9145 if (IsUpdateExprFound) {
9146 V = BinOp->getLHS();
9147 X = Checker.getX();
9148 E = Checker.getExpr();
9149 UE = Checker.getUpdateExpr();
9150 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009151 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009152 }
9153 }
9154 if (!IsUpdateExprFound) {
9155 IsUpdateExprFound = !Checker.checkStatement(First);
9156 BinOp = nullptr;
9157 if (IsUpdateExprFound) {
9158 BinOp = dyn_cast<BinaryOperator>(Second);
9159 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9160 }
9161 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9162 // { x++; v = x; }
9163 // { x--; v = x; }
9164 // { ++x; v = x; }
9165 // { --x; v = x; }
9166 // { x binop= expr; v = x; }
9167 // { x = x binop expr; v = x; }
9168 // { x = expr binop x; v = x; }
9169 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009170 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009171 llvm::FoldingSetNodeID XId, PossibleXId;
9172 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9173 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9174 IsUpdateExprFound = XId == PossibleXId;
9175 if (IsUpdateExprFound) {
9176 V = BinOp->getLHS();
9177 X = Checker.getX();
9178 E = Checker.getExpr();
9179 UE = Checker.getUpdateExpr();
9180 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009181 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009182 }
9183 }
9184 }
9185 if (!IsUpdateExprFound) {
9186 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009187 auto *FirstExpr = dyn_cast<Expr>(First);
9188 auto *SecondExpr = dyn_cast<Expr>(Second);
9189 if (!FirstExpr || !SecondExpr ||
9190 !(FirstExpr->isInstantiationDependent() ||
9191 SecondExpr->isInstantiationDependent())) {
9192 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9193 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009194 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009195 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009196 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009197 NoteRange = ErrorRange = FirstBinOp
9198 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009199 : SourceRange(ErrorLoc, ErrorLoc);
9200 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009201 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9202 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9203 ErrorFound = NotAnAssignmentOp;
9204 NoteLoc = ErrorLoc = SecondBinOp
9205 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009206 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009207 NoteRange = ErrorRange =
9208 SecondBinOp ? SecondBinOp->getSourceRange()
9209 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009210 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009211 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009212 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009213 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009214 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9215 llvm::FoldingSetNodeID X1Id, X2Id;
9216 PossibleXRHSInFirst->Profile(X1Id, Context,
9217 /*Canonical=*/true);
9218 PossibleXLHSInSecond->Profile(X2Id, Context,
9219 /*Canonical=*/true);
9220 IsUpdateExprFound = X1Id == X2Id;
9221 if (IsUpdateExprFound) {
9222 V = FirstBinOp->getLHS();
9223 X = SecondBinOp->getLHS();
9224 E = SecondBinOp->getRHS();
9225 UE = nullptr;
9226 IsXLHSInRHSPart = false;
9227 IsPostfixUpdate = true;
9228 } else {
9229 ErrorFound = NotASpecificExpression;
9230 ErrorLoc = FirstBinOp->getExprLoc();
9231 ErrorRange = FirstBinOp->getSourceRange();
9232 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9233 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9234 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009235 }
9236 }
9237 }
9238 }
9239 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009240 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009241 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009242 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009243 ErrorFound = NotTwoSubstatements;
9244 }
9245 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009246 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009247 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009248 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009249 ErrorFound = NotACompoundStatement;
9250 }
9251 if (ErrorFound != NoError) {
9252 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9253 << ErrorRange;
9254 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9255 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009256 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009257 if (CurContext->isDependentContext())
9258 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009259 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009260 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009261
Reid Kleckner87a31802018-03-12 21:43:02 +00009262 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009263
Alexey Bataev62cec442014-11-18 10:14:22 +00009264 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009265 X, V, E, UE, IsXLHSInRHSPart,
9266 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009267}
9268
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009269StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9270 Stmt *AStmt,
9271 SourceLocation StartLoc,
9272 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009273 if (!AStmt)
9274 return StmtError();
9275
Alexey Bataeve3727102018-04-18 15:57:46 +00009276 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009277 // 1.2.2 OpenMP Language Terminology
9278 // Structured block - An executable statement with a single entry at the
9279 // top and a single exit at the bottom.
9280 // The point of exit cannot be a branch out of the structured block.
9281 // longjmp() and throw() must not violate the entry/exit criteria.
9282 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009283 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9284 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9285 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9286 // 1.2.2 OpenMP Language Terminology
9287 // Structured block - An executable statement with a single entry at the
9288 // top and a single exit at the bottom.
9289 // The point of exit cannot be a branch out of the structured block.
9290 // longjmp() and throw() must not violate the entry/exit criteria.
9291 CS->getCapturedDecl()->setNothrow();
9292 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009293
Alexey Bataev13314bf2014-10-09 04:18:56 +00009294 // OpenMP [2.16, Nesting of Regions]
9295 // If specified, a teams construct must be contained within a target
9296 // construct. That target construct must contain no statements or directives
9297 // outside of the teams construct.
9298 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009299 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009300 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009301 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009302 auto I = CS->body_begin();
9303 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009304 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009305 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9306 OMPTeamsFound) {
9307
Alexey Bataev13314bf2014-10-09 04:18:56 +00009308 OMPTeamsFound = false;
9309 break;
9310 }
9311 ++I;
9312 }
9313 assert(I != CS->body_end() && "Not found statement");
9314 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009315 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009316 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009317 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009318 }
9319 if (!OMPTeamsFound) {
9320 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9321 Diag(DSAStack->getInnerTeamsRegionLoc(),
9322 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009323 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009324 << isa<OMPExecutableDirective>(S);
9325 return StmtError();
9326 }
9327 }
9328
Reid Kleckner87a31802018-03-12 21:43:02 +00009329 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009330
9331 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9332}
9333
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009334StmtResult
9335Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9336 Stmt *AStmt, SourceLocation StartLoc,
9337 SourceLocation EndLoc) {
9338 if (!AStmt)
9339 return StmtError();
9340
Alexey Bataeve3727102018-04-18 15:57:46 +00009341 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009342 // 1.2.2 OpenMP Language Terminology
9343 // Structured block - An executable statement with a single entry at the
9344 // top and a single exit at the bottom.
9345 // The point of exit cannot be a branch out of the structured block.
9346 // longjmp() and throw() must not violate the entry/exit criteria.
9347 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009348 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9349 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9350 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9351 // 1.2.2 OpenMP Language Terminology
9352 // Structured block - An executable statement with a single entry at the
9353 // top and a single exit at the bottom.
9354 // The point of exit cannot be a branch out of the structured block.
9355 // longjmp() and throw() must not violate the entry/exit criteria.
9356 CS->getCapturedDecl()->setNothrow();
9357 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009358
Reid Kleckner87a31802018-03-12 21:43:02 +00009359 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009360
9361 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9362 AStmt);
9363}
9364
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009365StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9366 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009367 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009368 if (!AStmt)
9369 return StmtError();
9370
Alexey Bataeve3727102018-04-18 15:57:46 +00009371 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009372 // 1.2.2 OpenMP Language Terminology
9373 // Structured block - An executable statement with a single entry at the
9374 // top and a single exit at the bottom.
9375 // The point of exit cannot be a branch out of the structured block.
9376 // longjmp() and throw() must not violate the entry/exit criteria.
9377 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009378 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9379 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9380 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9381 // 1.2.2 OpenMP Language Terminology
9382 // Structured block - An executable statement with a single entry at the
9383 // top and a single exit at the bottom.
9384 // The point of exit cannot be a branch out of the structured block.
9385 // longjmp() and throw() must not violate the entry/exit criteria.
9386 CS->getCapturedDecl()->setNothrow();
9387 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009388
9389 OMPLoopDirective::HelperExprs B;
9390 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9391 // define the nested loops number.
9392 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009393 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009394 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009395 VarsWithImplicitDSA, B);
9396 if (NestedLoopCount == 0)
9397 return StmtError();
9398
9399 assert((CurContext->isDependentContext() || B.builtAll()) &&
9400 "omp target parallel for loop exprs were not built");
9401
9402 if (!CurContext->isDependentContext()) {
9403 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009404 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009405 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009406 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009407 B.NumIterations, *this, CurScope,
9408 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009409 return StmtError();
9410 }
9411 }
9412
Reid Kleckner87a31802018-03-12 21:43:02 +00009413 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009414 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9415 NestedLoopCount, Clauses, AStmt,
9416 B, DSAStack->isCancelRegion());
9417}
9418
Alexey Bataev95b64a92017-05-30 16:00:04 +00009419/// Check for existence of a map clause in the list of clauses.
9420static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9421 const OpenMPClauseKind K) {
9422 return llvm::any_of(
9423 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9424}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009425
Alexey Bataev95b64a92017-05-30 16:00:04 +00009426template <typename... Params>
9427static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9428 const Params... ClauseTypes) {
9429 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009430}
9431
Michael Wong65f367f2015-07-21 13:44:28 +00009432StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9433 Stmt *AStmt,
9434 SourceLocation StartLoc,
9435 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009436 if (!AStmt)
9437 return StmtError();
9438
9439 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9440
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009441 // OpenMP [2.10.1, Restrictions, p. 97]
9442 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009443 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9444 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9445 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009446 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009447 return StmtError();
9448 }
9449
Reid Kleckner87a31802018-03-12 21:43:02 +00009450 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009451
9452 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9453 AStmt);
9454}
9455
Samuel Antaodf67fc42016-01-19 19:15:56 +00009456StmtResult
9457Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9458 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009459 SourceLocation EndLoc, Stmt *AStmt) {
9460 if (!AStmt)
9461 return StmtError();
9462
Alexey Bataeve3727102018-04-18 15:57:46 +00009463 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009464 // 1.2.2 OpenMP Language Terminology
9465 // Structured block - An executable statement with a single entry at the
9466 // top and a single exit at the bottom.
9467 // The point of exit cannot be a branch out of the structured block.
9468 // longjmp() and throw() must not violate the entry/exit criteria.
9469 CS->getCapturedDecl()->setNothrow();
9470 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9471 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9472 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9473 // 1.2.2 OpenMP Language Terminology
9474 // Structured block - An executable statement with a single entry at the
9475 // top and a single exit at the bottom.
9476 // The point of exit cannot be a branch out of the structured block.
9477 // longjmp() and throw() must not violate the entry/exit criteria.
9478 CS->getCapturedDecl()->setNothrow();
9479 }
9480
Samuel Antaodf67fc42016-01-19 19:15:56 +00009481 // OpenMP [2.10.2, Restrictions, p. 99]
9482 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009483 if (!hasClauses(Clauses, OMPC_map)) {
9484 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9485 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009486 return StmtError();
9487 }
9488
Alexey Bataev7828b252017-11-21 17:08:48 +00009489 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9490 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009491}
9492
Samuel Antao72590762016-01-19 20:04:50 +00009493StmtResult
9494Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9495 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009496 SourceLocation EndLoc, Stmt *AStmt) {
9497 if (!AStmt)
9498 return StmtError();
9499
Alexey Bataeve3727102018-04-18 15:57:46 +00009500 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009501 // 1.2.2 OpenMP Language Terminology
9502 // Structured block - An executable statement with a single entry at the
9503 // top and a single exit at the bottom.
9504 // The point of exit cannot be a branch out of the structured block.
9505 // longjmp() and throw() must not violate the entry/exit criteria.
9506 CS->getCapturedDecl()->setNothrow();
9507 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9508 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9509 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9510 // 1.2.2 OpenMP Language Terminology
9511 // Structured block - An executable statement with a single entry at the
9512 // top and a single exit at the bottom.
9513 // The point of exit cannot be a branch out of the structured block.
9514 // longjmp() and throw() must not violate the entry/exit criteria.
9515 CS->getCapturedDecl()->setNothrow();
9516 }
9517
Samuel Antao72590762016-01-19 20:04:50 +00009518 // OpenMP [2.10.3, Restrictions, p. 102]
9519 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009520 if (!hasClauses(Clauses, OMPC_map)) {
9521 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9522 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009523 return StmtError();
9524 }
9525
Alexey Bataev7828b252017-11-21 17:08:48 +00009526 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9527 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009528}
9529
Samuel Antao686c70c2016-05-26 17:30:50 +00009530StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9531 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009532 SourceLocation EndLoc,
9533 Stmt *AStmt) {
9534 if (!AStmt)
9535 return StmtError();
9536
Alexey Bataeve3727102018-04-18 15:57:46 +00009537 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009538 // 1.2.2 OpenMP Language Terminology
9539 // Structured block - An executable statement with a single entry at the
9540 // top and a single exit at the bottom.
9541 // The point of exit cannot be a branch out of the structured block.
9542 // longjmp() and throw() must not violate the entry/exit criteria.
9543 CS->getCapturedDecl()->setNothrow();
9544 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9545 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9546 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9547 // 1.2.2 OpenMP Language Terminology
9548 // Structured block - An executable statement with a single entry at the
9549 // top and a single exit at the bottom.
9550 // The point of exit cannot be a branch out of the structured block.
9551 // longjmp() and throw() must not violate the entry/exit criteria.
9552 CS->getCapturedDecl()->setNothrow();
9553 }
9554
Alexey Bataev95b64a92017-05-30 16:00:04 +00009555 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009556 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9557 return StmtError();
9558 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009559 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9560 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009561}
9562
Alexey Bataev13314bf2014-10-09 04:18:56 +00009563StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9564 Stmt *AStmt, SourceLocation StartLoc,
9565 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009566 if (!AStmt)
9567 return StmtError();
9568
Alexey Bataeve3727102018-04-18 15:57:46 +00009569 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009570 // 1.2.2 OpenMP Language Terminology
9571 // Structured block - An executable statement with a single entry at the
9572 // top and a single exit at the bottom.
9573 // The point of exit cannot be a branch out of the structured block.
9574 // longjmp() and throw() must not violate the entry/exit criteria.
9575 CS->getCapturedDecl()->setNothrow();
9576
Reid Kleckner87a31802018-03-12 21:43:02 +00009577 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009578
Alexey Bataevceabd412017-11-30 18:01:54 +00009579 DSAStack->setParentTeamsRegionLoc(StartLoc);
9580
Alexey Bataev13314bf2014-10-09 04:18:56 +00009581 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9582}
9583
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009584StmtResult
9585Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9586 SourceLocation EndLoc,
9587 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009588 if (DSAStack->isParentNowaitRegion()) {
9589 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9590 return StmtError();
9591 }
9592 if (DSAStack->isParentOrderedRegion()) {
9593 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9594 return StmtError();
9595 }
9596 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9597 CancelRegion);
9598}
9599
Alexey Bataev87933c72015-09-18 08:07:34 +00009600StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9601 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009602 SourceLocation EndLoc,
9603 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009604 if (DSAStack->isParentNowaitRegion()) {
9605 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9606 return StmtError();
9607 }
9608 if (DSAStack->isParentOrderedRegion()) {
9609 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9610 return StmtError();
9611 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009612 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009613 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9614 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009615}
9616
Alexey Bataev382967a2015-12-08 12:06:20 +00009617static bool checkGrainsizeNumTasksClauses(Sema &S,
9618 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009619 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009620 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009621 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009622 if (C->getClauseKind() == OMPC_grainsize ||
9623 C->getClauseKind() == OMPC_num_tasks) {
9624 if (!PrevClause)
9625 PrevClause = C;
9626 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009627 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009628 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9629 << getOpenMPClauseName(C->getClauseKind())
9630 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009631 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009632 diag::note_omp_previous_grainsize_num_tasks)
9633 << getOpenMPClauseName(PrevClause->getClauseKind());
9634 ErrorFound = true;
9635 }
9636 }
9637 }
9638 return ErrorFound;
9639}
9640
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009641static bool checkReductionClauseWithNogroup(Sema &S,
9642 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009643 const OMPClause *ReductionClause = nullptr;
9644 const OMPClause *NogroupClause = nullptr;
9645 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009646 if (C->getClauseKind() == OMPC_reduction) {
9647 ReductionClause = C;
9648 if (NogroupClause)
9649 break;
9650 continue;
9651 }
9652 if (C->getClauseKind() == OMPC_nogroup) {
9653 NogroupClause = C;
9654 if (ReductionClause)
9655 break;
9656 continue;
9657 }
9658 }
9659 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009660 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9661 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009662 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009663 return true;
9664 }
9665 return false;
9666}
9667
Alexey Bataev49f6e782015-12-01 04:18:41 +00009668StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9669 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009670 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009671 if (!AStmt)
9672 return StmtError();
9673
9674 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9675 OMPLoopDirective::HelperExprs B;
9676 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9677 // define the nested loops number.
9678 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009679 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009680 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009681 VarsWithImplicitDSA, B);
9682 if (NestedLoopCount == 0)
9683 return StmtError();
9684
9685 assert((CurContext->isDependentContext() || B.builtAll()) &&
9686 "omp for loop exprs were not built");
9687
Alexey Bataev382967a2015-12-08 12:06:20 +00009688 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9689 // The grainsize clause and num_tasks clause are mutually exclusive and may
9690 // not appear on the same taskloop directive.
9691 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9692 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009693 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9694 // If a reduction clause is present on the taskloop directive, the nogroup
9695 // clause must not be specified.
9696 if (checkReductionClauseWithNogroup(*this, Clauses))
9697 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009698
Reid Kleckner87a31802018-03-12 21:43:02 +00009699 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009700 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9701 NestedLoopCount, Clauses, AStmt, B);
9702}
9703
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009704StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9705 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009706 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009707 if (!AStmt)
9708 return StmtError();
9709
9710 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9711 OMPLoopDirective::HelperExprs B;
9712 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9713 // define the nested loops number.
9714 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009715 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009716 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9717 VarsWithImplicitDSA, B);
9718 if (NestedLoopCount == 0)
9719 return StmtError();
9720
9721 assert((CurContext->isDependentContext() || B.builtAll()) &&
9722 "omp for loop exprs were not built");
9723
Alexey Bataev5a3af132016-03-29 08:58:54 +00009724 if (!CurContext->isDependentContext()) {
9725 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009726 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009727 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009728 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009729 B.NumIterations, *this, CurScope,
9730 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009731 return StmtError();
9732 }
9733 }
9734
Alexey Bataev382967a2015-12-08 12:06:20 +00009735 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9736 // The grainsize clause and num_tasks clause are mutually exclusive and may
9737 // not appear on the same taskloop directive.
9738 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9739 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009740 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9741 // If a reduction clause is present on the taskloop directive, the nogroup
9742 // clause must not be specified.
9743 if (checkReductionClauseWithNogroup(*this, Clauses))
9744 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009745 if (checkSimdlenSafelenSpecified(*this, Clauses))
9746 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009747
Reid Kleckner87a31802018-03-12 21:43:02 +00009748 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009749 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9750 NestedLoopCount, Clauses, AStmt, B);
9751}
9752
Alexey Bataev60e51c42019-10-10 20:13:02 +00009753StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9754 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9755 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9756 if (!AStmt)
9757 return StmtError();
9758
9759 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9760 OMPLoopDirective::HelperExprs B;
9761 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9762 // define the nested loops number.
9763 unsigned NestedLoopCount =
9764 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9765 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9766 VarsWithImplicitDSA, B);
9767 if (NestedLoopCount == 0)
9768 return StmtError();
9769
9770 assert((CurContext->isDependentContext() || B.builtAll()) &&
9771 "omp for loop exprs were not built");
9772
9773 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9774 // The grainsize clause and num_tasks clause are mutually exclusive and may
9775 // not appear on the same taskloop directive.
9776 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9777 return StmtError();
9778 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9779 // If a reduction clause is present on the taskloop directive, the nogroup
9780 // clause must not be specified.
9781 if (checkReductionClauseWithNogroup(*this, Clauses))
9782 return StmtError();
9783
9784 setFunctionHasBranchProtectedScope();
9785 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9786 NestedLoopCount, Clauses, AStmt, B);
9787}
9788
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009789StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9790 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9791 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9792 if (!AStmt)
9793 return StmtError();
9794
9795 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9796 OMPLoopDirective::HelperExprs B;
9797 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9798 // define the nested loops number.
9799 unsigned NestedLoopCount =
9800 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9801 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9802 VarsWithImplicitDSA, B);
9803 if (NestedLoopCount == 0)
9804 return StmtError();
9805
9806 assert((CurContext->isDependentContext() || B.builtAll()) &&
9807 "omp for loop exprs were not built");
9808
9809 if (!CurContext->isDependentContext()) {
9810 // Finalize the clauses that need pre-built expressions for CodeGen.
9811 for (OMPClause *C : Clauses) {
9812 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9813 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9814 B.NumIterations, *this, CurScope,
9815 DSAStack))
9816 return StmtError();
9817 }
9818 }
9819
9820 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9821 // The grainsize clause and num_tasks clause are mutually exclusive and may
9822 // not appear on the same taskloop directive.
9823 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9824 return StmtError();
9825 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9826 // If a reduction clause is present on the taskloop directive, the nogroup
9827 // clause must not be specified.
9828 if (checkReductionClauseWithNogroup(*this, Clauses))
9829 return StmtError();
9830 if (checkSimdlenSafelenSpecified(*this, Clauses))
9831 return StmtError();
9832
9833 setFunctionHasBranchProtectedScope();
9834 return OMPMasterTaskLoopSimdDirective::Create(
9835 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9836}
9837
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009838StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9839 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9840 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9841 if (!AStmt)
9842 return StmtError();
9843
9844 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9845 auto *CS = cast<CapturedStmt>(AStmt);
9846 // 1.2.2 OpenMP Language Terminology
9847 // Structured block - An executable statement with a single entry at the
9848 // top and a single exit at the bottom.
9849 // The point of exit cannot be a branch out of the structured block.
9850 // longjmp() and throw() must not violate the entry/exit criteria.
9851 CS->getCapturedDecl()->setNothrow();
9852 for (int ThisCaptureLevel =
9853 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9854 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9855 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9856 // 1.2.2 OpenMP Language Terminology
9857 // Structured block - An executable statement with a single entry at the
9858 // top and a single exit at the bottom.
9859 // The point of exit cannot be a branch out of the structured block.
9860 // longjmp() and throw() must not violate the entry/exit criteria.
9861 CS->getCapturedDecl()->setNothrow();
9862 }
9863
9864 OMPLoopDirective::HelperExprs B;
9865 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9866 // define the nested loops number.
9867 unsigned NestedLoopCount = checkOpenMPLoop(
9868 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9869 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9870 VarsWithImplicitDSA, B);
9871 if (NestedLoopCount == 0)
9872 return StmtError();
9873
9874 assert((CurContext->isDependentContext() || B.builtAll()) &&
9875 "omp for loop exprs were not built");
9876
9877 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9878 // The grainsize clause and num_tasks clause are mutually exclusive and may
9879 // not appear on the same taskloop directive.
9880 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9881 return StmtError();
9882 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9883 // If a reduction clause is present on the taskloop directive, the nogroup
9884 // clause must not be specified.
9885 if (checkReductionClauseWithNogroup(*this, Clauses))
9886 return StmtError();
9887
9888 setFunctionHasBranchProtectedScope();
9889 return OMPParallelMasterTaskLoopDirective::Create(
9890 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9891}
9892
Alexey Bataev14a388f2019-10-25 10:27:13 -04009893StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9894 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9895 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9896 if (!AStmt)
9897 return StmtError();
9898
9899 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9900 auto *CS = cast<CapturedStmt>(AStmt);
9901 // 1.2.2 OpenMP Language Terminology
9902 // Structured block - An executable statement with a single entry at the
9903 // top and a single exit at the bottom.
9904 // The point of exit cannot be a branch out of the structured block.
9905 // longjmp() and throw() must not violate the entry/exit criteria.
9906 CS->getCapturedDecl()->setNothrow();
9907 for (int ThisCaptureLevel =
9908 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
9909 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9910 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9911 // 1.2.2 OpenMP Language Terminology
9912 // Structured block - An executable statement with a single entry at the
9913 // top and a single exit at the bottom.
9914 // The point of exit cannot be a branch out of the structured block.
9915 // longjmp() and throw() must not violate the entry/exit criteria.
9916 CS->getCapturedDecl()->setNothrow();
9917 }
9918
9919 OMPLoopDirective::HelperExprs B;
9920 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9921 // define the nested loops number.
9922 unsigned NestedLoopCount = checkOpenMPLoop(
9923 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9924 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9925 VarsWithImplicitDSA, B);
9926 if (NestedLoopCount == 0)
9927 return StmtError();
9928
9929 assert((CurContext->isDependentContext() || B.builtAll()) &&
9930 "omp for loop exprs were not built");
9931
9932 if (!CurContext->isDependentContext()) {
9933 // Finalize the clauses that need pre-built expressions for CodeGen.
9934 for (OMPClause *C : Clauses) {
9935 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9936 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9937 B.NumIterations, *this, CurScope,
9938 DSAStack))
9939 return StmtError();
9940 }
9941 }
9942
9943 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9944 // The grainsize clause and num_tasks clause are mutually exclusive and may
9945 // not appear on the same taskloop directive.
9946 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9947 return StmtError();
9948 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9949 // If a reduction clause is present on the taskloop directive, the nogroup
9950 // clause must not be specified.
9951 if (checkReductionClauseWithNogroup(*this, Clauses))
9952 return StmtError();
9953 if (checkSimdlenSafelenSpecified(*this, Clauses))
9954 return StmtError();
9955
9956 setFunctionHasBranchProtectedScope();
9957 return OMPParallelMasterTaskLoopSimdDirective::Create(
9958 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9959}
9960
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009961StmtResult Sema::ActOnOpenMPDistributeDirective(
9962 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009963 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009964 if (!AStmt)
9965 return StmtError();
9966
9967 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9968 OMPLoopDirective::HelperExprs B;
9969 // In presence of clause 'collapse' with number of loops, it will
9970 // define the nested loops number.
9971 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009972 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009973 nullptr /*ordered not a clause on distribute*/, AStmt,
9974 *this, *DSAStack, VarsWithImplicitDSA, B);
9975 if (NestedLoopCount == 0)
9976 return StmtError();
9977
9978 assert((CurContext->isDependentContext() || B.builtAll()) &&
9979 "omp for loop exprs were not built");
9980
Reid Kleckner87a31802018-03-12 21:43:02 +00009981 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009982 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9983 NestedLoopCount, Clauses, AStmt, B);
9984}
9985
Carlo Bertolli9925f152016-06-27 14:55:37 +00009986StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9987 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009988 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009989 if (!AStmt)
9990 return StmtError();
9991
Alexey Bataeve3727102018-04-18 15:57:46 +00009992 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009993 // 1.2.2 OpenMP Language Terminology
9994 // Structured block - An executable statement with a single entry at the
9995 // top and a single exit at the bottom.
9996 // The point of exit cannot be a branch out of the structured block.
9997 // longjmp() and throw() must not violate the entry/exit criteria.
9998 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009999 for (int ThisCaptureLevel =
10000 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
10001 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10002 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10003 // 1.2.2 OpenMP Language Terminology
10004 // Structured block - An executable statement with a single entry at the
10005 // top and a single exit at the bottom.
10006 // The point of exit cannot be a branch out of the structured block.
10007 // longjmp() and throw() must not violate the entry/exit criteria.
10008 CS->getCapturedDecl()->setNothrow();
10009 }
Carlo Bertolli9925f152016-06-27 14:55:37 +000010010
10011 OMPLoopDirective::HelperExprs B;
10012 // In presence of clause 'collapse' with number of loops, it will
10013 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010014 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +000010015 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +000010016 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +000010017 VarsWithImplicitDSA, B);
10018 if (NestedLoopCount == 0)
10019 return StmtError();
10020
10021 assert((CurContext->isDependentContext() || B.builtAll()) &&
10022 "omp for loop exprs were not built");
10023
Reid Kleckner87a31802018-03-12 21:43:02 +000010024 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +000010025 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010026 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10027 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +000010028}
10029
Kelvin Li4a39add2016-07-05 05:00:15 +000010030StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
10031 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010032 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +000010033 if (!AStmt)
10034 return StmtError();
10035
Alexey Bataeve3727102018-04-18 15:57:46 +000010036 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +000010037 // 1.2.2 OpenMP Language Terminology
10038 // Structured block - An executable statement with a single entry at the
10039 // top and a single exit at the bottom.
10040 // The point of exit cannot be a branch out of the structured block.
10041 // longjmp() and throw() must not violate the entry/exit criteria.
10042 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +000010043 for (int ThisCaptureLevel =
10044 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
10045 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10046 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10047 // 1.2.2 OpenMP Language Terminology
10048 // Structured block - An executable statement with a single entry at the
10049 // top and a single exit at the bottom.
10050 // The point of exit cannot be a branch out of the structured block.
10051 // longjmp() and throw() must not violate the entry/exit criteria.
10052 CS->getCapturedDecl()->setNothrow();
10053 }
Kelvin Li4a39add2016-07-05 05:00:15 +000010054
10055 OMPLoopDirective::HelperExprs B;
10056 // In presence of clause 'collapse' with number of loops, it will
10057 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010058 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +000010059 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +000010060 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +000010061 VarsWithImplicitDSA, B);
10062 if (NestedLoopCount == 0)
10063 return StmtError();
10064
10065 assert((CurContext->isDependentContext() || B.builtAll()) &&
10066 "omp for loop exprs were not built");
10067
Alexey Bataev438388c2017-11-22 18:34:02 +000010068 if (!CurContext->isDependentContext()) {
10069 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010070 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010071 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10072 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10073 B.NumIterations, *this, CurScope,
10074 DSAStack))
10075 return StmtError();
10076 }
10077 }
10078
Kelvin Lic5609492016-07-15 04:39:07 +000010079 if (checkSimdlenSafelenSpecified(*this, Clauses))
10080 return StmtError();
10081
Reid Kleckner87a31802018-03-12 21:43:02 +000010082 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +000010083 return OMPDistributeParallelForSimdDirective::Create(
10084 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10085}
10086
Kelvin Li787f3fc2016-07-06 04:45:38 +000010087StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10088 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010089 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +000010090 if (!AStmt)
10091 return StmtError();
10092
Alexey Bataeve3727102018-04-18 15:57:46 +000010093 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010094 // 1.2.2 OpenMP Language Terminology
10095 // Structured block - An executable statement with a single entry at the
10096 // top and a single exit at the bottom.
10097 // The point of exit cannot be a branch out of the structured block.
10098 // longjmp() and throw() must not violate the entry/exit criteria.
10099 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +000010100 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10101 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10102 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10103 // 1.2.2 OpenMP Language Terminology
10104 // Structured block - An executable statement with a single entry at the
10105 // top and a single exit at the bottom.
10106 // The point of exit cannot be a branch out of the structured block.
10107 // longjmp() and throw() must not violate the entry/exit criteria.
10108 CS->getCapturedDecl()->setNothrow();
10109 }
Kelvin Li787f3fc2016-07-06 04:45:38 +000010110
10111 OMPLoopDirective::HelperExprs B;
10112 // In presence of clause 'collapse' with number of loops, it will
10113 // define the nested loops number.
10114 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010115 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +000010116 nullptr /*ordered not a clause on distribute*/, CS, *this,
10117 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010118 if (NestedLoopCount == 0)
10119 return StmtError();
10120
10121 assert((CurContext->isDependentContext() || B.builtAll()) &&
10122 "omp for loop exprs were not built");
10123
Alexey Bataev438388c2017-11-22 18:34:02 +000010124 if (!CurContext->isDependentContext()) {
10125 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010126 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010127 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10128 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10129 B.NumIterations, *this, CurScope,
10130 DSAStack))
10131 return StmtError();
10132 }
10133 }
10134
Kelvin Lic5609492016-07-15 04:39:07 +000010135 if (checkSimdlenSafelenSpecified(*this, Clauses))
10136 return StmtError();
10137
Reid Kleckner87a31802018-03-12 21:43:02 +000010138 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +000010139 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
10140 NestedLoopCount, Clauses, AStmt, B);
10141}
10142
Kelvin Lia579b912016-07-14 02:54:56 +000010143StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
10144 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010145 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +000010146 if (!AStmt)
10147 return StmtError();
10148
Alexey Bataeve3727102018-04-18 15:57:46 +000010149 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +000010150 // 1.2.2 OpenMP Language Terminology
10151 // Structured block - An executable statement with a single entry at the
10152 // top and a single exit at the bottom.
10153 // The point of exit cannot be a branch out of the structured block.
10154 // longjmp() and throw() must not violate the entry/exit criteria.
10155 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010156 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10157 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10158 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10159 // 1.2.2 OpenMP Language Terminology
10160 // Structured block - An executable statement with a single entry at the
10161 // top and a single exit at the bottom.
10162 // The point of exit cannot be a branch out of the structured block.
10163 // longjmp() and throw() must not violate the entry/exit criteria.
10164 CS->getCapturedDecl()->setNothrow();
10165 }
Kelvin Lia579b912016-07-14 02:54:56 +000010166
10167 OMPLoopDirective::HelperExprs B;
10168 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10169 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010170 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010171 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010172 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010173 VarsWithImplicitDSA, B);
10174 if (NestedLoopCount == 0)
10175 return StmtError();
10176
10177 assert((CurContext->isDependentContext() || B.builtAll()) &&
10178 "omp target parallel for simd loop exprs were not built");
10179
10180 if (!CurContext->isDependentContext()) {
10181 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010182 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010183 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010184 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10185 B.NumIterations, *this, CurScope,
10186 DSAStack))
10187 return StmtError();
10188 }
10189 }
Kelvin Lic5609492016-07-15 04:39:07 +000010190 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010191 return StmtError();
10192
Reid Kleckner87a31802018-03-12 21:43:02 +000010193 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010194 return OMPTargetParallelForSimdDirective::Create(
10195 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10196}
10197
Kelvin Li986330c2016-07-20 22:57:10 +000010198StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10199 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010200 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010201 if (!AStmt)
10202 return StmtError();
10203
Alexey Bataeve3727102018-04-18 15:57:46 +000010204 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010205 // 1.2.2 OpenMP Language Terminology
10206 // Structured block - An executable statement with a single entry at the
10207 // top and a single exit at the bottom.
10208 // The point of exit cannot be a branch out of the structured block.
10209 // longjmp() and throw() must not violate the entry/exit criteria.
10210 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010211 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10212 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10213 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10214 // 1.2.2 OpenMP Language Terminology
10215 // Structured block - An executable statement with a single entry at the
10216 // top and a single exit at the bottom.
10217 // The point of exit cannot be a branch out of the structured block.
10218 // longjmp() and throw() must not violate the entry/exit criteria.
10219 CS->getCapturedDecl()->setNothrow();
10220 }
10221
Kelvin Li986330c2016-07-20 22:57:10 +000010222 OMPLoopDirective::HelperExprs B;
10223 // In presence of clause 'collapse' with number of loops, it will define the
10224 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010225 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010226 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010227 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010228 VarsWithImplicitDSA, B);
10229 if (NestedLoopCount == 0)
10230 return StmtError();
10231
10232 assert((CurContext->isDependentContext() || B.builtAll()) &&
10233 "omp target simd loop exprs were not built");
10234
10235 if (!CurContext->isDependentContext()) {
10236 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010237 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010238 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010239 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10240 B.NumIterations, *this, CurScope,
10241 DSAStack))
10242 return StmtError();
10243 }
10244 }
10245
10246 if (checkSimdlenSafelenSpecified(*this, Clauses))
10247 return StmtError();
10248
Reid Kleckner87a31802018-03-12 21:43:02 +000010249 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010250 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10251 NestedLoopCount, Clauses, AStmt, B);
10252}
10253
Kelvin Li02532872016-08-05 14:37:37 +000010254StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10255 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010256 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010257 if (!AStmt)
10258 return StmtError();
10259
Alexey Bataeve3727102018-04-18 15:57:46 +000010260 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +000010261 // 1.2.2 OpenMP Language Terminology
10262 // Structured block - An executable statement with a single entry at the
10263 // top and a single exit at the bottom.
10264 // The point of exit cannot be a branch out of the structured block.
10265 // longjmp() and throw() must not violate the entry/exit criteria.
10266 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010267 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10268 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10269 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10270 // 1.2.2 OpenMP Language Terminology
10271 // Structured block - An executable statement with a single entry at the
10272 // top and a single exit at the bottom.
10273 // The point of exit cannot be a branch out of the structured block.
10274 // longjmp() and throw() must not violate the entry/exit criteria.
10275 CS->getCapturedDecl()->setNothrow();
10276 }
Kelvin Li02532872016-08-05 14:37:37 +000010277
10278 OMPLoopDirective::HelperExprs B;
10279 // In presence of clause 'collapse' with number of loops, it will
10280 // define the nested loops number.
10281 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010282 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010283 nullptr /*ordered not a clause on distribute*/, CS, *this,
10284 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010285 if (NestedLoopCount == 0)
10286 return StmtError();
10287
10288 assert((CurContext->isDependentContext() || B.builtAll()) &&
10289 "omp teams distribute loop exprs were not built");
10290
Reid Kleckner87a31802018-03-12 21:43:02 +000010291 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010292
10293 DSAStack->setParentTeamsRegionLoc(StartLoc);
10294
David Majnemer9d168222016-08-05 17:44:54 +000010295 return OMPTeamsDistributeDirective::Create(
10296 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010297}
10298
Kelvin Li4e325f72016-10-25 12:50:55 +000010299StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10300 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010301 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010302 if (!AStmt)
10303 return StmtError();
10304
Alexey Bataeve3727102018-04-18 15:57:46 +000010305 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010306 // 1.2.2 OpenMP Language Terminology
10307 // Structured block - An executable statement with a single entry at the
10308 // top and a single exit at the bottom.
10309 // The point of exit cannot be a branch out of the structured block.
10310 // longjmp() and throw() must not violate the entry/exit criteria.
10311 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010312 for (int ThisCaptureLevel =
10313 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10314 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10315 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10316 // 1.2.2 OpenMP Language Terminology
10317 // Structured block - An executable statement with a single entry at the
10318 // top and a single exit at the bottom.
10319 // The point of exit cannot be a branch out of the structured block.
10320 // longjmp() and throw() must not violate the entry/exit criteria.
10321 CS->getCapturedDecl()->setNothrow();
10322 }
10323
Kelvin Li4e325f72016-10-25 12:50:55 +000010324
10325 OMPLoopDirective::HelperExprs B;
10326 // In presence of clause 'collapse' with number of loops, it will
10327 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010328 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010329 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010330 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010331 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010332
10333 if (NestedLoopCount == 0)
10334 return StmtError();
10335
10336 assert((CurContext->isDependentContext() || B.builtAll()) &&
10337 "omp teams distribute simd loop exprs were not built");
10338
10339 if (!CurContext->isDependentContext()) {
10340 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010341 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010342 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10343 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10344 B.NumIterations, *this, CurScope,
10345 DSAStack))
10346 return StmtError();
10347 }
10348 }
10349
10350 if (checkSimdlenSafelenSpecified(*this, Clauses))
10351 return StmtError();
10352
Reid Kleckner87a31802018-03-12 21:43:02 +000010353 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010354
10355 DSAStack->setParentTeamsRegionLoc(StartLoc);
10356
Kelvin Li4e325f72016-10-25 12:50:55 +000010357 return OMPTeamsDistributeSimdDirective::Create(
10358 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10359}
10360
Kelvin Li579e41c2016-11-30 23:51:03 +000010361StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10362 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010363 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010364 if (!AStmt)
10365 return StmtError();
10366
Alexey Bataeve3727102018-04-18 15:57:46 +000010367 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010368 // 1.2.2 OpenMP Language Terminology
10369 // Structured block - An executable statement with a single entry at the
10370 // top and a single exit at the bottom.
10371 // The point of exit cannot be a branch out of the structured block.
10372 // longjmp() and throw() must not violate the entry/exit criteria.
10373 CS->getCapturedDecl()->setNothrow();
10374
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010375 for (int ThisCaptureLevel =
10376 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10377 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10378 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10379 // 1.2.2 OpenMP Language Terminology
10380 // Structured block - An executable statement with a single entry at the
10381 // top and a single exit at the bottom.
10382 // The point of exit cannot be a branch out of the structured block.
10383 // longjmp() and throw() must not violate the entry/exit criteria.
10384 CS->getCapturedDecl()->setNothrow();
10385 }
10386
Kelvin Li579e41c2016-11-30 23:51:03 +000010387 OMPLoopDirective::HelperExprs B;
10388 // In presence of clause 'collapse' with number of loops, it will
10389 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010390 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010391 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010392 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010393 VarsWithImplicitDSA, B);
10394
10395 if (NestedLoopCount == 0)
10396 return StmtError();
10397
10398 assert((CurContext->isDependentContext() || B.builtAll()) &&
10399 "omp for loop exprs were not built");
10400
10401 if (!CurContext->isDependentContext()) {
10402 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010403 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010404 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10405 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10406 B.NumIterations, *this, CurScope,
10407 DSAStack))
10408 return StmtError();
10409 }
10410 }
10411
10412 if (checkSimdlenSafelenSpecified(*this, Clauses))
10413 return StmtError();
10414
Reid Kleckner87a31802018-03-12 21:43:02 +000010415 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010416
10417 DSAStack->setParentTeamsRegionLoc(StartLoc);
10418
Kelvin Li579e41c2016-11-30 23:51:03 +000010419 return OMPTeamsDistributeParallelForSimdDirective::Create(
10420 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10421}
10422
Kelvin Li7ade93f2016-12-09 03:24:30 +000010423StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10424 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010425 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010426 if (!AStmt)
10427 return StmtError();
10428
Alexey Bataeve3727102018-04-18 15:57:46 +000010429 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010430 // 1.2.2 OpenMP Language Terminology
10431 // Structured block - An executable statement with a single entry at the
10432 // top and a single exit at the bottom.
10433 // The point of exit cannot be a branch out of the structured block.
10434 // longjmp() and throw() must not violate the entry/exit criteria.
10435 CS->getCapturedDecl()->setNothrow();
10436
Carlo Bertolli62fae152017-11-20 20:46:39 +000010437 for (int ThisCaptureLevel =
10438 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10439 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10440 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10441 // 1.2.2 OpenMP Language Terminology
10442 // Structured block - An executable statement with a single entry at the
10443 // top and a single exit at the bottom.
10444 // The point of exit cannot be a branch out of the structured block.
10445 // longjmp() and throw() must not violate the entry/exit criteria.
10446 CS->getCapturedDecl()->setNothrow();
10447 }
10448
Kelvin Li7ade93f2016-12-09 03:24:30 +000010449 OMPLoopDirective::HelperExprs B;
10450 // In presence of clause 'collapse' with number of loops, it will
10451 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010452 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010453 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010454 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010455 VarsWithImplicitDSA, B);
10456
10457 if (NestedLoopCount == 0)
10458 return StmtError();
10459
10460 assert((CurContext->isDependentContext() || B.builtAll()) &&
10461 "omp for loop exprs were not built");
10462
Reid Kleckner87a31802018-03-12 21:43:02 +000010463 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010464
10465 DSAStack->setParentTeamsRegionLoc(StartLoc);
10466
Kelvin Li7ade93f2016-12-09 03:24:30 +000010467 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010468 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10469 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010470}
10471
Kelvin Libf594a52016-12-17 05:48:59 +000010472StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10473 Stmt *AStmt,
10474 SourceLocation StartLoc,
10475 SourceLocation EndLoc) {
10476 if (!AStmt)
10477 return StmtError();
10478
Alexey Bataeve3727102018-04-18 15:57:46 +000010479 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010480 // 1.2.2 OpenMP Language Terminology
10481 // Structured block - An executable statement with a single entry at the
10482 // top and a single exit at the bottom.
10483 // The point of exit cannot be a branch out of the structured block.
10484 // longjmp() and throw() must not violate the entry/exit criteria.
10485 CS->getCapturedDecl()->setNothrow();
10486
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010487 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10488 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10489 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10490 // 1.2.2 OpenMP Language Terminology
10491 // Structured block - An executable statement with a single entry at the
10492 // top and a single exit at the bottom.
10493 // The point of exit cannot be a branch out of the structured block.
10494 // longjmp() and throw() must not violate the entry/exit criteria.
10495 CS->getCapturedDecl()->setNothrow();
10496 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010497 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010498
10499 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10500 AStmt);
10501}
10502
Kelvin Li83c451e2016-12-25 04:52:54 +000010503StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10504 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010505 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010506 if (!AStmt)
10507 return StmtError();
10508
Alexey Bataeve3727102018-04-18 15:57:46 +000010509 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010510 // 1.2.2 OpenMP Language Terminology
10511 // Structured block - An executable statement with a single entry at the
10512 // top and a single exit at the bottom.
10513 // The point of exit cannot be a branch out of the structured block.
10514 // longjmp() and throw() must not violate the entry/exit criteria.
10515 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010516 for (int ThisCaptureLevel =
10517 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10518 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10519 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10520 // 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 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010527
10528 OMPLoopDirective::HelperExprs B;
10529 // In presence of clause 'collapse' with number of loops, it will
10530 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010531 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010532 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10533 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010534 VarsWithImplicitDSA, B);
10535 if (NestedLoopCount == 0)
10536 return StmtError();
10537
10538 assert((CurContext->isDependentContext() || B.builtAll()) &&
10539 "omp target teams distribute loop exprs were not built");
10540
Reid Kleckner87a31802018-03-12 21:43:02 +000010541 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010542 return OMPTargetTeamsDistributeDirective::Create(
10543 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10544}
10545
Kelvin Li80e8f562016-12-29 22:16:30 +000010546StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10547 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010548 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010549 if (!AStmt)
10550 return StmtError();
10551
Alexey Bataeve3727102018-04-18 15:57:46 +000010552 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010553 // 1.2.2 OpenMP Language Terminology
10554 // Structured block - An executable statement with a single entry at the
10555 // top and a single exit at the bottom.
10556 // The point of exit cannot be a branch out of the structured block.
10557 // longjmp() and throw() must not violate the entry/exit criteria.
10558 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010559 for (int ThisCaptureLevel =
10560 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10561 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10562 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10563 // 1.2.2 OpenMP Language Terminology
10564 // Structured block - An executable statement with a single entry at the
10565 // top and a single exit at the bottom.
10566 // The point of exit cannot be a branch out of the structured block.
10567 // longjmp() and throw() must not violate the entry/exit criteria.
10568 CS->getCapturedDecl()->setNothrow();
10569 }
10570
Kelvin Li80e8f562016-12-29 22:16:30 +000010571 OMPLoopDirective::HelperExprs B;
10572 // In presence of clause 'collapse' with number of loops, it will
10573 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010574 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010575 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10576 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010577 VarsWithImplicitDSA, B);
10578 if (NestedLoopCount == 0)
10579 return StmtError();
10580
10581 assert((CurContext->isDependentContext() || B.builtAll()) &&
10582 "omp target teams distribute parallel for loop exprs were not built");
10583
Alexey Bataev647dd842018-01-15 20:59:40 +000010584 if (!CurContext->isDependentContext()) {
10585 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010586 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010587 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10588 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10589 B.NumIterations, *this, CurScope,
10590 DSAStack))
10591 return StmtError();
10592 }
10593 }
10594
Reid Kleckner87a31802018-03-12 21:43:02 +000010595 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010596 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010597 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10598 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010599}
10600
Kelvin Li1851df52017-01-03 05:23:48 +000010601StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10602 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010603 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010604 if (!AStmt)
10605 return StmtError();
10606
Alexey Bataeve3727102018-04-18 15:57:46 +000010607 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010608 // 1.2.2 OpenMP Language Terminology
10609 // Structured block - An executable statement with a single entry at the
10610 // top and a single exit at the bottom.
10611 // The point of exit cannot be a branch out of the structured block.
10612 // longjmp() and throw() must not violate the entry/exit criteria.
10613 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010614 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10615 OMPD_target_teams_distribute_parallel_for_simd);
10616 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10617 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10618 // 1.2.2 OpenMP Language Terminology
10619 // Structured block - An executable statement with a single entry at the
10620 // top and a single exit at the bottom.
10621 // The point of exit cannot be a branch out of the structured block.
10622 // longjmp() and throw() must not violate the entry/exit criteria.
10623 CS->getCapturedDecl()->setNothrow();
10624 }
Kelvin Li1851df52017-01-03 05:23:48 +000010625
10626 OMPLoopDirective::HelperExprs B;
10627 // In presence of clause 'collapse' with number of loops, it will
10628 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010629 unsigned NestedLoopCount =
10630 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010631 getCollapseNumberExpr(Clauses),
10632 nullptr /*ordered not a clause on distribute*/, CS, *this,
10633 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010634 if (NestedLoopCount == 0)
10635 return StmtError();
10636
10637 assert((CurContext->isDependentContext() || B.builtAll()) &&
10638 "omp target teams distribute parallel for simd loop exprs were not "
10639 "built");
10640
10641 if (!CurContext->isDependentContext()) {
10642 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010643 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010644 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10645 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10646 B.NumIterations, *this, CurScope,
10647 DSAStack))
10648 return StmtError();
10649 }
10650 }
10651
Alexey Bataev438388c2017-11-22 18:34:02 +000010652 if (checkSimdlenSafelenSpecified(*this, Clauses))
10653 return StmtError();
10654
Reid Kleckner87a31802018-03-12 21:43:02 +000010655 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010656 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10657 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10658}
10659
Kelvin Lida681182017-01-10 18:08:18 +000010660StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10661 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010662 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010663 if (!AStmt)
10664 return StmtError();
10665
10666 auto *CS = cast<CapturedStmt>(AStmt);
10667 // 1.2.2 OpenMP Language Terminology
10668 // Structured block - An executable statement with a single entry at the
10669 // top and a single exit at the bottom.
10670 // The point of exit cannot be a branch out of the structured block.
10671 // longjmp() and throw() must not violate the entry/exit criteria.
10672 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010673 for (int ThisCaptureLevel =
10674 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10675 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10676 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10677 // 1.2.2 OpenMP Language Terminology
10678 // Structured block - An executable statement with a single entry at the
10679 // top and a single exit at the bottom.
10680 // The point of exit cannot be a branch out of the structured block.
10681 // longjmp() and throw() must not violate the entry/exit criteria.
10682 CS->getCapturedDecl()->setNothrow();
10683 }
Kelvin Lida681182017-01-10 18:08:18 +000010684
10685 OMPLoopDirective::HelperExprs B;
10686 // In presence of clause 'collapse' with number of loops, it will
10687 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010688 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010689 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010690 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010691 VarsWithImplicitDSA, B);
10692 if (NestedLoopCount == 0)
10693 return StmtError();
10694
10695 assert((CurContext->isDependentContext() || B.builtAll()) &&
10696 "omp target teams distribute simd loop exprs were not built");
10697
Alexey Bataev438388c2017-11-22 18:34:02 +000010698 if (!CurContext->isDependentContext()) {
10699 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010700 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010701 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10702 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10703 B.NumIterations, *this, CurScope,
10704 DSAStack))
10705 return StmtError();
10706 }
10707 }
10708
10709 if (checkSimdlenSafelenSpecified(*this, Clauses))
10710 return StmtError();
10711
Reid Kleckner87a31802018-03-12 21:43:02 +000010712 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010713 return OMPTargetTeamsDistributeSimdDirective::Create(
10714 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10715}
10716
Alexey Bataeved09d242014-05-28 05:53:51 +000010717OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010718 SourceLocation StartLoc,
10719 SourceLocation LParenLoc,
10720 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010721 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010722 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010723 case OMPC_final:
10724 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10725 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010726 case OMPC_num_threads:
10727 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10728 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010729 case OMPC_safelen:
10730 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10731 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010732 case OMPC_simdlen:
10733 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10734 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010735 case OMPC_allocator:
10736 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10737 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010738 case OMPC_collapse:
10739 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10740 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010741 case OMPC_ordered:
10742 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10743 break;
Michael Wonge710d542015-08-07 16:16:36 +000010744 case OMPC_device:
10745 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10746 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010747 case OMPC_num_teams:
10748 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10749 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010750 case OMPC_thread_limit:
10751 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10752 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010753 case OMPC_priority:
10754 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10755 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010756 case OMPC_grainsize:
10757 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10758 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010759 case OMPC_num_tasks:
10760 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10761 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010762 case OMPC_hint:
10763 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10764 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010765 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010766 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010767 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010768 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010769 case OMPC_private:
10770 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010771 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010772 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010773 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010774 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010775 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010776 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010777 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010778 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010779 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010780 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010781 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010782 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010783 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010784 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010785 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010786 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010787 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010788 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010789 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010790 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010791 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010792 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010793 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010794 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010795 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010796 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010797 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010798 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010799 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010800 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010801 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010802 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010803 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010804 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010805 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010806 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010807 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010808 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010809 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010810 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050010811 case OMPC_nontemporal:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010812 llvm_unreachable("Clause is not allowed.");
10813 }
10814 return Res;
10815}
10816
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010817// An OpenMP directive such as 'target parallel' has two captured regions:
10818// for the 'target' and 'parallel' respectively. This function returns
10819// the region in which to capture expressions associated with a clause.
10820// A return value of OMPD_unknown signifies that the expression should not
10821// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010822static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050010823 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010824 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010825 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010826 switch (CKind) {
10827 case OMPC_if:
10828 switch (DKind) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010829 case OMPD_target_parallel_for_simd:
10830 if (OpenMPVersion >= 50 &&
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010831 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010832 CaptureRegion = OMPD_parallel;
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010833 break;
10834 }
Alexey Bataevda17a532019-12-10 11:37:03 -050010835 LLVM_FALLTHROUGH;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010836 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010837 case OMPD_target_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010838 // If this clause applies to the nested 'parallel' region, capture within
10839 // the 'target' region, otherwise do not capture.
10840 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10841 CaptureRegion = OMPD_target;
10842 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010843 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfd0c91b2019-12-16 10:27:39 -050010844 if (OpenMPVersion >= 50 &&
10845 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10846 CaptureRegion = OMPD_parallel;
10847 break;
10848 }
10849 LLVM_FALLTHROUGH;
10850 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +000010851 // If this clause applies to the nested 'parallel' region, capture within
10852 // the 'teams' region, otherwise do not capture.
10853 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10854 CaptureRegion = OMPD_teams;
10855 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010856 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataev0b978942019-12-11 15:26:38 -050010857 if (OpenMPVersion >= 50 &&
10858 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10859 CaptureRegion = OMPD_parallel;
10860 break;
10861 }
10862 LLVM_FALLTHROUGH;
10863 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010864 CaptureRegion = OMPD_teams;
10865 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010866 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010867 case OMPD_target_enter_data:
10868 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010869 CaptureRegion = OMPD_task;
10870 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010871 case OMPD_parallel_master_taskloop:
10872 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10873 CaptureRegion = OMPD_parallel;
10874 break;
Alexey Bataev5c517a62019-12-05 11:31:45 -050010875 case OMPD_parallel_master_taskloop_simd:
10876 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
10877 NameModifier == OMPD_taskloop) {
10878 CaptureRegion = OMPD_parallel;
10879 break;
10880 }
10881 if (OpenMPVersion <= 45)
10882 break;
10883 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10884 CaptureRegion = OMPD_taskloop;
10885 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010886 case OMPD_parallel_for_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010887 if (OpenMPVersion <= 45)
10888 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010889 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10890 CaptureRegion = OMPD_parallel;
10891 break;
Alexey Bataev61205822019-12-04 09:50:21 -050010892 case OMPD_taskloop_simd:
Alexey Bataev853961f2019-12-05 09:50:18 -050010893 case OMPD_master_taskloop_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010894 if (OpenMPVersion <= 45)
10895 break;
10896 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10897 CaptureRegion = OMPD_taskloop;
10898 break;
Alexey Bataev52812f22019-12-05 13:22:15 -050010899 case OMPD_distribute_parallel_for_simd:
10900 if (OpenMPVersion <= 45)
10901 break;
10902 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10903 CaptureRegion = OMPD_parallel;
10904 break;
Alexey Bataevef94cd12019-12-10 12:44:45 -050010905 case OMPD_target_simd:
10906 if (OpenMPVersion >= 50 &&
10907 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10908 CaptureRegion = OMPD_target;
10909 break;
Alexey Bataev7b774b72019-12-11 11:20:47 -050010910 case OMPD_teams_distribute_simd:
Alexey Bataev411e81a2019-12-16 11:16:46 -050010911 case OMPD_target_teams_distribute_simd:
Alexey Bataev7b774b72019-12-11 11:20:47 -050010912 if (OpenMPVersion >= 50 &&
10913 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10914 CaptureRegion = OMPD_teams;
10915 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010916 case OMPD_cancel:
10917 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010918 case OMPD_parallel_master:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010919 case OMPD_parallel_sections:
10920 case OMPD_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010921 case OMPD_target:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010922 case OMPD_target_teams:
10923 case OMPD_target_teams_distribute:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010924 case OMPD_distribute_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010925 case OMPD_task:
10926 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010927 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010928 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050010929 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050010930 case OMPD_for_simd:
Alexey Bataev779a1802019-12-06 12:21:31 -050010931 case OMPD_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010932 // Do not capture if-clause expressions.
10933 break;
10934 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010935 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010936 case OMPD_taskyield:
10937 case OMPD_barrier:
10938 case OMPD_taskwait:
10939 case OMPD_cancellation_point:
10940 case OMPD_flush:
10941 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010942 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010943 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010944 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010945 case OMPD_declare_target:
10946 case OMPD_end_declare_target:
10947 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010948 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010949 case OMPD_sections:
10950 case OMPD_section:
10951 case OMPD_single:
10952 case OMPD_master:
10953 case OMPD_critical:
10954 case OMPD_taskgroup:
10955 case OMPD_distribute:
10956 case OMPD_ordered:
10957 case OMPD_atomic:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010958 case OMPD_teams_distribute:
Kelvin Li1408f912018-09-26 04:28:39 +000010959 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010960 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10961 case OMPD_unknown:
10962 llvm_unreachable("Unknown OpenMP directive");
10963 }
10964 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010965 case OMPC_num_threads:
10966 switch (DKind) {
10967 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010968 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010969 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010970 CaptureRegion = OMPD_target;
10971 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010972 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010973 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010974 case OMPD_target_teams_distribute_parallel_for:
10975 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010976 CaptureRegion = OMPD_teams;
10977 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010978 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010979 case OMPD_parallel_master:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010980 case OMPD_parallel_sections:
10981 case OMPD_parallel_for:
10982 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010983 case OMPD_distribute_parallel_for:
10984 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010985 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010986 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010987 // Do not capture num_threads-clause expressions.
10988 break;
10989 case OMPD_target_data:
10990 case OMPD_target_enter_data:
10991 case OMPD_target_exit_data:
10992 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010993 case OMPD_target:
10994 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010995 case OMPD_target_teams:
10996 case OMPD_target_teams_distribute:
10997 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010998 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010999 case OMPD_task:
11000 case OMPD_taskloop:
11001 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011002 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011003 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011004 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011005 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011006 case OMPD_taskyield:
11007 case OMPD_barrier:
11008 case OMPD_taskwait:
11009 case OMPD_cancellation_point:
11010 case OMPD_flush:
11011 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011012 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011013 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011014 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011015 case OMPD_declare_target:
11016 case OMPD_end_declare_target:
11017 case OMPD_teams:
11018 case OMPD_simd:
11019 case OMPD_for:
11020 case OMPD_for_simd:
11021 case OMPD_sections:
11022 case OMPD_section:
11023 case OMPD_single:
11024 case OMPD_master:
11025 case OMPD_critical:
11026 case OMPD_taskgroup:
11027 case OMPD_distribute:
11028 case OMPD_ordered:
11029 case OMPD_atomic:
11030 case OMPD_distribute_simd:
11031 case OMPD_teams_distribute:
11032 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011033 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011034 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
11035 case OMPD_unknown:
11036 llvm_unreachable("Unknown OpenMP directive");
11037 }
11038 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011039 case OMPC_num_teams:
11040 switch (DKind) {
11041 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011042 case OMPD_target_teams_distribute:
11043 case OMPD_target_teams_distribute_simd:
11044 case OMPD_target_teams_distribute_parallel_for:
11045 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011046 CaptureRegion = OMPD_target;
11047 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011048 case OMPD_teams_distribute_parallel_for:
11049 case OMPD_teams_distribute_parallel_for_simd:
11050 case OMPD_teams:
11051 case OMPD_teams_distribute:
11052 case OMPD_teams_distribute_simd:
11053 // Do not capture num_teams-clause expressions.
11054 break;
11055 case OMPD_distribute_parallel_for:
11056 case OMPD_distribute_parallel_for_simd:
11057 case OMPD_task:
11058 case OMPD_taskloop:
11059 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011060 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011061 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011062 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011063 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011064 case OMPD_target_data:
11065 case OMPD_target_enter_data:
11066 case OMPD_target_exit_data:
11067 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011068 case OMPD_cancel:
11069 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011070 case OMPD_parallel_master:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011071 case OMPD_parallel_sections:
11072 case OMPD_parallel_for:
11073 case OMPD_parallel_for_simd:
11074 case OMPD_target:
11075 case OMPD_target_simd:
11076 case OMPD_target_parallel:
11077 case OMPD_target_parallel_for:
11078 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011079 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011080 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011081 case OMPD_taskyield:
11082 case OMPD_barrier:
11083 case OMPD_taskwait:
11084 case OMPD_cancellation_point:
11085 case OMPD_flush:
11086 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011087 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011088 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011089 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011090 case OMPD_declare_target:
11091 case OMPD_end_declare_target:
11092 case OMPD_simd:
11093 case OMPD_for:
11094 case OMPD_for_simd:
11095 case OMPD_sections:
11096 case OMPD_section:
11097 case OMPD_single:
11098 case OMPD_master:
11099 case OMPD_critical:
11100 case OMPD_taskgroup:
11101 case OMPD_distribute:
11102 case OMPD_ordered:
11103 case OMPD_atomic:
11104 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011105 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011106 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11107 case OMPD_unknown:
11108 llvm_unreachable("Unknown OpenMP directive");
11109 }
11110 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011111 case OMPC_thread_limit:
11112 switch (DKind) {
11113 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011114 case OMPD_target_teams_distribute:
11115 case OMPD_target_teams_distribute_simd:
11116 case OMPD_target_teams_distribute_parallel_for:
11117 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011118 CaptureRegion = OMPD_target;
11119 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011120 case OMPD_teams_distribute_parallel_for:
11121 case OMPD_teams_distribute_parallel_for_simd:
11122 case OMPD_teams:
11123 case OMPD_teams_distribute:
11124 case OMPD_teams_distribute_simd:
11125 // Do not capture thread_limit-clause expressions.
11126 break;
11127 case OMPD_distribute_parallel_for:
11128 case OMPD_distribute_parallel_for_simd:
11129 case OMPD_task:
11130 case OMPD_taskloop:
11131 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011132 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011133 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011134 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011135 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011136 case OMPD_target_data:
11137 case OMPD_target_enter_data:
11138 case OMPD_target_exit_data:
11139 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011140 case OMPD_cancel:
11141 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011142 case OMPD_parallel_master:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011143 case OMPD_parallel_sections:
11144 case OMPD_parallel_for:
11145 case OMPD_parallel_for_simd:
11146 case OMPD_target:
11147 case OMPD_target_simd:
11148 case OMPD_target_parallel:
11149 case OMPD_target_parallel_for:
11150 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011151 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011152 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011153 case OMPD_taskyield:
11154 case OMPD_barrier:
11155 case OMPD_taskwait:
11156 case OMPD_cancellation_point:
11157 case OMPD_flush:
11158 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011159 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011160 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011161 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011162 case OMPD_declare_target:
11163 case OMPD_end_declare_target:
11164 case OMPD_simd:
11165 case OMPD_for:
11166 case OMPD_for_simd:
11167 case OMPD_sections:
11168 case OMPD_section:
11169 case OMPD_single:
11170 case OMPD_master:
11171 case OMPD_critical:
11172 case OMPD_taskgroup:
11173 case OMPD_distribute:
11174 case OMPD_ordered:
11175 case OMPD_atomic:
11176 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011177 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011178 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
11179 case OMPD_unknown:
11180 llvm_unreachable("Unknown OpenMP directive");
11181 }
11182 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011183 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011184 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000011185 case OMPD_parallel_for:
11186 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011187 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000011188 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011189 case OMPD_teams_distribute_parallel_for:
11190 case OMPD_teams_distribute_parallel_for_simd:
11191 case OMPD_target_parallel_for:
11192 case OMPD_target_parallel_for_simd:
11193 case OMPD_target_teams_distribute_parallel_for:
11194 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011195 CaptureRegion = OMPD_parallel;
11196 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011197 case OMPD_for:
11198 case OMPD_for_simd:
11199 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011200 break;
11201 case OMPD_task:
11202 case OMPD_taskloop:
11203 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011204 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011205 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011206 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011207 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011208 case OMPD_target_data:
11209 case OMPD_target_enter_data:
11210 case OMPD_target_exit_data:
11211 case OMPD_target_update:
11212 case OMPD_teams:
11213 case OMPD_teams_distribute:
11214 case OMPD_teams_distribute_simd:
11215 case OMPD_target_teams_distribute:
11216 case OMPD_target_teams_distribute_simd:
11217 case OMPD_target:
11218 case OMPD_target_simd:
11219 case OMPD_target_parallel:
11220 case OMPD_cancel:
11221 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011222 case OMPD_parallel_master:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011223 case OMPD_parallel_sections:
11224 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011225 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011226 case OMPD_taskyield:
11227 case OMPD_barrier:
11228 case OMPD_taskwait:
11229 case OMPD_cancellation_point:
11230 case OMPD_flush:
11231 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011232 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011233 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011234 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011235 case OMPD_declare_target:
11236 case OMPD_end_declare_target:
11237 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011238 case OMPD_sections:
11239 case OMPD_section:
11240 case OMPD_single:
11241 case OMPD_master:
11242 case OMPD_critical:
11243 case OMPD_taskgroup:
11244 case OMPD_distribute:
11245 case OMPD_ordered:
11246 case OMPD_atomic:
11247 case OMPD_distribute_simd:
11248 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011249 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011250 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11251 case OMPD_unknown:
11252 llvm_unreachable("Unknown OpenMP directive");
11253 }
11254 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011255 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011256 switch (DKind) {
11257 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011258 case OMPD_teams_distribute_parallel_for_simd:
11259 case OMPD_teams_distribute:
11260 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011261 case OMPD_target_teams_distribute_parallel_for:
11262 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011263 case OMPD_target_teams_distribute:
11264 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011265 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011266 break;
11267 case OMPD_distribute_parallel_for:
11268 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011269 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011270 case OMPD_distribute_simd:
11271 // Do not capture thread_limit-clause expressions.
11272 break;
11273 case OMPD_parallel_for:
11274 case OMPD_parallel_for_simd:
11275 case OMPD_target_parallel_for_simd:
11276 case OMPD_target_parallel_for:
11277 case OMPD_task:
11278 case OMPD_taskloop:
11279 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011280 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011281 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011282 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011283 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011284 case OMPD_target_data:
11285 case OMPD_target_enter_data:
11286 case OMPD_target_exit_data:
11287 case OMPD_target_update:
11288 case OMPD_teams:
11289 case OMPD_target:
11290 case OMPD_target_simd:
11291 case OMPD_target_parallel:
11292 case OMPD_cancel:
11293 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011294 case OMPD_parallel_master:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011295 case OMPD_parallel_sections:
11296 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011297 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011298 case OMPD_taskyield:
11299 case OMPD_barrier:
11300 case OMPD_taskwait:
11301 case OMPD_cancellation_point:
11302 case OMPD_flush:
11303 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011304 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011305 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011306 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011307 case OMPD_declare_target:
11308 case OMPD_end_declare_target:
11309 case OMPD_simd:
11310 case OMPD_for:
11311 case OMPD_for_simd:
11312 case OMPD_sections:
11313 case OMPD_section:
11314 case OMPD_single:
11315 case OMPD_master:
11316 case OMPD_critical:
11317 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011318 case OMPD_ordered:
11319 case OMPD_atomic:
11320 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011321 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011322 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11323 case OMPD_unknown:
11324 llvm_unreachable("Unknown OpenMP directive");
11325 }
11326 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011327 case OMPC_device:
11328 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011329 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011330 case OMPD_target_enter_data:
11331 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011332 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011333 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011334 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011335 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011336 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011337 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011338 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011339 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011340 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011341 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011342 CaptureRegion = OMPD_task;
11343 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011344 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011345 // Do not capture device-clause expressions.
11346 break;
11347 case OMPD_teams_distribute_parallel_for:
11348 case OMPD_teams_distribute_parallel_for_simd:
11349 case OMPD_teams:
11350 case OMPD_teams_distribute:
11351 case OMPD_teams_distribute_simd:
11352 case OMPD_distribute_parallel_for:
11353 case OMPD_distribute_parallel_for_simd:
11354 case OMPD_task:
11355 case OMPD_taskloop:
11356 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011357 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011358 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011359 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011360 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011361 case OMPD_cancel:
11362 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011363 case OMPD_parallel_master:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011364 case OMPD_parallel_sections:
11365 case OMPD_parallel_for:
11366 case OMPD_parallel_for_simd:
11367 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011368 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011369 case OMPD_taskyield:
11370 case OMPD_barrier:
11371 case OMPD_taskwait:
11372 case OMPD_cancellation_point:
11373 case OMPD_flush:
11374 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011375 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011376 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011377 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011378 case OMPD_declare_target:
11379 case OMPD_end_declare_target:
11380 case OMPD_simd:
11381 case OMPD_for:
11382 case OMPD_for_simd:
11383 case OMPD_sections:
11384 case OMPD_section:
11385 case OMPD_single:
11386 case OMPD_master:
11387 case OMPD_critical:
11388 case OMPD_taskgroup:
11389 case OMPD_distribute:
11390 case OMPD_ordered:
11391 case OMPD_atomic:
11392 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011393 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011394 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11395 case OMPD_unknown:
11396 llvm_unreachable("Unknown OpenMP directive");
11397 }
11398 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011399 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011400 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011401 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011402 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011403 switch (DKind) {
11404 case OMPD_task:
11405 case OMPD_taskloop:
11406 case OMPD_taskloop_simd:
11407 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011408 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011409 break;
11410 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011411 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011412 CaptureRegion = OMPD_parallel;
11413 break;
11414 case OMPD_target_update:
11415 case OMPD_target_enter_data:
11416 case OMPD_target_exit_data:
11417 case OMPD_target:
11418 case OMPD_target_simd:
11419 case OMPD_target_teams:
11420 case OMPD_target_parallel:
11421 case OMPD_target_teams_distribute:
11422 case OMPD_target_teams_distribute_simd:
11423 case OMPD_target_parallel_for:
11424 case OMPD_target_parallel_for_simd:
11425 case OMPD_target_teams_distribute_parallel_for:
11426 case OMPD_target_teams_distribute_parallel_for_simd:
11427 case OMPD_target_data:
11428 case OMPD_teams_distribute_parallel_for:
11429 case OMPD_teams_distribute_parallel_for_simd:
11430 case OMPD_teams:
11431 case OMPD_teams_distribute:
11432 case OMPD_teams_distribute_simd:
11433 case OMPD_distribute_parallel_for:
11434 case OMPD_distribute_parallel_for_simd:
11435 case OMPD_cancel:
11436 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011437 case OMPD_parallel_master:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011438 case OMPD_parallel_sections:
11439 case OMPD_parallel_for:
11440 case OMPD_parallel_for_simd:
11441 case OMPD_threadprivate:
11442 case OMPD_allocate:
11443 case OMPD_taskyield:
11444 case OMPD_barrier:
11445 case OMPD_taskwait:
11446 case OMPD_cancellation_point:
11447 case OMPD_flush:
11448 case OMPD_declare_reduction:
11449 case OMPD_declare_mapper:
11450 case OMPD_declare_simd:
11451 case OMPD_declare_variant:
11452 case OMPD_declare_target:
11453 case OMPD_end_declare_target:
11454 case OMPD_simd:
11455 case OMPD_for:
11456 case OMPD_for_simd:
11457 case OMPD_sections:
11458 case OMPD_section:
11459 case OMPD_single:
11460 case OMPD_master:
11461 case OMPD_critical:
11462 case OMPD_taskgroup:
11463 case OMPD_distribute:
11464 case OMPD_ordered:
11465 case OMPD_atomic:
11466 case OMPD_distribute_simd:
11467 case OMPD_requires:
11468 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11469 case OMPD_unknown:
11470 llvm_unreachable("Unknown OpenMP directive");
11471 }
11472 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011473 case OMPC_firstprivate:
11474 case OMPC_lastprivate:
11475 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011476 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011477 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011478 case OMPC_linear:
11479 case OMPC_default:
11480 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011481 case OMPC_safelen:
11482 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011483 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011484 case OMPC_collapse:
11485 case OMPC_private:
11486 case OMPC_shared:
11487 case OMPC_aligned:
11488 case OMPC_copyin:
11489 case OMPC_copyprivate:
11490 case OMPC_ordered:
11491 case OMPC_nowait:
11492 case OMPC_untied:
11493 case OMPC_mergeable:
11494 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011495 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011496 case OMPC_flush:
11497 case OMPC_read:
11498 case OMPC_write:
11499 case OMPC_update:
11500 case OMPC_capture:
11501 case OMPC_seq_cst:
11502 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011503 case OMPC_threads:
11504 case OMPC_simd:
11505 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011506 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011507 case OMPC_hint:
11508 case OMPC_defaultmap:
11509 case OMPC_unknown:
11510 case OMPC_uniform:
11511 case OMPC_to:
11512 case OMPC_from:
11513 case OMPC_use_device_ptr:
11514 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011515 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011516 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011517 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011518 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011519 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011520 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011521 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011522 case OMPC_nontemporal:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011523 llvm_unreachable("Unexpected OpenMP clause.");
11524 }
11525 return CaptureRegion;
11526}
11527
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011528OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11529 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011530 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011531 SourceLocation NameModifierLoc,
11532 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011533 SourceLocation EndLoc) {
11534 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011535 Stmt *HelperValStmt = nullptr;
11536 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011537 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11538 !Condition->isInstantiationDependent() &&
11539 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011540 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011541 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011542 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011543
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011544 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011545
11546 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011547 CaptureRegion = getOpenMPCaptureRegionForClause(
11548 DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011549 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011550 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011551 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011552 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11553 HelperValStmt = buildPreInits(Context, Captures);
11554 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011555 }
11556
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011557 return new (Context)
11558 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11559 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011560}
11561
Alexey Bataev3778b602014-07-17 07:32:53 +000011562OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11563 SourceLocation StartLoc,
11564 SourceLocation LParenLoc,
11565 SourceLocation EndLoc) {
11566 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011567 Stmt *HelperValStmt = nullptr;
11568 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011569 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11570 !Condition->isInstantiationDependent() &&
11571 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011572 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011573 if (Val.isInvalid())
11574 return nullptr;
11575
Richard Smith03a4aa32016-06-23 19:02:52 +000011576 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011577
11578 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011579 CaptureRegion =
11580 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011581 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11582 ValExpr = MakeFullExpr(ValExpr).get();
11583 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11584 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11585 HelperValStmt = buildPreInits(Context, Captures);
11586 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011587 }
11588
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011589 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11590 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011591}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011592
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011593ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11594 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011595 if (!Op)
11596 return ExprError();
11597
11598 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11599 public:
11600 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011601 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011602 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11603 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011604 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11605 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011606 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11607 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011608 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11609 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011610 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11611 QualType T,
11612 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011613 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11614 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011615 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11616 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011617 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011618 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011619 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011620 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11621 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011622 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11623 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011624 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11625 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011626 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011627 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011628 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011629 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11630 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011631 llvm_unreachable("conversion functions are permitted");
11632 }
11633 } ConvertDiagnoser;
11634 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11635}
11636
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011637static bool
11638isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11639 bool StrictlyPositive, bool BuildCapture = false,
11640 OpenMPDirectiveKind DKind = OMPD_unknown,
11641 OpenMPDirectiveKind *CaptureRegion = nullptr,
11642 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011643 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11644 !ValExpr->isInstantiationDependent()) {
11645 SourceLocation Loc = ValExpr->getExprLoc();
11646 ExprResult Value =
11647 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11648 if (Value.isInvalid())
11649 return false;
11650
11651 ValExpr = Value.get();
11652 // The expression must evaluate to a non-negative integer value.
11653 llvm::APSInt Result;
11654 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011655 Result.isSigned() &&
11656 !((!StrictlyPositive && Result.isNonNegative()) ||
11657 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011658 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011659 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11660 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011661 return false;
11662 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011663 if (!BuildCapture)
11664 return true;
Alexey Bataev61205822019-12-04 09:50:21 -050011665 *CaptureRegion =
11666 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011667 if (*CaptureRegion != OMPD_unknown &&
11668 !SemaRef.CurContext->isDependentContext()) {
11669 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11670 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11671 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11672 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11673 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011674 }
11675 return true;
11676}
11677
Alexey Bataev568a8332014-03-06 06:15:19 +000011678OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11679 SourceLocation StartLoc,
11680 SourceLocation LParenLoc,
11681 SourceLocation EndLoc) {
11682 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011683 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011684
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011685 // OpenMP [2.5, Restrictions]
11686 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011687 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011688 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011689 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011690
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011691 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011692 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050011693 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011694 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011695 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011696 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011697 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11698 HelperValStmt = buildPreInits(Context, Captures);
11699 }
11700
11701 return new (Context) OMPNumThreadsClause(
11702 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011703}
11704
Alexey Bataev62c87d22014-03-21 04:51:18 +000011705ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011706 OpenMPClauseKind CKind,
11707 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011708 if (!E)
11709 return ExprError();
11710 if (E->isValueDependent() || E->isTypeDependent() ||
11711 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011712 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011713 llvm::APSInt Result;
11714 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11715 if (ICE.isInvalid())
11716 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011717 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11718 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011719 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011720 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11721 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011722 return ExprError();
11723 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011724 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11725 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11726 << E->getSourceRange();
11727 return ExprError();
11728 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011729 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11730 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011731 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011732 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011733 return ICE;
11734}
11735
11736OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11737 SourceLocation LParenLoc,
11738 SourceLocation EndLoc) {
11739 // OpenMP [2.8.1, simd construct, Description]
11740 // The parameter of the safelen clause must be a constant
11741 // positive integer expression.
11742 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11743 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011744 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011745 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011746 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011747}
11748
Alexey Bataev66b15b52015-08-21 11:14:16 +000011749OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11750 SourceLocation LParenLoc,
11751 SourceLocation EndLoc) {
11752 // OpenMP [2.8.1, simd construct, Description]
11753 // The parameter of the simdlen clause must be a constant
11754 // positive integer expression.
11755 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11756 if (Simdlen.isInvalid())
11757 return nullptr;
11758 return new (Context)
11759 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11760}
11761
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011762/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011763static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11764 DSAStackTy *Stack) {
11765 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011766 if (!OMPAllocatorHandleT.isNull())
11767 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011768 // Build the predefined allocator expressions.
11769 bool ErrorFound = false;
11770 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11771 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11772 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11773 StringRef Allocator =
11774 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11775 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11776 auto *VD = dyn_cast_or_null<ValueDecl>(
11777 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11778 if (!VD) {
11779 ErrorFound = true;
11780 break;
11781 }
11782 QualType AllocatorType =
11783 VD->getType().getNonLValueExprType(S.getASTContext());
11784 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11785 if (!Res.isUsable()) {
11786 ErrorFound = true;
11787 break;
11788 }
11789 if (OMPAllocatorHandleT.isNull())
11790 OMPAllocatorHandleT = AllocatorType;
11791 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11792 ErrorFound = true;
11793 break;
11794 }
11795 Stack->setAllocator(AllocatorKind, Res.get());
11796 }
11797 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011798 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11799 return false;
11800 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011801 OMPAllocatorHandleT.addConst();
11802 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011803 return true;
11804}
11805
11806OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11807 SourceLocation LParenLoc,
11808 SourceLocation EndLoc) {
11809 // OpenMP [2.11.3, allocate Directive, Description]
11810 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011811 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011812 return nullptr;
11813
11814 ExprResult Allocator = DefaultLvalueConversion(A);
11815 if (Allocator.isInvalid())
11816 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011817 Allocator = PerformImplicitConversion(Allocator.get(),
11818 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011819 Sema::AA_Initializing,
11820 /*AllowExplicit=*/true);
11821 if (Allocator.isInvalid())
11822 return nullptr;
11823 return new (Context)
11824 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11825}
11826
Alexander Musman64d33f12014-06-04 07:53:32 +000011827OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11828 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011829 SourceLocation LParenLoc,
11830 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011831 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011832 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011833 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011834 // The parameter of the collapse clause must be a constant
11835 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011836 ExprResult NumForLoopsResult =
11837 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11838 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011839 return nullptr;
11840 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011841 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011842}
11843
Alexey Bataev10e775f2015-07-30 11:36:16 +000011844OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11845 SourceLocation EndLoc,
11846 SourceLocation LParenLoc,
11847 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011848 // OpenMP [2.7.1, loop construct, Description]
11849 // OpenMP [2.8.1, simd construct, Description]
11850 // OpenMP [2.9.6, distribute construct, Description]
11851 // The parameter of the ordered clause must be a constant
11852 // positive integer expression if any.
11853 if (NumForLoops && LParenLoc.isValid()) {
11854 ExprResult NumForLoopsResult =
11855 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11856 if (NumForLoopsResult.isInvalid())
11857 return nullptr;
11858 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011859 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011860 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011861 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011862 auto *Clause = OMPOrderedClause::Create(
11863 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11864 StartLoc, LParenLoc, EndLoc);
11865 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11866 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011867}
11868
Alexey Bataeved09d242014-05-28 05:53:51 +000011869OMPClause *Sema::ActOnOpenMPSimpleClause(
11870 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11871 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011872 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011873 switch (Kind) {
11874 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011875 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011876 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11877 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011878 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011879 case OMPC_proc_bind:
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060011880 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
11881 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011882 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011883 case OMPC_atomic_default_mem_order:
11884 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11885 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11886 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11887 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011888 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011889 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011890 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011891 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011892 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011893 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011894 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011895 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011896 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011897 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011898 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011899 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011900 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011901 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011902 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011903 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011904 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011905 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011906 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011907 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011908 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011909 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011910 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011911 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011912 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011913 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011914 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011915 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011916 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011917 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011918 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011919 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011920 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011921 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011922 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011923 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011924 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011925 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011926 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011927 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011928 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011929 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011930 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011931 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011932 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011933 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011934 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011935 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011936 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011937 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011938 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011939 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011940 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011941 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011942 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011943 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011944 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011945 case OMPC_nontemporal:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011946 llvm_unreachable("Clause is not allowed.");
11947 }
11948 return Res;
11949}
11950
Alexey Bataev6402bca2015-12-28 07:25:51 +000011951static std::string
11952getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11953 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011954 SmallString<256> Buffer;
11955 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011956 unsigned Skipped = Exclude.size();
11957 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011958 for (unsigned I = First; I < Last; ++I) {
11959 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011960 --Skipped;
11961 continue;
11962 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011963 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
Alexey Bataev87a004d2020-01-02 09:26:32 -050011964 if (I + Skipped + 2 == Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000011965 Out << " or ";
Alexey Bataev87a004d2020-01-02 09:26:32 -050011966 else if (I + Skipped + 1 != Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000011967 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011968 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011969 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011970}
11971
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011972OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11973 SourceLocation KindKwLoc,
11974 SourceLocation StartLoc,
11975 SourceLocation LParenLoc,
11976 SourceLocation EndLoc) {
11977 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011978 static_assert(OMPC_DEFAULT_unknown > 0,
11979 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011980 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011981 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11982 /*Last=*/OMPC_DEFAULT_unknown)
11983 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011984 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011985 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011986 switch (Kind) {
11987 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011988 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011989 break;
11990 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011991 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011992 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011993 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011994 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011995 break;
11996 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011997 return new (Context)
11998 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011999}
12000
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012001OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012002 SourceLocation KindKwLoc,
12003 SourceLocation StartLoc,
12004 SourceLocation LParenLoc,
12005 SourceLocation EndLoc) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012006 if (Kind == OMP_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012007 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012008 << getListOfPossibleValues(OMPC_proc_bind,
12009 /*First=*/unsigned(OMP_PROC_BIND_master),
12010 /*Last=*/5)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012011 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012012 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012013 }
Alexey Bataeved09d242014-05-28 05:53:51 +000012014 return new (Context)
12015 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012016}
12017
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012018OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
12019 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
12020 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12021 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
12022 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12023 << getListOfPossibleValues(
12024 OMPC_atomic_default_mem_order, /*First=*/0,
12025 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
12026 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
12027 return nullptr;
12028 }
12029 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
12030 LParenLoc, EndLoc);
12031}
12032
Alexey Bataev56dafe82014-06-20 07:16:17 +000012033OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012034 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012035 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012036 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012037 SourceLocation EndLoc) {
12038 OMPClause *Res = nullptr;
12039 switch (Kind) {
12040 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012041 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
12042 assert(Argument.size() == NumberOfElements &&
12043 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012044 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012045 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
12046 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
12047 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
12048 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
12049 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012050 break;
12051 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012052 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
12053 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
12054 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
12055 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000012056 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012057 case OMPC_dist_schedule:
12058 Res = ActOnOpenMPDistScheduleClause(
12059 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
12060 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
12061 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012062 case OMPC_defaultmap:
12063 enum { Modifier, DefaultmapKind };
12064 Res = ActOnOpenMPDefaultmapClause(
12065 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
12066 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000012067 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
12068 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012069 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000012070 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012071 case OMPC_num_threads:
12072 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012073 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012074 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012075 case OMPC_collapse:
12076 case OMPC_default:
12077 case OMPC_proc_bind:
12078 case OMPC_private:
12079 case OMPC_firstprivate:
12080 case OMPC_lastprivate:
12081 case OMPC_shared:
12082 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012083 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012084 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012085 case OMPC_linear:
12086 case OMPC_aligned:
12087 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012088 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012089 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012090 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012091 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012092 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012093 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012094 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012095 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012096 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012097 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012098 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012099 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012100 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012101 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012102 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012103 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012104 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012105 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012106 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012107 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012108 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012109 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012110 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012111 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012112 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012113 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012114 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012115 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012116 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012117 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012118 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000012119 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012120 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012121 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012122 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012123 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012124 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012125 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012126 case OMPC_nontemporal:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012127 llvm_unreachable("Clause is not allowed.");
12128 }
12129 return Res;
12130}
12131
Alexey Bataev6402bca2015-12-28 07:25:51 +000012132static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
12133 OpenMPScheduleClauseModifier M2,
12134 SourceLocation M1Loc, SourceLocation M2Loc) {
12135 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
12136 SmallVector<unsigned, 2> Excluded;
12137 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
12138 Excluded.push_back(M2);
12139 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
12140 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
12141 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
12142 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
12143 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
12144 << getListOfPossibleValues(OMPC_schedule,
12145 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
12146 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12147 Excluded)
12148 << getOpenMPClauseName(OMPC_schedule);
12149 return true;
12150 }
12151 return false;
12152}
12153
Alexey Bataev56dafe82014-06-20 07:16:17 +000012154OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012155 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012156 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012157 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
12158 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
12159 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
12160 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
12161 return nullptr;
12162 // OpenMP, 2.7.1, Loop Construct, Restrictions
12163 // Either the monotonic modifier or the nonmonotonic modifier can be specified
12164 // but not both.
12165 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
12166 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
12167 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
12168 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
12169 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
12170 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
12171 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
12172 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
12173 return nullptr;
12174 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012175 if (Kind == OMPC_SCHEDULE_unknown) {
12176 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000012177 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
12178 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
12179 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12180 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12181 Exclude);
12182 } else {
12183 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12184 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012185 }
12186 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12187 << Values << getOpenMPClauseName(OMPC_schedule);
12188 return nullptr;
12189 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000012190 // OpenMP, 2.7.1, Loop Construct, Restrictions
12191 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
12192 // schedule(guided).
12193 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
12194 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
12195 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
12196 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
12197 diag::err_omp_schedule_nonmonotonic_static);
12198 return nullptr;
12199 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012200 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012201 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000012202 if (ChunkSize) {
12203 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12204 !ChunkSize->isInstantiationDependent() &&
12205 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012206 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000012207 ExprResult Val =
12208 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12209 if (Val.isInvalid())
12210 return nullptr;
12211
12212 ValExpr = Val.get();
12213
12214 // OpenMP [2.7.1, Restrictions]
12215 // chunk_size must be a loop invariant integer expression with a positive
12216 // value.
12217 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000012218 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12219 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12220 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000012221 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000012222 return nullptr;
12223 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012224 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050012225 DSAStack->getCurrentDirective(), OMPC_schedule,
12226 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012227 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012228 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012229 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012230 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12231 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012232 }
12233 }
12234 }
12235
Alexey Bataev6402bca2015-12-28 07:25:51 +000012236 return new (Context)
12237 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012238 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012239}
12240
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012241OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12242 SourceLocation StartLoc,
12243 SourceLocation EndLoc) {
12244 OMPClause *Res = nullptr;
12245 switch (Kind) {
12246 case OMPC_ordered:
12247 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12248 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012249 case OMPC_nowait:
12250 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12251 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012252 case OMPC_untied:
12253 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12254 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012255 case OMPC_mergeable:
12256 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12257 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012258 case OMPC_read:
12259 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12260 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012261 case OMPC_write:
12262 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12263 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012264 case OMPC_update:
12265 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12266 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012267 case OMPC_capture:
12268 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12269 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012270 case OMPC_seq_cst:
12271 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12272 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012273 case OMPC_threads:
12274 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12275 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012276 case OMPC_simd:
12277 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12278 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012279 case OMPC_nogroup:
12280 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12281 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012282 case OMPC_unified_address:
12283 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12284 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012285 case OMPC_unified_shared_memory:
12286 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12287 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012288 case OMPC_reverse_offload:
12289 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12290 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012291 case OMPC_dynamic_allocators:
12292 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12293 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012294 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012295 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012296 case OMPC_num_threads:
12297 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012298 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012299 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012300 case OMPC_collapse:
12301 case OMPC_schedule:
12302 case OMPC_private:
12303 case OMPC_firstprivate:
12304 case OMPC_lastprivate:
12305 case OMPC_shared:
12306 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012307 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012308 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012309 case OMPC_linear:
12310 case OMPC_aligned:
12311 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012312 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012313 case OMPC_default:
12314 case OMPC_proc_bind:
12315 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012316 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012317 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012318 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012319 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012320 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012321 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012322 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012323 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012324 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012325 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012326 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012327 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012328 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012329 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012330 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012331 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012332 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012333 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012334 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012335 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012336 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012337 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012338 case OMPC_nontemporal:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012339 llvm_unreachable("Clause is not allowed.");
12340 }
12341 return Res;
12342}
12343
Alexey Bataev236070f2014-06-20 11:19:47 +000012344OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12345 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012346 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012347 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12348}
12349
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012350OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12351 SourceLocation EndLoc) {
12352 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12353}
12354
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012355OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12356 SourceLocation EndLoc) {
12357 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12358}
12359
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012360OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12361 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012362 return new (Context) OMPReadClause(StartLoc, EndLoc);
12363}
12364
Alexey Bataevdea47612014-07-23 07:46:59 +000012365OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12366 SourceLocation EndLoc) {
12367 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12368}
12369
Alexey Bataev67a4f222014-07-23 10:25:33 +000012370OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12371 SourceLocation EndLoc) {
12372 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12373}
12374
Alexey Bataev459dec02014-07-24 06:46:57 +000012375OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12376 SourceLocation EndLoc) {
12377 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12378}
12379
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012380OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12381 SourceLocation EndLoc) {
12382 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12383}
12384
Alexey Bataev346265e2015-09-25 10:37:12 +000012385OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12386 SourceLocation EndLoc) {
12387 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12388}
12389
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012390OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12391 SourceLocation EndLoc) {
12392 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12393}
12394
Alexey Bataevb825de12015-12-07 10:51:44 +000012395OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12396 SourceLocation EndLoc) {
12397 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12398}
12399
Kelvin Li1408f912018-09-26 04:28:39 +000012400OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12401 SourceLocation EndLoc) {
12402 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12403}
12404
Patrick Lyster4a370b92018-10-01 13:47:43 +000012405OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12406 SourceLocation EndLoc) {
12407 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12408}
12409
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012410OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12411 SourceLocation EndLoc) {
12412 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12413}
12414
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012415OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12416 SourceLocation EndLoc) {
12417 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12418}
12419
Alexey Bataevc5e02582014-06-16 07:08:35 +000012420OMPClause *Sema::ActOnOpenMPVarListClause(
12421 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012422 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12423 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012424 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
Kelvin Lief579432018-12-18 22:18:41 +000012425 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012426 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
12427 SourceLocation DepLinMapLastLoc) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012428 SourceLocation StartLoc = Locs.StartLoc;
12429 SourceLocation LParenLoc = Locs.LParenLoc;
12430 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012431 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012432 switch (Kind) {
12433 case OMPC_private:
12434 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12435 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012436 case OMPC_firstprivate:
12437 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12438 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012439 case OMPC_lastprivate:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012440 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
12441 "Unexpected lastprivate modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012442 Res = ActOnOpenMPLastprivateClause(
12443 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
12444 DepLinMapLastLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012445 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012446 case OMPC_shared:
12447 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12448 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012449 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012450 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012451 EndLoc, ReductionOrMapperIdScopeSpec,
12452 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012453 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012454 case OMPC_task_reduction:
12455 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012456 EndLoc, ReductionOrMapperIdScopeSpec,
12457 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012458 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012459 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012460 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12461 EndLoc, ReductionOrMapperIdScopeSpec,
12462 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012463 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012464 case OMPC_linear:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012465 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
12466 "Unexpected linear modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012467 Res = ActOnOpenMPLinearClause(
12468 VarList, TailExpr, StartLoc, LParenLoc,
12469 static_cast<OpenMPLinearClauseKind>(ExtraModifier), DepLinMapLastLoc,
12470 ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012471 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012472 case OMPC_aligned:
12473 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12474 ColonLoc, EndLoc);
12475 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012476 case OMPC_copyin:
12477 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12478 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012479 case OMPC_copyprivate:
12480 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12481 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012482 case OMPC_flush:
12483 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12484 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012485 case OMPC_depend:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012486 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
12487 "Unexpected depend modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012488 Res = ActOnOpenMPDependClause(
12489 static_cast<OpenMPDependClauseKind>(ExtraModifier), DepLinMapLastLoc,
12490 ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012491 break;
12492 case OMPC_map:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012493 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
12494 "Unexpected map modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012495 Res = ActOnOpenMPMapClause(
12496 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
12497 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
12498 IsMapTypeImplicit, DepLinMapLastLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012499 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012500 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012501 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12502 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012503 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012504 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012505 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12506 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012507 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012508 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012509 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012510 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012511 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012512 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012513 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012514 case OMPC_allocate:
12515 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12516 ColonLoc, EndLoc);
12517 break;
Alexey Bataevb6e70842019-12-16 15:54:17 -050012518 case OMPC_nontemporal:
12519 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
12520 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012521 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012522 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012523 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012524 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012525 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012526 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012527 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012528 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012529 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012530 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012531 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012532 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012533 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012534 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012535 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012536 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012537 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012538 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012539 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012540 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012541 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012542 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012543 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012544 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012545 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012546 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012547 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012548 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012549 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012550 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012551 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012552 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012553 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012554 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012555 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012556 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012557 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012558 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012559 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012560 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012561 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012562 llvm_unreachable("Clause is not allowed.");
12563 }
12564 return Res;
12565}
12566
Alexey Bataev90c228f2016-02-08 09:29:13 +000012567ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012568 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012569 ExprResult Res = BuildDeclRefExpr(
12570 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12571 if (!Res.isUsable())
12572 return ExprError();
12573 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12574 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12575 if (!Res.isUsable())
12576 return ExprError();
12577 }
12578 if (VK != VK_LValue && Res.get()->isGLValue()) {
12579 Res = DefaultLvalueConversion(Res.get());
12580 if (!Res.isUsable())
12581 return ExprError();
12582 }
12583 return Res;
12584}
12585
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012586OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12587 SourceLocation StartLoc,
12588 SourceLocation LParenLoc,
12589 SourceLocation EndLoc) {
12590 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012591 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012592 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012593 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012594 SourceLocation ELoc;
12595 SourceRange ERange;
12596 Expr *SimpleRefExpr = RefExpr;
12597 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012598 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012599 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012600 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012601 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012602 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012603 ValueDecl *D = Res.first;
12604 if (!D)
12605 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012606
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012607 QualType Type = D->getType();
12608 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012609
12610 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12611 // A variable that appears in a private clause must not have an incomplete
12612 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012613 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012614 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012615 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012616
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012617 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12618 // A variable that is privatized must not have a const-qualified type
12619 // unless it is of class type with a mutable member. This restriction does
12620 // not apply to the firstprivate clause.
12621 //
12622 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12623 // A variable that appears in a private clause must not have a
12624 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012625 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012626 continue;
12627
Alexey Bataev758e55e2013-09-06 18:03:48 +000012628 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12629 // in a Construct]
12630 // Variables with the predetermined data-sharing attributes may not be
12631 // listed in data-sharing attributes clauses, except for the cases
12632 // listed below. For these exceptions only, listing a predetermined
12633 // variable in a data-sharing attribute clause is allowed and overrides
12634 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012635 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012636 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012637 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12638 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012639 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012640 continue;
12641 }
12642
Alexey Bataeve3727102018-04-18 15:57:46 +000012643 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012644 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012645 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012646 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012647 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12648 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012649 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012650 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012651 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012652 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012653 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012654 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012655 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012656 continue;
12657 }
12658
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012659 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12660 // A list item cannot appear in both a map clause and a data-sharing
12661 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012662 //
12663 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12664 // A list item cannot appear in both a map clause and a data-sharing
12665 // attribute clause on the same construct unless the construct is a
12666 // combined construct.
12667 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12668 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012669 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012670 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012671 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012672 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12673 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12674 ConflictKind = WhereFoundClauseKind;
12675 return true;
12676 })) {
12677 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012678 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012679 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012680 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012681 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012682 continue;
12683 }
12684 }
12685
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012686 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12687 // A variable of class type (or array thereof) that appears in a private
12688 // clause requires an accessible, unambiguous default constructor for the
12689 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012690 // Generate helper private variable and initialize it with the default
12691 // value. The address of the original variable is replaced by the address of
12692 // the new private variable in CodeGen. This new variable is not added to
12693 // IdResolver, so the code in the OpenMP region uses original variable for
12694 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012695 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012696 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012697 buildVarDecl(*this, ELoc, Type, D->getName(),
12698 D->hasAttrs() ? &D->getAttrs() : nullptr,
12699 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012700 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012701 if (VDPrivate->isInvalidDecl())
12702 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012703 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012704 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012705
Alexey Bataev90c228f2016-02-08 09:29:13 +000012706 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012707 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012708 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012709 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012710 Vars.push_back((VD || CurContext->isDependentContext())
12711 ? RefExpr->IgnoreParens()
12712 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012713 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012714 }
12715
Alexey Bataeved09d242014-05-28 05:53:51 +000012716 if (Vars.empty())
12717 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012718
Alexey Bataev03b340a2014-10-21 03:16:40 +000012719 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12720 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012721}
12722
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012723namespace {
12724class DiagsUninitializedSeveretyRAII {
12725private:
12726 DiagnosticsEngine &Diags;
12727 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012728 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012729
12730public:
12731 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12732 bool IsIgnored)
12733 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12734 if (!IsIgnored) {
12735 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12736 /*Map*/ diag::Severity::Ignored, Loc);
12737 }
12738 }
12739 ~DiagsUninitializedSeveretyRAII() {
12740 if (!IsIgnored)
12741 Diags.popMappings(SavedLoc);
12742 }
12743};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012744}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012745
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012746OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12747 SourceLocation StartLoc,
12748 SourceLocation LParenLoc,
12749 SourceLocation EndLoc) {
12750 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012751 SmallVector<Expr *, 8> PrivateCopies;
12752 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012753 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012754 bool IsImplicitClause =
12755 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012756 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012757
Alexey Bataeve3727102018-04-18 15:57:46 +000012758 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012759 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012760 SourceLocation ELoc;
12761 SourceRange ERange;
12762 Expr *SimpleRefExpr = RefExpr;
12763 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012764 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012765 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012766 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012767 PrivateCopies.push_back(nullptr);
12768 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012769 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012770 ValueDecl *D = Res.first;
12771 if (!D)
12772 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012773
Alexey Bataev60da77e2016-02-29 05:54:20 +000012774 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012775 QualType Type = D->getType();
12776 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012777
12778 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12779 // A variable that appears in a private clause must not have an incomplete
12780 // type or a reference type.
12781 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012782 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012783 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012784 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012785
12786 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12787 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012788 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012789 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012790 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012791
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012792 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012793 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012794 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012795 DSAStackTy::DSAVarData DVar =
12796 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012797 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012798 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012799 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012800 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12801 // A list item that specifies a given variable may not appear in more
12802 // than one clause on the same directive, except that a variable may be
12803 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012804 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12805 // A list item may appear in a firstprivate or lastprivate clause but not
12806 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012807 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012808 (isOpenMPDistributeDirective(CurrDir) ||
12809 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012810 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012811 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012812 << getOpenMPClauseName(DVar.CKind)
12813 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012814 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012815 continue;
12816 }
12817
12818 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12819 // in a Construct]
12820 // Variables with the predetermined data-sharing attributes may not be
12821 // listed in data-sharing attributes clauses, except for the cases
12822 // listed below. For these exceptions only, listing a predetermined
12823 // variable in a data-sharing attribute clause is allowed and overrides
12824 // the variable's predetermined data-sharing attributes.
12825 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12826 // in a Construct, C/C++, p.2]
12827 // Variables with const-qualified type having no mutable member may be
12828 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012829 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012830 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12831 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012832 << getOpenMPClauseName(DVar.CKind)
12833 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012834 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012835 continue;
12836 }
12837
12838 // OpenMP [2.9.3.4, Restrictions, p.2]
12839 // A list item that is private within a parallel region must not appear
12840 // in a firstprivate clause on a worksharing construct if any of the
12841 // worksharing regions arising from the worksharing construct ever bind
12842 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012843 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12844 // A list item that is private within a teams region must not appear in a
12845 // firstprivate clause on a distribute construct if any of the distribute
12846 // regions arising from the distribute construct ever bind to any of the
12847 // teams regions arising from the teams construct.
12848 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12849 // A list item that appears in a reduction clause of a teams construct
12850 // must not appear in a firstprivate clause on a distribute construct if
12851 // any of the distribute regions arising from the distribute construct
12852 // ever bind to any of the teams regions arising from the teams construct.
12853 if ((isOpenMPWorksharingDirective(CurrDir) ||
12854 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012855 !isOpenMPParallelDirective(CurrDir) &&
12856 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012857 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012858 if (DVar.CKind != OMPC_shared &&
12859 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012860 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012861 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012862 Diag(ELoc, diag::err_omp_required_access)
12863 << getOpenMPClauseName(OMPC_firstprivate)
12864 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012865 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012866 continue;
12867 }
12868 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012869 // OpenMP [2.9.3.4, Restrictions, p.3]
12870 // A list item that appears in a reduction clause of a parallel construct
12871 // must not appear in a firstprivate clause on a worksharing or task
12872 // construct if any of the worksharing or task regions arising from the
12873 // worksharing or task construct ever bind to any of the parallel regions
12874 // arising from the parallel construct.
12875 // OpenMP [2.9.3.4, Restrictions, p.4]
12876 // A list item that appears in a reduction clause in worksharing
12877 // construct must not appear in a firstprivate clause in a task construct
12878 // encountered during execution of any of the worksharing regions arising
12879 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012880 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012881 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012882 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12883 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012884 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012885 isOpenMPWorksharingDirective(K) ||
12886 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012887 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012888 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012889 if (DVar.CKind == OMPC_reduction &&
12890 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012891 isOpenMPWorksharingDirective(DVar.DKind) ||
12892 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012893 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12894 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012895 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012896 continue;
12897 }
12898 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012899
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012900 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12901 // A list item cannot appear in both a map clause and a data-sharing
12902 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012903 //
12904 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12905 // A list item cannot appear in both a map clause and a data-sharing
12906 // attribute clause on the same construct unless the construct is a
12907 // combined construct.
12908 if ((LangOpts.OpenMP <= 45 &&
12909 isOpenMPTargetExecutionDirective(CurrDir)) ||
12910 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012911 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012912 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012913 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012914 [&ConflictKind](
12915 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12916 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012917 ConflictKind = WhereFoundClauseKind;
12918 return true;
12919 })) {
12920 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012921 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012922 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012923 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012924 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012925 continue;
12926 }
12927 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012928 }
12929
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012930 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012931 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012932 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012933 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12934 << getOpenMPClauseName(OMPC_firstprivate) << Type
12935 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12936 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012937 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012938 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012939 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012940 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012941 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012942 continue;
12943 }
12944
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012945 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012946 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012947 buildVarDecl(*this, ELoc, Type, D->getName(),
12948 D->hasAttrs() ? &D->getAttrs() : nullptr,
12949 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012950 // Generate helper private variable and initialize it with the value of the
12951 // original variable. The address of the original variable is replaced by
12952 // the address of the new private variable in the CodeGen. This new variable
12953 // is not added to IdResolver, so the code in the OpenMP region uses
12954 // original variable for proper diagnostics and variable capturing.
12955 Expr *VDInitRefExpr = nullptr;
12956 // For arrays generate initializer for single element and replace it by the
12957 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012958 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012959 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012960 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012961 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012962 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012963 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012964 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12965 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012966 InitializedEntity Entity =
12967 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012968 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12969
12970 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12971 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12972 if (Result.isInvalid())
12973 VDPrivate->setInvalidDecl();
12974 else
12975 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012976 // Remove temp variable declaration.
12977 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012978 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012979 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12980 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012981 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12982 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012983 AddInitializerToDecl(VDPrivate,
12984 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012985 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012986 }
12987 if (VDPrivate->isInvalidDecl()) {
12988 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012989 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012990 diag::note_omp_task_predetermined_firstprivate_here);
12991 }
12992 continue;
12993 }
12994 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012995 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012996 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12997 RefExpr->getExprLoc());
12998 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012999 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013000 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013001 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013002 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013003 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013004 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013005 ExprCaptures.push_back(Ref->getDecl());
13006 }
Alexey Bataev417089f2016-02-17 13:19:37 +000013007 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000013008 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013009 Vars.push_back((VD || CurContext->isDependentContext())
13010 ? RefExpr->IgnoreParens()
13011 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013012 PrivateCopies.push_back(VDPrivateRefExpr);
13013 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013014 }
13015
Alexey Bataeved09d242014-05-28 05:53:51 +000013016 if (Vars.empty())
13017 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013018
13019 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013020 Vars, PrivateCopies, Inits,
13021 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013022}
13023
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013024OMPClause *Sema::ActOnOpenMPLastprivateClause(
13025 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
13026 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
13027 SourceLocation LParenLoc, SourceLocation EndLoc) {
13028 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
13029 assert(ColonLoc.isValid() && "Colon location must be valid.");
13030 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
13031 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
13032 /*Last=*/OMPC_LASTPRIVATE_unknown)
13033 << getOpenMPClauseName(OMPC_lastprivate);
13034 return nullptr;
13035 }
13036
Alexander Musman1bb328c2014-06-04 13:06:39 +000013037 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000013038 SmallVector<Expr *, 8> SrcExprs;
13039 SmallVector<Expr *, 8> DstExprs;
13040 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000013041 SmallVector<Decl *, 4> ExprCaptures;
13042 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000013043 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013044 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013045 SourceLocation ELoc;
13046 SourceRange ERange;
13047 Expr *SimpleRefExpr = RefExpr;
13048 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000013049 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013050 // It will be analyzed later.
13051 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013052 SrcExprs.push_back(nullptr);
13053 DstExprs.push_back(nullptr);
13054 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013055 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013056 ValueDecl *D = Res.first;
13057 if (!D)
13058 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013059
Alexey Bataev74caaf22016-02-20 04:09:36 +000013060 QualType Type = D->getType();
13061 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013062
13063 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
13064 // A variable that appears in a lastprivate clause must not have an
13065 // incomplete type or a reference type.
13066 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000013067 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000013068 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013069 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013070
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013071 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13072 // A variable that is privatized must not have a const-qualified type
13073 // unless it is of class type with a mutable member. This restriction does
13074 // not apply to the firstprivate clause.
13075 //
13076 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
13077 // A variable that appears in a lastprivate clause must not have a
13078 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013079 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013080 continue;
13081
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013082 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
13083 // A list item that appears in a lastprivate clause with the conditional
13084 // modifier must be a scalar variable.
13085 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
13086 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
13087 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13088 VarDecl::DeclarationOnly;
13089 Diag(D->getLocation(),
13090 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13091 << D;
13092 continue;
13093 }
13094
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013095 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013096 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13097 // in a Construct]
13098 // Variables with the predetermined data-sharing attributes may not be
13099 // listed in data-sharing attributes clauses, except for the cases
13100 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013101 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13102 // A list item may appear in a firstprivate or lastprivate clause but not
13103 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000013104 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013105 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000013106 (isOpenMPDistributeDirective(CurrDir) ||
13107 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000013108 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
13109 Diag(ELoc, diag::err_omp_wrong_dsa)
13110 << getOpenMPClauseName(DVar.CKind)
13111 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013112 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013113 continue;
13114 }
13115
Alexey Bataevf29276e2014-06-18 04:14:57 +000013116 // OpenMP [2.14.3.5, Restrictions, p.2]
13117 // A list item that is private within a parallel region, or that appears in
13118 // the reduction clause of a parallel construct, must not appear in a
13119 // lastprivate clause on a worksharing construct if any of the corresponding
13120 // worksharing regions ever binds to any of the corresponding parallel
13121 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000013122 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000013123 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013124 !isOpenMPParallelDirective(CurrDir) &&
13125 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000013126 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013127 if (DVar.CKind != OMPC_shared) {
13128 Diag(ELoc, diag::err_omp_required_access)
13129 << getOpenMPClauseName(OMPC_lastprivate)
13130 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013131 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013132 continue;
13133 }
13134 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013135
Alexander Musman1bb328c2014-06-04 13:06:39 +000013136 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000013137 // A variable of class type (or array thereof) that appears in a
13138 // lastprivate clause requires an accessible, unambiguous default
13139 // constructor for the class type, unless the list item is also specified
13140 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000013141 // A variable of class type (or array thereof) that appears in a
13142 // lastprivate clause requires an accessible, unambiguous copy assignment
13143 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000013144 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013145 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
13146 Type.getUnqualifiedType(), ".lastprivate.src",
13147 D->hasAttrs() ? &D->getAttrs() : nullptr);
13148 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000013149 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013150 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013151 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000013152 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013153 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000013154 // For arrays generate assignment operation for single element and replace
13155 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013156 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
13157 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013158 if (AssignmentOp.isInvalid())
13159 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013160 AssignmentOp =
13161 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000013162 if (AssignmentOp.isInvalid())
13163 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013164
Alexey Bataev74caaf22016-02-20 04:09:36 +000013165 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013166 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013167 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013168 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013169 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013170 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013171 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013172 ExprCaptures.push_back(Ref->getDecl());
13173 }
13174 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013175 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013176 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013177 ExprResult RefRes = DefaultLvalueConversion(Ref);
13178 if (!RefRes.isUsable())
13179 continue;
13180 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013181 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13182 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013183 if (!PostUpdateRes.isUsable())
13184 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013185 ExprPostUpdates.push_back(
13186 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013187 }
13188 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013189 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013190 Vars.push_back((VD || CurContext->isDependentContext())
13191 ? RefExpr->IgnoreParens()
13192 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000013193 SrcExprs.push_back(PseudoSrcExpr);
13194 DstExprs.push_back(PseudoDstExpr);
13195 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000013196 }
13197
13198 if (Vars.empty())
13199 return nullptr;
13200
13201 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000013202 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013203 LPKind, LPKindLoc, ColonLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013204 buildPreInits(Context, ExprCaptures),
13205 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000013206}
13207
Alexey Bataev758e55e2013-09-06 18:03:48 +000013208OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
13209 SourceLocation StartLoc,
13210 SourceLocation LParenLoc,
13211 SourceLocation EndLoc) {
13212 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013213 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013214 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013215 SourceLocation ELoc;
13216 SourceRange ERange;
13217 Expr *SimpleRefExpr = RefExpr;
13218 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013219 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000013220 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013221 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013222 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013223 ValueDecl *D = Res.first;
13224 if (!D)
13225 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013226
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013227 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013228 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13229 // in a Construct]
13230 // Variables with the predetermined data-sharing attributes may not be
13231 // listed in data-sharing attributes clauses, except for the cases
13232 // listed below. For these exceptions only, listing a predetermined
13233 // variable in a data-sharing attribute clause is allowed and overrides
13234 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000013235 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000013236 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
13237 DVar.RefExpr) {
13238 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13239 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013240 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013241 continue;
13242 }
13243
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013244 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013245 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000013246 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013247 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013248 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
13249 ? RefExpr->IgnoreParens()
13250 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013251 }
13252
Alexey Bataeved09d242014-05-28 05:53:51 +000013253 if (Vars.empty())
13254 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013255
13256 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13257}
13258
Alexey Bataevc5e02582014-06-16 07:08:35 +000013259namespace {
13260class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13261 DSAStackTy *Stack;
13262
13263public:
13264 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013265 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13266 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013267 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13268 return false;
13269 if (DVar.CKind != OMPC_unknown)
13270 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013271 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013272 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013273 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013274 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013275 }
13276 return false;
13277 }
13278 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013279 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013280 if (Child && Visit(Child))
13281 return true;
13282 }
13283 return false;
13284 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013285 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013286};
Alexey Bataev23b69422014-06-18 07:08:49 +000013287} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013288
Alexey Bataev60da77e2016-02-29 05:54:20 +000013289namespace {
13290// Transform MemberExpression for specified FieldDecl of current class to
13291// DeclRefExpr to specified OMPCapturedExprDecl.
13292class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13293 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013294 ValueDecl *Field = nullptr;
13295 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013296
13297public:
13298 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13299 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13300
13301 ExprResult TransformMemberExpr(MemberExpr *E) {
13302 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13303 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013304 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013305 return CapturedExpr;
13306 }
13307 return BaseTransform::TransformMemberExpr(E);
13308 }
13309 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13310};
13311} // namespace
13312
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013313template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013314static T filterLookupForUDReductionAndMapper(
13315 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013316 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013317 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013318 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013319 return Res;
13320 }
13321 }
13322 return T();
13323}
13324
Alexey Bataev43b90b72018-09-12 16:31:59 +000013325static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13326 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13327
13328 for (auto RD : D->redecls()) {
13329 // Don't bother with extra checks if we already know this one isn't visible.
13330 if (RD == D)
13331 continue;
13332
13333 auto ND = cast<NamedDecl>(RD);
13334 if (LookupResult::isVisible(SemaRef, ND))
13335 return ND;
13336 }
13337
13338 return nullptr;
13339}
13340
13341static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013342argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013343 SourceLocation Loc, QualType Ty,
13344 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13345 // Find all of the associated namespaces and classes based on the
13346 // arguments we have.
13347 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13348 Sema::AssociatedClassSet AssociatedClasses;
13349 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13350 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13351 AssociatedClasses);
13352
13353 // C++ [basic.lookup.argdep]p3:
13354 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13355 // and let Y be the lookup set produced by argument dependent
13356 // lookup (defined as follows). If X contains [...] then Y is
13357 // empty. Otherwise Y is the set of declarations found in the
13358 // namespaces associated with the argument types as described
13359 // below. The set of declarations found by the lookup of the name
13360 // is the union of X and Y.
13361 //
13362 // Here, we compute Y and add its members to the overloaded
13363 // candidate set.
13364 for (auto *NS : AssociatedNamespaces) {
13365 // When considering an associated namespace, the lookup is the
13366 // same as the lookup performed when the associated namespace is
13367 // used as a qualifier (3.4.3.2) except that:
13368 //
13369 // -- Any using-directives in the associated namespace are
13370 // ignored.
13371 //
13372 // -- Any namespace-scope friend functions declared in
13373 // associated classes are visible within their respective
13374 // namespaces even if they are not visible during an ordinary
13375 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013376 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013377 for (auto *D : R) {
13378 auto *Underlying = D;
13379 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13380 Underlying = USD->getTargetDecl();
13381
Michael Kruse4304e9d2019-02-19 16:38:20 +000013382 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13383 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013384 continue;
13385
13386 if (!SemaRef.isVisible(D)) {
13387 D = findAcceptableDecl(SemaRef, D);
13388 if (!D)
13389 continue;
13390 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13391 Underlying = USD->getTargetDecl();
13392 }
13393 Lookups.emplace_back();
13394 Lookups.back().addDecl(Underlying);
13395 }
13396 }
13397}
13398
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013399static ExprResult
13400buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13401 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13402 const DeclarationNameInfo &ReductionId, QualType Ty,
13403 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13404 if (ReductionIdScopeSpec.isInvalid())
13405 return ExprError();
13406 SmallVector<UnresolvedSet<8>, 4> Lookups;
13407 if (S) {
13408 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13409 Lookup.suppressDiagnostics();
13410 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013411 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013412 do {
13413 S = S->getParent();
13414 } while (S && !S->isDeclScope(D));
13415 if (S)
13416 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013417 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013418 Lookups.back().append(Lookup.begin(), Lookup.end());
13419 Lookup.clear();
13420 }
13421 } else if (auto *ULE =
13422 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13423 Lookups.push_back(UnresolvedSet<8>());
13424 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013425 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013426 if (D == PrevD)
13427 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013428 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013429 Lookups.back().addDecl(DRD);
13430 PrevD = D;
13431 }
13432 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013433 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13434 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013435 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013436 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013437 return !D->isInvalidDecl() &&
13438 (D->getType()->isDependentType() ||
13439 D->getType()->isInstantiationDependentType() ||
13440 D->getType()->containsUnexpandedParameterPack());
13441 })) {
13442 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013443 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013444 if (Set.empty())
13445 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013446 ResSet.append(Set.begin(), Set.end());
13447 // The last item marks the end of all declarations at the specified scope.
13448 ResSet.addDecl(Set[Set.size() - 1]);
13449 }
13450 return UnresolvedLookupExpr::Create(
13451 SemaRef.Context, /*NamingClass=*/nullptr,
13452 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13453 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13454 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013455 // Lookup inside the classes.
13456 // C++ [over.match.oper]p3:
13457 // For a unary operator @ with an operand of a type whose
13458 // cv-unqualified version is T1, and for a binary operator @ with
13459 // a left operand of a type whose cv-unqualified version is T1 and
13460 // a right operand of a type whose cv-unqualified version is T2,
13461 // three sets of candidate functions, designated member
13462 // candidates, non-member candidates and built-in candidates, are
13463 // constructed as follows:
13464 // -- If T1 is a complete class type or a class currently being
13465 // defined, the set of member candidates is the result of the
13466 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13467 // the set of member candidates is empty.
13468 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13469 Lookup.suppressDiagnostics();
13470 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13471 // Complete the type if it can be completed.
13472 // If the type is neither complete nor being defined, bail out now.
13473 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13474 TyRec->getDecl()->getDefinition()) {
13475 Lookup.clear();
13476 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13477 if (Lookup.empty()) {
13478 Lookups.emplace_back();
13479 Lookups.back().append(Lookup.begin(), Lookup.end());
13480 }
13481 }
13482 }
13483 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013484 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013485 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013486 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13487 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13488 if (!D->isInvalidDecl() &&
13489 SemaRef.Context.hasSameType(D->getType(), Ty))
13490 return D;
13491 return nullptr;
13492 }))
13493 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13494 VK_LValue, Loc);
13495 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013496 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13497 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13498 if (!D->isInvalidDecl() &&
13499 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13500 !Ty.isMoreQualifiedThan(D->getType()))
13501 return D;
13502 return nullptr;
13503 })) {
13504 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13505 /*DetectVirtual=*/false);
13506 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13507 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13508 VD->getType().getUnqualifiedType()))) {
13509 if (SemaRef.CheckBaseClassAccess(
13510 Loc, VD->getType(), Ty, Paths.front(),
13511 /*DiagID=*/0) != Sema::AR_inaccessible) {
13512 SemaRef.BuildBasePathArray(Paths, BasePath);
13513 return SemaRef.BuildDeclRefExpr(
13514 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13515 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013516 }
13517 }
13518 }
13519 }
13520 if (ReductionIdScopeSpec.isSet()) {
Alexey Bataevadd743b2020-01-03 11:58:16 -050013521 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
13522 << Ty << Range;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013523 return ExprError();
13524 }
13525 return ExprEmpty();
13526}
13527
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013528namespace {
13529/// Data for the reduction-based clauses.
13530struct ReductionData {
13531 /// List of original reduction items.
13532 SmallVector<Expr *, 8> Vars;
13533 /// List of private copies of the reduction items.
13534 SmallVector<Expr *, 8> Privates;
13535 /// LHS expressions for the reduction_op expressions.
13536 SmallVector<Expr *, 8> LHSs;
13537 /// RHS expressions for the reduction_op expressions.
13538 SmallVector<Expr *, 8> RHSs;
13539 /// Reduction operation expression.
13540 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013541 /// Taskgroup descriptors for the corresponding reduction items in
13542 /// in_reduction clauses.
13543 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013544 /// List of captures for clause.
13545 SmallVector<Decl *, 4> ExprCaptures;
13546 /// List of postupdate expressions.
13547 SmallVector<Expr *, 4> ExprPostUpdates;
13548 ReductionData() = delete;
13549 /// Reserves required memory for the reduction data.
13550 ReductionData(unsigned Size) {
13551 Vars.reserve(Size);
13552 Privates.reserve(Size);
13553 LHSs.reserve(Size);
13554 RHSs.reserve(Size);
13555 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013556 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013557 ExprCaptures.reserve(Size);
13558 ExprPostUpdates.reserve(Size);
13559 }
13560 /// Stores reduction item and reduction operation only (required for dependent
13561 /// reduction item).
13562 void push(Expr *Item, Expr *ReductionOp) {
13563 Vars.emplace_back(Item);
13564 Privates.emplace_back(nullptr);
13565 LHSs.emplace_back(nullptr);
13566 RHSs.emplace_back(nullptr);
13567 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013568 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013569 }
13570 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013571 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13572 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013573 Vars.emplace_back(Item);
13574 Privates.emplace_back(Private);
13575 LHSs.emplace_back(LHS);
13576 RHSs.emplace_back(RHS);
13577 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013578 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013579 }
13580};
13581} // namespace
13582
Alexey Bataeve3727102018-04-18 15:57:46 +000013583static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013584 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13585 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13586 const Expr *Length = OASE->getLength();
13587 if (Length == nullptr) {
13588 // For array sections of the form [1:] or [:], we would need to analyze
13589 // the lower bound...
13590 if (OASE->getColonLoc().isValid())
13591 return false;
13592
13593 // This is an array subscript which has implicit length 1!
13594 SingleElement = true;
13595 ArraySizes.push_back(llvm::APSInt::get(1));
13596 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013597 Expr::EvalResult Result;
13598 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013599 return false;
13600
Fangrui Song407659a2018-11-30 23:41:18 +000013601 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013602 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13603 ArraySizes.push_back(ConstantLengthValue);
13604 }
13605
13606 // Get the base of this array section and walk up from there.
13607 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13608
13609 // We require length = 1 for all array sections except the right-most to
13610 // guarantee that the memory region is contiguous and has no holes in it.
13611 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13612 Length = TempOASE->getLength();
13613 if (Length == nullptr) {
13614 // For array sections of the form [1:] or [:], we would need to analyze
13615 // the lower bound...
13616 if (OASE->getColonLoc().isValid())
13617 return false;
13618
13619 // This is an array subscript which has implicit length 1!
13620 ArraySizes.push_back(llvm::APSInt::get(1));
13621 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013622 Expr::EvalResult Result;
13623 if (!Length->EvaluateAsInt(Result, Context))
13624 return false;
13625
13626 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13627 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013628 return false;
13629
13630 ArraySizes.push_back(ConstantLengthValue);
13631 }
13632 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13633 }
13634
13635 // If we have a single element, we don't need to add the implicit lengths.
13636 if (!SingleElement) {
13637 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13638 // Has implicit length 1!
13639 ArraySizes.push_back(llvm::APSInt::get(1));
13640 Base = TempASE->getBase()->IgnoreParenImpCasts();
13641 }
13642 }
13643
13644 // This array section can be privatized as a single value or as a constant
13645 // sized array.
13646 return true;
13647}
13648
Alexey Bataeve3727102018-04-18 15:57:46 +000013649static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013650 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13651 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13652 SourceLocation ColonLoc, SourceLocation EndLoc,
13653 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013654 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013655 DeclarationName DN = ReductionId.getName();
13656 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013657 BinaryOperatorKind BOK = BO_Comma;
13658
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013659 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013660 // OpenMP [2.14.3.6, reduction clause]
13661 // C
13662 // reduction-identifier is either an identifier or one of the following
13663 // operators: +, -, *, &, |, ^, && and ||
13664 // C++
13665 // reduction-identifier is either an id-expression or one of the following
13666 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013667 switch (OOK) {
13668 case OO_Plus:
13669 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013670 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013671 break;
13672 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013673 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013674 break;
13675 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013676 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013677 break;
13678 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013679 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013680 break;
13681 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013682 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013683 break;
13684 case OO_AmpAmp:
13685 BOK = BO_LAnd;
13686 break;
13687 case OO_PipePipe:
13688 BOK = BO_LOr;
13689 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013690 case OO_New:
13691 case OO_Delete:
13692 case OO_Array_New:
13693 case OO_Array_Delete:
13694 case OO_Slash:
13695 case OO_Percent:
13696 case OO_Tilde:
13697 case OO_Exclaim:
13698 case OO_Equal:
13699 case OO_Less:
13700 case OO_Greater:
13701 case OO_LessEqual:
13702 case OO_GreaterEqual:
13703 case OO_PlusEqual:
13704 case OO_MinusEqual:
13705 case OO_StarEqual:
13706 case OO_SlashEqual:
13707 case OO_PercentEqual:
13708 case OO_CaretEqual:
13709 case OO_AmpEqual:
13710 case OO_PipeEqual:
13711 case OO_LessLess:
13712 case OO_GreaterGreater:
13713 case OO_LessLessEqual:
13714 case OO_GreaterGreaterEqual:
13715 case OO_EqualEqual:
13716 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013717 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013718 case OO_PlusPlus:
13719 case OO_MinusMinus:
13720 case OO_Comma:
13721 case OO_ArrowStar:
13722 case OO_Arrow:
13723 case OO_Call:
13724 case OO_Subscript:
13725 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013726 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013727 case NUM_OVERLOADED_OPERATORS:
13728 llvm_unreachable("Unexpected reduction identifier");
13729 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013730 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013731 if (II->isStr("max"))
13732 BOK = BO_GT;
13733 else if (II->isStr("min"))
13734 BOK = BO_LT;
13735 }
13736 break;
13737 }
13738 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013739 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013740 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013741 else
13742 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013743 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013744
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013745 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13746 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013747 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013748 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013749 // OpenMP [2.1, C/C++]
13750 // A list item is a variable or array section, subject to the restrictions
13751 // specified in Section 2.4 on page 42 and in each of the sections
13752 // describing clauses and directives for which a list appears.
13753 // OpenMP [2.14.3.3, Restrictions, p.1]
13754 // A variable that is part of another variable (as an array or
13755 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013756 if (!FirstIter && IR != ER)
13757 ++IR;
13758 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013759 SourceLocation ELoc;
13760 SourceRange ERange;
13761 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013762 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013763 /*AllowArraySection=*/true);
13764 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013765 // Try to find 'declare reduction' corresponding construct before using
13766 // builtin/overloaded operators.
13767 QualType Type = Context.DependentTy;
13768 CXXCastPath BasePath;
13769 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013770 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013771 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013772 Expr *ReductionOp = nullptr;
13773 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013774 (DeclareReductionRef.isUnset() ||
13775 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013776 ReductionOp = DeclareReductionRef.get();
13777 // It will be analyzed later.
13778 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013779 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013780 ValueDecl *D = Res.first;
13781 if (!D)
13782 continue;
13783
Alexey Bataev88202be2017-07-27 13:20:36 +000013784 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013785 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013786 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13787 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013788 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013789 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013790 } else if (OASE) {
13791 QualType BaseType =
13792 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13793 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013794 Type = ATy->getElementType();
13795 else
13796 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013797 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013798 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013799 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013800 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013801 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013802
Alexey Bataevc5e02582014-06-16 07:08:35 +000013803 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13804 // A variable that appears in a private clause must not have an incomplete
13805 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013806 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013807 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013808 continue;
13809 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013810 // A list item that appears in a reduction clause must not be
13811 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013812 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13813 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013814 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013815
13816 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013817 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13818 // If a list-item is a reference type then it must bind to the same object
13819 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013820 if (!ASE && !OASE) {
13821 if (VD) {
13822 VarDecl *VDDef = VD->getDefinition();
13823 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13824 DSARefChecker Check(Stack);
13825 if (Check.Visit(VDDef->getInit())) {
13826 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13827 << getOpenMPClauseName(ClauseKind) << ERange;
13828 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13829 continue;
13830 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013831 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013832 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013833
Alexey Bataevbc529672018-09-28 19:33:14 +000013834 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13835 // in a Construct]
13836 // Variables with the predetermined data-sharing attributes may not be
13837 // listed in data-sharing attributes clauses, except for the cases
13838 // listed below. For these exceptions only, listing a predetermined
13839 // variable in a data-sharing attribute clause is allowed and overrides
13840 // the variable's predetermined data-sharing attributes.
13841 // OpenMP [2.14.3.6, Restrictions, p.3]
13842 // Any number of reduction clauses can be specified on the directive,
13843 // but a list item can appear only once in the reduction clauses for that
13844 // directive.
13845 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13846 if (DVar.CKind == OMPC_reduction) {
13847 S.Diag(ELoc, diag::err_omp_once_referenced)
13848 << getOpenMPClauseName(ClauseKind);
13849 if (DVar.RefExpr)
13850 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13851 continue;
13852 }
13853 if (DVar.CKind != OMPC_unknown) {
13854 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13855 << getOpenMPClauseName(DVar.CKind)
13856 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013857 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013858 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013859 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013860
13861 // OpenMP [2.14.3.6, Restrictions, p.1]
13862 // A list item that appears in a reduction clause of a worksharing
13863 // construct must be shared in the parallel regions to which any of the
13864 // worksharing regions arising from the worksharing construct bind.
13865 if (isOpenMPWorksharingDirective(CurrDir) &&
13866 !isOpenMPParallelDirective(CurrDir) &&
13867 !isOpenMPTeamsDirective(CurrDir)) {
13868 DVar = Stack->getImplicitDSA(D, true);
13869 if (DVar.CKind != OMPC_shared) {
13870 S.Diag(ELoc, diag::err_omp_required_access)
13871 << getOpenMPClauseName(OMPC_reduction)
13872 << getOpenMPClauseName(OMPC_shared);
13873 reportOriginalDsa(S, Stack, D, DVar);
13874 continue;
13875 }
13876 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013877 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013878
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013879 // Try to find 'declare reduction' corresponding construct before using
13880 // builtin/overloaded operators.
13881 CXXCastPath BasePath;
13882 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013883 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013884 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13885 if (DeclareReductionRef.isInvalid())
13886 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013887 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013888 (DeclareReductionRef.isUnset() ||
13889 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013890 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013891 continue;
13892 }
13893 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13894 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013895 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013896 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013897 << Type << ReductionIdRange;
13898 continue;
13899 }
13900
13901 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13902 // The type of a list item that appears in a reduction clause must be valid
13903 // for the reduction-identifier. For a max or min reduction in C, the type
13904 // of the list item must be an allowed arithmetic data type: char, int,
13905 // float, double, or _Bool, possibly modified with long, short, signed, or
13906 // unsigned. For a max or min reduction in C++, the type of the list item
13907 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13908 // double, or bool, possibly modified with long, short, signed, or unsigned.
13909 if (DeclareReductionRef.isUnset()) {
13910 if ((BOK == BO_GT || BOK == BO_LT) &&
13911 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013912 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13913 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013914 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013915 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013916 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13917 VarDecl::DeclarationOnly;
13918 S.Diag(D->getLocation(),
13919 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013920 << D;
13921 }
13922 continue;
13923 }
13924 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013925 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013926 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13927 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013928 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013929 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13930 VarDecl::DeclarationOnly;
13931 S.Diag(D->getLocation(),
13932 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013933 << D;
13934 }
13935 continue;
13936 }
13937 }
13938
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013939 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013940 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13941 D->hasAttrs() ? &D->getAttrs() : nullptr);
13942 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13943 D->hasAttrs() ? &D->getAttrs() : nullptr);
13944 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013945
13946 // Try if we can determine constant lengths for all array sections and avoid
13947 // the VLA.
13948 bool ConstantLengthOASE = false;
13949 if (OASE) {
13950 bool SingleElement;
13951 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013952 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013953 Context, OASE, SingleElement, ArraySizes);
13954
13955 // If we don't have a single element, we must emit a constant array type.
13956 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013957 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013958 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13959 ArrayType::Normal,
13960 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013961 }
13962 }
13963
13964 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013965 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013966 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013967 if (!Context.getTargetInfo().isVLASupported()) {
13968 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13969 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13970 S.Diag(ELoc, diag::note_vla_unsupported);
13971 } else {
13972 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13973 S.targetDiag(ELoc, diag::note_vla_unsupported);
13974 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013975 continue;
13976 }
David Majnemer9d168222016-08-05 17:44:54 +000013977 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013978 // Create pseudo array type for private copy. The size for this array will
13979 // be generated during codegen.
13980 // For array subscripts or single variables Private Ty is the same as Type
13981 // (type of the variable or single array element).
13982 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013983 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013984 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013985 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013986 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013987 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013988 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013989 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013990 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013991 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013992 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13993 D->hasAttrs() ? &D->getAttrs() : nullptr,
13994 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013995 // Add initializer for private variable.
13996 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013997 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13998 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013999 if (DeclareReductionRef.isUsable()) {
14000 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
14001 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
14002 if (DRD->getInitializer()) {
14003 Init = DRDRef;
14004 RHSVD->setInit(DRDRef);
14005 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014006 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014007 } else {
14008 switch (BOK) {
14009 case BO_Add:
14010 case BO_Xor:
14011 case BO_Or:
14012 case BO_LOr:
14013 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
14014 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014015 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014016 break;
14017 case BO_Mul:
14018 case BO_LAnd:
14019 if (Type->isScalarType() || Type->isAnyComplexType()) {
14020 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014021 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000014022 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014023 break;
14024 case BO_And: {
14025 // '&' reduction op - initializer is '~0'.
14026 QualType OrigType = Type;
14027 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
14028 Type = ComplexTy->getElementType();
14029 if (Type->isRealFloatingType()) {
14030 llvm::APFloat InitValue =
14031 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
14032 /*isIEEE=*/true);
14033 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14034 Type, ELoc);
14035 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014036 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014037 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
14038 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
14039 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14040 }
14041 if (Init && OrigType->isAnyComplexType()) {
14042 // Init = 0xFFFF + 0xFFFFi;
14043 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014044 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014045 }
14046 Type = OrigType;
14047 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014048 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014049 case BO_LT:
14050 case BO_GT: {
14051 // 'min' reduction op - initializer is 'Largest representable number in
14052 // the reduction list item type'.
14053 // 'max' reduction op - initializer is 'Least representable number in
14054 // the reduction list item type'.
14055 if (Type->isIntegerType() || Type->isPointerType()) {
14056 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014057 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014058 QualType IntTy =
14059 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
14060 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014061 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
14062 : llvm::APInt::getMinValue(Size)
14063 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
14064 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014065 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14066 if (Type->isPointerType()) {
14067 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014068 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000014069 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014070 if (CastExpr.isInvalid())
14071 continue;
14072 Init = CastExpr.get();
14073 }
14074 } else if (Type->isRealFloatingType()) {
14075 llvm::APFloat InitValue = llvm::APFloat::getLargest(
14076 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
14077 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14078 Type, ELoc);
14079 }
14080 break;
14081 }
14082 case BO_PtrMemD:
14083 case BO_PtrMemI:
14084 case BO_MulAssign:
14085 case BO_Div:
14086 case BO_Rem:
14087 case BO_Sub:
14088 case BO_Shl:
14089 case BO_Shr:
14090 case BO_LE:
14091 case BO_GE:
14092 case BO_EQ:
14093 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000014094 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014095 case BO_AndAssign:
14096 case BO_XorAssign:
14097 case BO_OrAssign:
14098 case BO_Assign:
14099 case BO_AddAssign:
14100 case BO_SubAssign:
14101 case BO_DivAssign:
14102 case BO_RemAssign:
14103 case BO_ShlAssign:
14104 case BO_ShrAssign:
14105 case BO_Comma:
14106 llvm_unreachable("Unexpected reduction operation");
14107 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014108 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014109 if (Init && DeclareReductionRef.isUnset())
14110 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
14111 else if (!Init)
14112 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014113 if (RHSVD->isInvalidDecl())
14114 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000014115 if (!RHSVD->hasInit() &&
14116 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014117 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
14118 << Type << ReductionIdRange;
14119 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14120 VarDecl::DeclarationOnly;
14121 S.Diag(D->getLocation(),
14122 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000014123 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014124 continue;
14125 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014126 // Store initializer for single element in private copy. Will be used during
14127 // codegen.
14128 PrivateVD->setInit(RHSVD->getInit());
14129 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000014130 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014131 ExprResult ReductionOp;
14132 if (DeclareReductionRef.isUsable()) {
14133 QualType RedTy = DeclareReductionRef.get()->getType();
14134 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014135 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
14136 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014137 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014138 LHS = S.DefaultLvalueConversion(LHS.get());
14139 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014140 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14141 CK_UncheckedDerivedToBase, LHS.get(),
14142 &BasePath, LHS.get()->getValueKind());
14143 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14144 CK_UncheckedDerivedToBase, RHS.get(),
14145 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014146 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014147 FunctionProtoType::ExtProtoInfo EPI;
14148 QualType Params[] = {PtrRedTy, PtrRedTy};
14149 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
14150 auto *OVE = new (Context) OpaqueValueExpr(
14151 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014152 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014153 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000014154 ReductionOp =
14155 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014156 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014157 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014158 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014159 if (ReductionOp.isUsable()) {
14160 if (BOK != BO_LT && BOK != BO_GT) {
14161 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014162 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014163 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014164 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000014165 auto *ConditionalOp = new (Context)
14166 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
14167 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014168 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014169 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014170 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014171 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014172 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014173 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
14174 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014175 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014176 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014177 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000014178 }
14179
Alexey Bataevfa312f32017-07-21 18:48:21 +000014180 // OpenMP [2.15.4.6, Restrictions, p.2]
14181 // A list item that appears in an in_reduction clause of a task construct
14182 // must appear in a task_reduction clause of a construct associated with a
14183 // taskgroup region that includes the participating task in its taskgroup
14184 // set. The construct associated with the innermost region that meets this
14185 // condition must specify the same reduction-identifier as the in_reduction
14186 // clause.
14187 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000014188 SourceRange ParentSR;
14189 BinaryOperatorKind ParentBOK;
14190 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000014191 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000014192 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014193 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
14194 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014195 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014196 Stack->getTopMostTaskgroupReductionData(
14197 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014198 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
14199 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
14200 if (!IsParentBOK && !IsParentReductionOp) {
14201 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
14202 continue;
14203 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000014204 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
14205 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
14206 IsParentReductionOp) {
14207 bool EmitError = true;
14208 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
14209 llvm::FoldingSetNodeID RedId, ParentRedId;
14210 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
14211 DeclareReductionRef.get()->Profile(RedId, Context,
14212 /*Canonical=*/true);
14213 EmitError = RedId != ParentRedId;
14214 }
14215 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014216 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000014217 diag::err_omp_reduction_identifier_mismatch)
14218 << ReductionIdRange << RefExpr->getSourceRange();
14219 S.Diag(ParentSR.getBegin(),
14220 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000014221 << ParentSR
14222 << (IsParentBOK ? ParentBOKDSA.RefExpr
14223 : ParentReductionOpDSA.RefExpr)
14224 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000014225 continue;
14226 }
14227 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014228 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
14229 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000014230 }
14231
Alexey Bataev60da77e2016-02-29 05:54:20 +000014232 DeclRefExpr *Ref = nullptr;
14233 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014234 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014235 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014236 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000014237 VarsExpr =
14238 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
14239 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000014240 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014241 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014242 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014243 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014244 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014245 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014246 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014247 if (!RefRes.isUsable())
14248 continue;
14249 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014250 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14251 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014252 if (!PostUpdateRes.isUsable())
14253 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014254 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14255 Stack->getCurrentDirective() == OMPD_taskgroup) {
14256 S.Diag(RefExpr->getExprLoc(),
14257 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014258 << RefExpr->getSourceRange();
14259 continue;
14260 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014261 RD.ExprPostUpdates.emplace_back(
14262 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014263 }
14264 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014265 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014266 // All reduction items are still marked as reduction (to do not increase
14267 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014268 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014269 if (CurrDir == OMPD_taskgroup) {
14270 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014271 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14272 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014273 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014274 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014275 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014276 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14277 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014278 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014279 return RD.Vars.empty();
14280}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014281
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014282OMPClause *Sema::ActOnOpenMPReductionClause(
14283 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14284 SourceLocation ColonLoc, SourceLocation EndLoc,
14285 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14286 ArrayRef<Expr *> UnresolvedReductions) {
14287 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014288 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014289 StartLoc, LParenLoc, ColonLoc, EndLoc,
14290 ReductionIdScopeSpec, ReductionId,
14291 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014292 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014293
Alexey Bataevc5e02582014-06-16 07:08:35 +000014294 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014295 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14296 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14297 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14298 buildPreInits(Context, RD.ExprCaptures),
14299 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014300}
14301
Alexey Bataev169d96a2017-07-18 20:17:46 +000014302OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14303 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14304 SourceLocation ColonLoc, SourceLocation EndLoc,
14305 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14306 ArrayRef<Expr *> UnresolvedReductions) {
14307 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014308 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14309 StartLoc, LParenLoc, ColonLoc, EndLoc,
14310 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014311 UnresolvedReductions, RD))
14312 return nullptr;
14313
14314 return OMPTaskReductionClause::Create(
14315 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14316 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14317 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14318 buildPreInits(Context, RD.ExprCaptures),
14319 buildPostUpdate(*this, RD.ExprPostUpdates));
14320}
14321
Alexey Bataevfa312f32017-07-21 18:48:21 +000014322OMPClause *Sema::ActOnOpenMPInReductionClause(
14323 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14324 SourceLocation ColonLoc, SourceLocation EndLoc,
14325 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14326 ArrayRef<Expr *> UnresolvedReductions) {
14327 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014328 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014329 StartLoc, LParenLoc, ColonLoc, EndLoc,
14330 ReductionIdScopeSpec, ReductionId,
14331 UnresolvedReductions, RD))
14332 return nullptr;
14333
14334 return OMPInReductionClause::Create(
14335 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14336 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014337 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014338 buildPreInits(Context, RD.ExprCaptures),
14339 buildPostUpdate(*this, RD.ExprPostUpdates));
14340}
14341
Alexey Bataevecba70f2016-04-12 11:02:11 +000014342bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14343 SourceLocation LinLoc) {
14344 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14345 LinKind == OMPC_LINEAR_unknown) {
14346 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14347 return true;
14348 }
14349 return false;
14350}
14351
Alexey Bataeve3727102018-04-18 15:57:46 +000014352bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014353 OpenMPLinearClauseKind LinKind,
14354 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014355 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014356 // A variable must not have an incomplete type or a reference type.
14357 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14358 return true;
14359 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14360 !Type->isReferenceType()) {
14361 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14362 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14363 return true;
14364 }
14365 Type = Type.getNonReferenceType();
14366
Joel E. Dennybae586f2019-01-04 22:12:13 +000014367 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14368 // A variable that is privatized must not have a const-qualified type
14369 // unless it is of class type with a mutable member. This restriction does
14370 // not apply to the firstprivate clause.
14371 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014372 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014373
14374 // A list item must be of integral or pointer type.
14375 Type = Type.getUnqualifiedType().getCanonicalType();
14376 const auto *Ty = Type.getTypePtrOrNull();
Alexey Bataev3f2e3dc2020-01-07 09:26:10 -050014377 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
14378 !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
Alexey Bataevecba70f2016-04-12 11:02:11 +000014379 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14380 if (D) {
14381 bool IsDecl =
14382 !VD ||
14383 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14384 Diag(D->getLocation(),
14385 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14386 << D;
14387 }
14388 return true;
14389 }
14390 return false;
14391}
14392
Alexey Bataev182227b2015-08-20 10:54:39 +000014393OMPClause *Sema::ActOnOpenMPLinearClause(
14394 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14395 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14396 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014397 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014398 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014399 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014400 SmallVector<Decl *, 4> ExprCaptures;
14401 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014402 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014403 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014404 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014405 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014406 SourceLocation ELoc;
14407 SourceRange ERange;
14408 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014409 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014410 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014411 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014412 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014413 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014414 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014415 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014416 ValueDecl *D = Res.first;
14417 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014418 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014419
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014420 QualType Type = D->getType();
14421 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014422
14423 // OpenMP [2.14.3.7, linear clause]
14424 // A list-item cannot appear in more than one linear clause.
14425 // A list-item that appears in a linear clause cannot appear in any
14426 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014427 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014428 if (DVar.RefExpr) {
14429 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14430 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014431 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014432 continue;
14433 }
14434
Alexey Bataevecba70f2016-04-12 11:02:11 +000014435 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014436 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014437 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014438
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014439 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014440 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014441 buildVarDecl(*this, ELoc, Type, D->getName(),
14442 D->hasAttrs() ? &D->getAttrs() : nullptr,
14443 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014444 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014445 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014446 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014447 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014448 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014449 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014450 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014451 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014452 ExprCaptures.push_back(Ref->getDecl());
14453 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14454 ExprResult RefRes = DefaultLvalueConversion(Ref);
14455 if (!RefRes.isUsable())
14456 continue;
14457 ExprResult PostUpdateRes =
14458 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14459 SimpleRefExpr, RefRes.get());
14460 if (!PostUpdateRes.isUsable())
14461 continue;
14462 ExprPostUpdates.push_back(
14463 IgnoredValueConversions(PostUpdateRes.get()).get());
14464 }
14465 }
14466 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014467 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014468 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014469 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014470 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014471 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014472 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014473 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014474
14475 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014476 Vars.push_back((VD || CurContext->isDependentContext())
14477 ? RefExpr->IgnoreParens()
14478 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014479 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014480 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014481 }
14482
14483 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014484 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014485
14486 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014487 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014488 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14489 !Step->isInstantiationDependent() &&
14490 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014491 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014492 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014493 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014494 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014495 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014496
Alexander Musman3276a272015-03-21 10:12:56 +000014497 // Build var to save the step value.
14498 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014499 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014500 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014501 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014502 ExprResult CalcStep =
14503 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014504 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014505
Alexander Musman8dba6642014-04-22 13:09:42 +000014506 // Warn about zero linear step (it would be probably better specified as
14507 // making corresponding variables 'const').
14508 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014509 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14510 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014511 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14512 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014513 if (!IsConstant && CalcStep.isUsable()) {
14514 // Calculate the step beforehand instead of doing this on each iteration.
14515 // (This is not used if the number of iterations may be kfold-ed).
14516 CalcStepExpr = CalcStep.get();
14517 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014518 }
14519
Alexey Bataev182227b2015-08-20 10:54:39 +000014520 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14521 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014522 StepExpr, CalcStepExpr,
14523 buildPreInits(Context, ExprCaptures),
14524 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014525}
14526
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014527static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14528 Expr *NumIterations, Sema &SemaRef,
14529 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014530 // Walk the vars and build update/final expressions for the CodeGen.
14531 SmallVector<Expr *, 8> Updates;
14532 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014533 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014534 Expr *Step = Clause.getStep();
14535 Expr *CalcStep = Clause.getCalcStep();
14536 // OpenMP [2.14.3.7, linear clause]
14537 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014538 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014539 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014540 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014541 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14542 bool HasErrors = false;
14543 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014544 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014545 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14546 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014547 SourceLocation ELoc;
14548 SourceRange ERange;
14549 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014550 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014551 ValueDecl *D = Res.first;
14552 if (Res.second || !D) {
14553 Updates.push_back(nullptr);
14554 Finals.push_back(nullptr);
14555 HasErrors = true;
14556 continue;
14557 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014558 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014559 // OpenMP [2.15.11, distribute simd Construct]
14560 // A list item may not appear in a linear clause, unless it is the loop
14561 // iteration variable.
14562 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14563 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14564 SemaRef.Diag(ELoc,
14565 diag::err_omp_linear_distribute_var_non_loop_iteration);
14566 Updates.push_back(nullptr);
14567 Finals.push_back(nullptr);
14568 HasErrors = true;
14569 continue;
14570 }
Alexander Musman3276a272015-03-21 10:12:56 +000014571 Expr *InitExpr = *CurInit;
14572
14573 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014574 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014575 Expr *CapturedRef;
14576 if (LinKind == OMPC_LINEAR_uval)
14577 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14578 else
14579 CapturedRef =
14580 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14581 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14582 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014583
14584 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014585 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014586 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014587 Update = buildCounterUpdate(
14588 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14589 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014590 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014591 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014592 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014593 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014594
14595 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014596 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014597 if (!Info.first)
14598 Final =
14599 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014600 InitExpr, NumIterations, Step, /*Subtract=*/false,
14601 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014602 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014603 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014604 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014605 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014606
Alexander Musman3276a272015-03-21 10:12:56 +000014607 if (!Update.isUsable() || !Final.isUsable()) {
14608 Updates.push_back(nullptr);
14609 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014610 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014611 HasErrors = true;
14612 } else {
14613 Updates.push_back(Update.get());
14614 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014615 if (!Info.first)
14616 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014617 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014618 ++CurInit;
14619 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014620 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014621 if (Expr *S = Clause.getStep())
14622 UsedExprs.push_back(S);
14623 // Fill the remaining part with the nullptr.
14624 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014625 Clause.setUpdates(Updates);
14626 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014627 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014628 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014629}
14630
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014631OMPClause *Sema::ActOnOpenMPAlignedClause(
14632 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14633 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014634 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014635 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014636 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14637 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 Bataev1efd1662016-03-29 10:59:56 +000014641 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014642 // It will be analyzed later.
14643 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014644 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014645 ValueDecl *D = Res.first;
14646 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014647 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014648
Alexey Bataev1efd1662016-03-29 10:59:56 +000014649 QualType QType = D->getType();
14650 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014651
14652 // OpenMP [2.8.1, simd construct, Restrictions]
14653 // The type of list items appearing in the aligned clause must be
14654 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014655 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014656 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014657 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014658 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014659 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014660 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014661 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014662 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014663 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014664 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014665 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014666 continue;
14667 }
14668
14669 // OpenMP [2.8.1, simd construct, Restrictions]
14670 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014671 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevb6e70842019-12-16 15:54:17 -050014672 Diag(ELoc, diag::err_omp_used_in_clause_twice)
14673 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014674 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14675 << getOpenMPClauseName(OMPC_aligned);
14676 continue;
14677 }
14678
Alexey Bataev1efd1662016-03-29 10:59:56 +000014679 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014680 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014681 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14682 Vars.push_back(DefaultFunctionArrayConversion(
14683 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14684 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014685 }
14686
14687 // OpenMP [2.8.1, simd construct, Description]
14688 // The parameter of the aligned clause, alignment, must be a constant
14689 // positive integer expression.
14690 // If no optional parameter is specified, implementation-defined default
14691 // alignments for SIMD instructions on the target platforms are assumed.
14692 if (Alignment != nullptr) {
14693 ExprResult AlignResult =
14694 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14695 if (AlignResult.isInvalid())
14696 return nullptr;
14697 Alignment = AlignResult.get();
14698 }
14699 if (Vars.empty())
14700 return nullptr;
14701
14702 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14703 EndLoc, Vars, Alignment);
14704}
14705
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014706OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14707 SourceLocation StartLoc,
14708 SourceLocation LParenLoc,
14709 SourceLocation EndLoc) {
14710 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014711 SmallVector<Expr *, 8> SrcExprs;
14712 SmallVector<Expr *, 8> DstExprs;
14713 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014714 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014715 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14716 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014717 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014718 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014719 SrcExprs.push_back(nullptr);
14720 DstExprs.push_back(nullptr);
14721 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014722 continue;
14723 }
14724
Alexey Bataeved09d242014-05-28 05:53:51 +000014725 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014726 // OpenMP [2.1, C/C++]
14727 // A list item is a variable name.
14728 // OpenMP [2.14.4.1, Restrictions, p.1]
14729 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014730 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014731 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014732 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14733 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014734 continue;
14735 }
14736
14737 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014738 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014739
14740 QualType Type = VD->getType();
14741 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14742 // It will be analyzed later.
14743 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014744 SrcExprs.push_back(nullptr);
14745 DstExprs.push_back(nullptr);
14746 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014747 continue;
14748 }
14749
14750 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14751 // A list item that appears in a copyin clause must be threadprivate.
14752 if (!DSAStack->isThreadPrivate(VD)) {
14753 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014754 << getOpenMPClauseName(OMPC_copyin)
14755 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014756 continue;
14757 }
14758
14759 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14760 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014761 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014762 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014763 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14764 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014765 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014766 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014767 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014768 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014769 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014770 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014771 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014772 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014773 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014774 // For arrays generate assignment operation for single element and replace
14775 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014776 ExprResult AssignmentOp =
14777 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14778 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014779 if (AssignmentOp.isInvalid())
14780 continue;
14781 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014782 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014783 if (AssignmentOp.isInvalid())
14784 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014785
14786 DSAStack->addDSA(VD, DE, OMPC_copyin);
14787 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014788 SrcExprs.push_back(PseudoSrcExpr);
14789 DstExprs.push_back(PseudoDstExpr);
14790 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014791 }
14792
Alexey Bataeved09d242014-05-28 05:53:51 +000014793 if (Vars.empty())
14794 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014795
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014796 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14797 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014798}
14799
Alexey Bataevbae9a792014-06-27 10:37:06 +000014800OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14801 SourceLocation StartLoc,
14802 SourceLocation LParenLoc,
14803 SourceLocation EndLoc) {
14804 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014805 SmallVector<Expr *, 8> SrcExprs;
14806 SmallVector<Expr *, 8> DstExprs;
14807 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014808 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014809 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14810 SourceLocation ELoc;
14811 SourceRange ERange;
14812 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014813 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014814 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014815 // It will be analyzed later.
14816 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014817 SrcExprs.push_back(nullptr);
14818 DstExprs.push_back(nullptr);
14819 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014820 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014821 ValueDecl *D = Res.first;
14822 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014823 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014824
Alexey Bataeve122da12016-03-17 10:50:17 +000014825 QualType Type = D->getType();
14826 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014827
14828 // OpenMP [2.14.4.2, Restrictions, p.2]
14829 // A list item that appears in a copyprivate clause may not appear in a
14830 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014831 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014832 DSAStackTy::DSAVarData DVar =
14833 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014834 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14835 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014836 Diag(ELoc, diag::err_omp_wrong_dsa)
14837 << getOpenMPClauseName(DVar.CKind)
14838 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014839 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014840 continue;
14841 }
14842
14843 // OpenMP [2.11.4.2, Restrictions, p.1]
14844 // All list items that appear in a copyprivate clause must be either
14845 // threadprivate or private in the enclosing context.
14846 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014847 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014848 if (DVar.CKind == OMPC_shared) {
14849 Diag(ELoc, diag::err_omp_required_access)
14850 << getOpenMPClauseName(OMPC_copyprivate)
14851 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014852 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014853 continue;
14854 }
14855 }
14856 }
14857
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014858 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014859 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014860 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014861 << getOpenMPClauseName(OMPC_copyprivate) << Type
14862 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014863 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014864 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014865 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014866 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014867 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014868 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014869 continue;
14870 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014871
Alexey Bataevbae9a792014-06-27 10:37:06 +000014872 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14873 // A variable of class type (or array thereof) that appears in a
14874 // copyin clause requires an accessible, unambiguous copy assignment
14875 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014876 Type = Context.getBaseElementType(Type.getNonReferenceType())
14877 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014878 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014879 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014880 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014881 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14882 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014883 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014884 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014885 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14886 ExprResult AssignmentOp = BuildBinOp(
14887 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014888 if (AssignmentOp.isInvalid())
14889 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014890 AssignmentOp =
14891 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014892 if (AssignmentOp.isInvalid())
14893 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014894
14895 // No need to mark vars as copyprivate, they are already threadprivate or
14896 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014897 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014898 Vars.push_back(
14899 VD ? RefExpr->IgnoreParens()
14900 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014901 SrcExprs.push_back(PseudoSrcExpr);
14902 DstExprs.push_back(PseudoDstExpr);
14903 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014904 }
14905
14906 if (Vars.empty())
14907 return nullptr;
14908
Alexey Bataeva63048e2015-03-23 06:18:07 +000014909 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14910 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014911}
14912
Alexey Bataev6125da92014-07-21 11:26:11 +000014913OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14914 SourceLocation StartLoc,
14915 SourceLocation LParenLoc,
14916 SourceLocation EndLoc) {
14917 if (VarList.empty())
14918 return nullptr;
14919
14920 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14921}
Alexey Bataevdea47612014-07-23 07:46:59 +000014922
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014923OMPClause *
14924Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14925 SourceLocation DepLoc, SourceLocation ColonLoc,
14926 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14927 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014928 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014929 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014930 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014931 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014932 return nullptr;
14933 }
14934 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014935 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14936 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014937 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014938 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014939 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14940 /*Last=*/OMPC_DEPEND_unknown, Except)
14941 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014942 return nullptr;
14943 }
14944 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014945 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014946 llvm::APSInt DepCounter(/*BitWidth=*/32);
14947 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014948 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14949 if (const Expr *OrderedCountExpr =
14950 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014951 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14952 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014953 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014954 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014955 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014956 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14957 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14958 // It will be analyzed later.
14959 Vars.push_back(RefExpr);
14960 continue;
14961 }
14962
14963 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014964 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014965 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014966 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014967 DepCounter >= TotalDepCount) {
14968 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14969 continue;
14970 }
14971 ++DepCounter;
14972 // OpenMP [2.13.9, Summary]
14973 // depend(dependence-type : vec), where dependence-type is:
14974 // 'sink' and where vec is the iteration vector, which has the form:
14975 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14976 // where n is the value specified by the ordered clause in the loop
14977 // directive, xi denotes the loop iteration variable of the i-th nested
14978 // loop associated with the loop directive, and di is a constant
14979 // non-negative integer.
14980 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014981 // It will be analyzed later.
14982 Vars.push_back(RefExpr);
14983 continue;
14984 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014985 SimpleExpr = SimpleExpr->IgnoreImplicit();
14986 OverloadedOperatorKind OOK = OO_None;
14987 SourceLocation OOLoc;
14988 Expr *LHS = SimpleExpr;
14989 Expr *RHS = nullptr;
14990 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14991 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14992 OOLoc = BO->getOperatorLoc();
14993 LHS = BO->getLHS()->IgnoreParenImpCasts();
14994 RHS = BO->getRHS()->IgnoreParenImpCasts();
14995 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14996 OOK = OCE->getOperator();
14997 OOLoc = OCE->getOperatorLoc();
14998 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14999 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
15000 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
15001 OOK = MCE->getMethodDecl()
15002 ->getNameInfo()
15003 .getName()
15004 .getCXXOverloadedOperator();
15005 OOLoc = MCE->getCallee()->getExprLoc();
15006 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
15007 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015008 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015009 SourceLocation ELoc;
15010 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000015011 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015012 if (Res.second) {
15013 // It will be analyzed later.
15014 Vars.push_back(RefExpr);
15015 }
15016 ValueDecl *D = Res.first;
15017 if (!D)
15018 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015019
Alexey Bataev17daedf2018-02-15 22:42:57 +000015020 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
15021 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
15022 continue;
15023 }
15024 if (RHS) {
15025 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
15026 RHS, OMPC_depend, /*StrictlyPositive=*/false);
15027 if (RHSRes.isInvalid())
15028 continue;
15029 }
15030 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015031 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015032 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015033 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000015034 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000015035 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000015036 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
15037 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000015038 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000015039 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000015040 continue;
15041 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015042 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015043 } else {
Kelvin Li427ffa22020-01-03 11:55:37 -050015044 // OpenMP 5.0 [2.17.11, Restrictions]
15045 // List items used in depend clauses cannot be zero-length array sections.
15046 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
15047 if (OASE) {
15048 const Expr *Length = OASE->getLength();
15049 Expr::EvalResult Result;
15050 if (Length && !Length->isValueDependent() &&
15051 Length->EvaluateAsInt(Result, Context) &&
15052 Result.Val.getInt().isNullValue()) {
15053 Diag(ELoc,
15054 diag::err_omp_depend_zero_length_array_section_not_allowed)
15055 << SimpleExpr->getSourceRange();
15056 continue;
15057 }
15058 }
15059
Alexey Bataev17daedf2018-02-15 22:42:57 +000015060 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
15061 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
15062 (ASE &&
15063 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
15064 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
15065 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15066 << RefExpr->getSourceRange();
15067 continue;
15068 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000015069
15070 ExprResult Res;
15071 {
15072 Sema::TentativeAnalysisScope Trap(*this);
15073 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
15074 RefExpr->IgnoreParenImpCasts());
15075 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015076 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
15077 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15078 << RefExpr->getSourceRange();
15079 continue;
15080 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015081 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015082 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015083 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015084
15085 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
15086 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015087 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015088 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
15089 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
15090 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
15091 }
15092 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
15093 Vars.empty())
15094 return nullptr;
15095
Alexey Bataev8b427062016-05-25 12:36:08 +000015096 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000015097 DepKind, DepLoc, ColonLoc, Vars,
15098 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000015099 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
15100 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000015101 DSAStack->addDoacrossDependClause(C, OpsOffs);
15102 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015103}
Michael Wonge710d542015-08-07 16:16:36 +000015104
15105OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
15106 SourceLocation LParenLoc,
15107 SourceLocation EndLoc) {
15108 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015109 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000015110
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015111 // OpenMP [2.9.1, Restrictions]
15112 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015113 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000015114 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015115 return nullptr;
15116
Alexey Bataev931e19b2017-10-02 16:32:39 +000015117 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015118 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050015119 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000015120 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015121 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015122 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015123 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15124 HelperValStmt = buildPreInits(Context, Captures);
15125 }
15126
Alexey Bataev8451efa2018-01-15 19:06:12 +000015127 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
15128 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000015129}
Kelvin Li0bff7af2015-11-23 05:32:03 +000015130
Alexey Bataeve3727102018-04-18 15:57:46 +000015131static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000015132 DSAStackTy *Stack, QualType QTy,
15133 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000015134 NamedDecl *ND;
15135 if (QTy->isIncompleteType(&ND)) {
15136 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
15137 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015138 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000015139 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
Jonas Hahnfeld071dca22019-12-07 13:31:46 +010015140 !QTy.isTriviallyCopyableType(SemaRef.Context))
Alexey Bataev95c23e72018-02-27 21:31:11 +000015141 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015142 return true;
15143}
15144
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000015145/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015146/// (array section or array subscript) does NOT specify the whole size of the
15147/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015148static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015149 const Expr *E,
15150 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015151 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015152
15153 // If this is an array subscript, it refers to the whole size if the size of
15154 // the dimension is constant and equals 1. Also, an array section assumes the
15155 // format of an array subscript if no colon is used.
15156 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015157 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015158 return ATy->getSize().getSExtValue() != 1;
15159 // Size can't be evaluated statically.
15160 return false;
15161 }
15162
15163 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015164 const Expr *LowerBound = OASE->getLowerBound();
15165 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015166
15167 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000015168 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015169 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000015170 Expr::EvalResult Result;
15171 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015172 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000015173
15174 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015175 if (ConstLowerBound.getSExtValue())
15176 return true;
15177 }
15178
15179 // If we don't have a length we covering the whole dimension.
15180 if (!Length)
15181 return false;
15182
15183 // If the base is a pointer, we don't have a way to get the size of the
15184 // pointee.
15185 if (BaseQTy->isPointerType())
15186 return false;
15187
15188 // We can only check if the length is the same as the size of the dimension
15189 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000015190 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015191 if (!CATy)
15192 return false;
15193
Fangrui Song407659a2018-11-30 23:41:18 +000015194 Expr::EvalResult Result;
15195 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015196 return false; // Can't get the integer value as a constant.
15197
Fangrui Song407659a2018-11-30 23:41:18 +000015198 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015199 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
15200}
15201
15202// Return true if it can be proven that the provided array expression (array
15203// section or array subscript) does NOT specify a single element of the array
15204// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015205static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000015206 const Expr *E,
15207 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015208 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015209
15210 // An array subscript always refer to a single element. Also, an array section
15211 // assumes the format of an array subscript if no colon is used.
15212 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
15213 return false;
15214
15215 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015216 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015217
15218 // If we don't have a length we have to check if the array has unitary size
15219 // for this dimension. Also, we should always expect a length if the base type
15220 // is pointer.
15221 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015222 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015223 return ATy->getSize().getSExtValue() != 1;
15224 // We cannot assume anything.
15225 return false;
15226 }
15227
15228 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000015229 Expr::EvalResult Result;
15230 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015231 return false; // Can't get the integer value as a constant.
15232
Fangrui Song407659a2018-11-30 23:41:18 +000015233 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015234 return ConstLength.getSExtValue() != 1;
15235}
15236
Samuel Antao661c0902016-05-26 17:39:58 +000015237// Return the expression of the base of the mappable expression or null if it
15238// cannot be determined and do all the necessary checks to see if the expression
15239// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000015240// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015241static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000015242 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000015243 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015244 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015245 SourceLocation ELoc = E->getExprLoc();
15246 SourceRange ERange = E->getSourceRange();
15247
15248 // The base of elements of list in a map clause have to be either:
15249 // - a reference to variable or field.
15250 // - a member expression.
15251 // - an array expression.
15252 //
15253 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
15254 // reference to 'r'.
15255 //
15256 // If we have:
15257 //
15258 // struct SS {
15259 // Bla S;
15260 // foo() {
15261 // #pragma omp target map (S.Arr[:12]);
15262 // }
15263 // }
15264 //
15265 // We want to retrieve the member expression 'this->S';
15266
Alexey Bataeve3727102018-04-18 15:57:46 +000015267 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015268
Samuel Antao5de996e2016-01-22 20:21:36 +000015269 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15270 // If a list item is an array section, it must specify contiguous storage.
15271 //
15272 // For this restriction it is sufficient that we make sure only references
15273 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015274 // exist except in the rightmost expression (unless they cover the whole
15275 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015276 //
15277 // r.ArrS[3:5].Arr[6:7]
15278 //
15279 // r.ArrS[3:5].x
15280 //
15281 // but these would be valid:
15282 // r.ArrS[3].Arr[6:7]
15283 //
15284 // r.ArrS[3].x
15285
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015286 bool AllowUnitySizeArraySection = true;
15287 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015288
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015289 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015290 E = E->IgnoreParenImpCasts();
15291
15292 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15293 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015294 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015295
15296 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015297
15298 // If we got a reference to a declaration, we should not expect any array
15299 // section before that.
15300 AllowUnitySizeArraySection = false;
15301 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015302
15303 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015304 CurComponents.emplace_back(CurE, CurE->getDecl());
15305 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015306 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015307
15308 if (isa<CXXThisExpr>(BaseE))
15309 // We found a base expression: this->Val.
15310 RelevantExpr = CurE;
15311 else
15312 E = BaseE;
15313
15314 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015315 if (!NoDiagnose) {
15316 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15317 << CurE->getSourceRange();
15318 return nullptr;
15319 }
15320 if (RelevantExpr)
15321 return nullptr;
15322 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015323 }
15324
15325 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15326
15327 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15328 // A bit-field cannot appear in a map clause.
15329 //
15330 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015331 if (!NoDiagnose) {
15332 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15333 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15334 return nullptr;
15335 }
15336 if (RelevantExpr)
15337 return nullptr;
15338 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015339 }
15340
15341 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15342 // If the type of a list item is a reference to a type T then the type
15343 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015344 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015345
15346 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15347 // A list item cannot be a variable that is a member of a structure with
15348 // a union type.
15349 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015350 if (CurType->isUnionType()) {
15351 if (!NoDiagnose) {
15352 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15353 << CurE->getSourceRange();
15354 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015355 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015356 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015357 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015358
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015359 // If we got a member expression, we should not expect any array section
15360 // before that:
15361 //
15362 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15363 // If a list item is an element of a structure, only the rightmost symbol
15364 // of the variable reference can be an array section.
15365 //
15366 AllowUnitySizeArraySection = false;
15367 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015368
15369 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015370 CurComponents.emplace_back(CurE, FD);
15371 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015372 E = CurE->getBase()->IgnoreParenImpCasts();
15373
15374 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015375 if (!NoDiagnose) {
15376 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15377 << 0 << CurE->getSourceRange();
15378 return nullptr;
15379 }
15380 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015381 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015382
15383 // If we got an array subscript that express the whole dimension we
15384 // can have any array expressions before. If it only expressing part of
15385 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015386 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015387 E->getType()))
15388 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015389
Patrick Lystere13b1e32019-01-02 19:28:48 +000015390 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15391 Expr::EvalResult Result;
15392 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15393 if (!Result.Val.getInt().isNullValue()) {
15394 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15395 diag::err_omp_invalid_map_this_expr);
15396 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15397 diag::note_omp_invalid_subscript_on_this_ptr_map);
15398 }
15399 }
15400 RelevantExpr = TE;
15401 }
15402
Samuel Antao90927002016-04-26 14:54:23 +000015403 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015404 CurComponents.emplace_back(CurE, nullptr);
15405 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015406 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015407 E = CurE->getBase()->IgnoreParenImpCasts();
15408
Alexey Bataev27041fa2017-12-05 15:22:49 +000015409 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015410 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15411
Samuel Antao5de996e2016-01-22 20:21:36 +000015412 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15413 // If the type of a list item is a reference to a type T then the type
15414 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015415 if (CurType->isReferenceType())
15416 CurType = CurType->getPointeeType();
15417
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015418 bool IsPointer = CurType->isAnyPointerType();
15419
15420 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015421 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15422 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015423 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015424 }
15425
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015426 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015427 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015428 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015429 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015430
Samuel Antaodab51bb2016-07-18 23:22:11 +000015431 if (AllowWholeSizeArraySection) {
15432 // Any array section is currently allowed. Allowing a whole size array
15433 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015434 //
15435 // If this array section refers to the whole dimension we can still
15436 // accept other array sections before this one, except if the base is a
15437 // pointer. Otherwise, only unitary sections are accepted.
15438 if (NotWhole || IsPointer)
15439 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015440 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015441 // A unity or whole array section is not allowed and that is not
15442 // compatible with the properties of the current array section.
15443 SemaRef.Diag(
15444 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15445 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015446 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015447 }
Samuel Antao90927002016-04-26 14:54:23 +000015448
Patrick Lystere13b1e32019-01-02 19:28:48 +000015449 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15450 Expr::EvalResult ResultR;
15451 Expr::EvalResult ResultL;
15452 if (CurE->getLength()->EvaluateAsInt(ResultR,
15453 SemaRef.getASTContext())) {
15454 if (!ResultR.Val.getInt().isOneValue()) {
15455 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15456 diag::err_omp_invalid_map_this_expr);
15457 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15458 diag::note_omp_invalid_length_on_this_ptr_mapping);
15459 }
15460 }
15461 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15462 ResultL, SemaRef.getASTContext())) {
15463 if (!ResultL.Val.getInt().isNullValue()) {
15464 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15465 diag::err_omp_invalid_map_this_expr);
15466 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15467 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15468 }
15469 }
15470 RelevantExpr = TE;
15471 }
15472
Samuel Antao90927002016-04-26 14:54:23 +000015473 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015474 CurComponents.emplace_back(CurE, nullptr);
15475 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015476 if (!NoDiagnose) {
15477 // If nothing else worked, this is not a valid map clause expression.
15478 SemaRef.Diag(
15479 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15480 << ERange;
15481 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015482 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015483 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015484 }
15485
15486 return RelevantExpr;
15487}
15488
15489// Return true if expression E associated with value VD has conflicts with other
15490// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015491static bool checkMapConflicts(
15492 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015493 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015494 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15495 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015496 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015497 SourceLocation ELoc = E->getExprLoc();
15498 SourceRange ERange = E->getSourceRange();
15499
15500 // In order to easily check the conflicts we need to match each component of
15501 // the expression under test with the components of the expressions that are
15502 // already in the stack.
15503
Samuel Antao5de996e2016-01-22 20:21:36 +000015504 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015505 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015506 "Map clause expression with unexpected base!");
15507
15508 // Variables to help detecting enclosing problems in data environment nests.
15509 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015510 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015511
Samuel Antao90927002016-04-26 14:54:23 +000015512 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15513 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015514 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15515 ERange, CKind, &EnclosingExpr,
15516 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15517 StackComponents,
15518 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015519 assert(!StackComponents.empty() &&
15520 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015521 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015522 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015523 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015524
Samuel Antao90927002016-04-26 14:54:23 +000015525 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015526 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015527
Samuel Antao5de996e2016-01-22 20:21:36 +000015528 // Expressions must start from the same base. Here we detect at which
15529 // point both expressions diverge from each other and see if we can
15530 // detect if the memory referred to both expressions is contiguous and
15531 // do not overlap.
15532 auto CI = CurComponents.rbegin();
15533 auto CE = CurComponents.rend();
15534 auto SI = StackComponents.rbegin();
15535 auto SE = StackComponents.rend();
15536 for (; CI != CE && SI != SE; ++CI, ++SI) {
15537
15538 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15539 // At most one list item can be an array item derived from a given
15540 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015541 if (CurrentRegionOnly &&
15542 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15543 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15544 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15545 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15546 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015547 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015548 << CI->getAssociatedExpression()->getSourceRange();
15549 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15550 diag::note_used_here)
15551 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015552 return true;
15553 }
15554
15555 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015556 if (CI->getAssociatedExpression()->getStmtClass() !=
15557 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015558 break;
15559
15560 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015561 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015562 break;
15563 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015564 // Check if the extra components of the expressions in the enclosing
15565 // data environment are redundant for the current base declaration.
15566 // If they are, the maps completely overlap, which is legal.
15567 for (; SI != SE; ++SI) {
15568 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015569 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015570 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015571 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015572 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015573 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015574 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015575 Type =
15576 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15577 }
15578 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015579 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015580 SemaRef, SI->getAssociatedExpression(), Type))
15581 break;
15582 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015583
15584 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15585 // List items of map clauses in the same construct must not share
15586 // original storage.
15587 //
15588 // If the expressions are exactly the same or one is a subset of the
15589 // other, it means they are sharing storage.
15590 if (CI == CE && SI == SE) {
15591 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015592 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015593 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015594 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015595 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015596 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15597 << ERange;
15598 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015599 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15600 << RE->getSourceRange();
15601 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015602 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015603 // If we find the same expression in the enclosing data environment,
15604 // that is legal.
15605 IsEnclosedByDataEnvironmentExpr = true;
15606 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015607 }
15608
Samuel Antao90927002016-04-26 14:54:23 +000015609 QualType DerivedType =
15610 std::prev(CI)->getAssociatedDeclaration()->getType();
15611 SourceLocation DerivedLoc =
15612 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015613
15614 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15615 // If the type of a list item is a reference to a type T then the type
15616 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015617 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015618
15619 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15620 // A variable for which the type is pointer and an array section
15621 // derived from that variable must not appear as list items of map
15622 // clauses of the same construct.
15623 //
15624 // Also, cover one of the cases in:
15625 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15626 // If any part of the original storage of a list item has corresponding
15627 // storage in the device data environment, all of the original storage
15628 // must have corresponding storage in the device data environment.
15629 //
15630 if (DerivedType->isAnyPointerType()) {
15631 if (CI == CE || SI == SE) {
15632 SemaRef.Diag(
15633 DerivedLoc,
15634 diag::err_omp_pointer_mapped_along_with_derived_section)
15635 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015636 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15637 << RE->getSourceRange();
15638 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015639 }
15640 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015641 SI->getAssociatedExpression()->getStmtClass() ||
15642 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15643 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015644 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015645 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015646 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015647 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15648 << RE->getSourceRange();
15649 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015650 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015651 }
15652
15653 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15654 // List items of map clauses in the same construct must not share
15655 // original storage.
15656 //
15657 // An expression is a subset of the other.
15658 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015659 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015660 if (CI != CE || SI != SE) {
15661 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15662 // a pointer.
15663 auto Begin =
15664 CI != CE ? CurComponents.begin() : StackComponents.begin();
15665 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15666 auto It = Begin;
15667 while (It != End && !It->getAssociatedDeclaration())
15668 std::advance(It, 1);
15669 assert(It != End &&
15670 "Expected at least one component with the declaration.");
15671 if (It != Begin && It->getAssociatedDeclaration()
15672 ->getType()
15673 .getCanonicalType()
15674 ->isAnyPointerType()) {
15675 IsEnclosedByDataEnvironmentExpr = false;
15676 EnclosingExpr = nullptr;
15677 return false;
15678 }
15679 }
Samuel Antao661c0902016-05-26 17:39:58 +000015680 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015681 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015682 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015683 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15684 << ERange;
15685 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015686 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15687 << RE->getSourceRange();
15688 return true;
15689 }
15690
15691 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015692 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015693 if (!CurrentRegionOnly && SI != SE)
15694 EnclosingExpr = RE;
15695
15696 // The current expression is a subset of the expression in the data
15697 // environment.
15698 IsEnclosedByDataEnvironmentExpr |=
15699 (!CurrentRegionOnly && CI != CE && SI == SE);
15700
15701 return false;
15702 });
15703
15704 if (CurrentRegionOnly)
15705 return FoundError;
15706
15707 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15708 // If any part of the original storage of a list item has corresponding
15709 // storage in the device data environment, all of the original storage must
15710 // have corresponding storage in the device data environment.
15711 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15712 // If a list item is an element of a structure, and a different element of
15713 // the structure has a corresponding list item in the device data environment
15714 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015715 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015716 // data environment prior to the task encountering the construct.
15717 //
15718 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15719 SemaRef.Diag(ELoc,
15720 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15721 << ERange;
15722 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15723 << EnclosingExpr->getSourceRange();
15724 return true;
15725 }
15726
15727 return FoundError;
15728}
15729
Michael Kruse4304e9d2019-02-19 16:38:20 +000015730// Look up the user-defined mapper given the mapper name and mapped type, and
15731// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015732static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15733 CXXScopeSpec &MapperIdScopeSpec,
15734 const DeclarationNameInfo &MapperId,
15735 QualType Type,
15736 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015737 if (MapperIdScopeSpec.isInvalid())
15738 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015739 // Get the actual type for the array type.
15740 if (Type->isArrayType()) {
15741 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15742 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15743 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015744 // Find all user-defined mappers with the given MapperId.
15745 SmallVector<UnresolvedSet<8>, 4> Lookups;
15746 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15747 Lookup.suppressDiagnostics();
15748 if (S) {
15749 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15750 NamedDecl *D = Lookup.getRepresentativeDecl();
15751 while (S && !S->isDeclScope(D))
15752 S = S->getParent();
15753 if (S)
15754 S = S->getParent();
15755 Lookups.emplace_back();
15756 Lookups.back().append(Lookup.begin(), Lookup.end());
15757 Lookup.clear();
15758 }
15759 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15760 // Extract the user-defined mappers with the given MapperId.
15761 Lookups.push_back(UnresolvedSet<8>());
15762 for (NamedDecl *D : ULE->decls()) {
15763 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15764 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15765 Lookups.back().addDecl(DMD);
15766 }
15767 }
15768 // Defer the lookup for dependent types. The results will be passed through
15769 // UnresolvedMapper on instantiation.
15770 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15771 Type->isInstantiationDependentType() ||
15772 Type->containsUnexpandedParameterPack() ||
15773 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15774 return !D->isInvalidDecl() &&
15775 (D->getType()->isDependentType() ||
15776 D->getType()->isInstantiationDependentType() ||
15777 D->getType()->containsUnexpandedParameterPack());
15778 })) {
15779 UnresolvedSet<8> URS;
15780 for (const UnresolvedSet<8> &Set : Lookups) {
15781 if (Set.empty())
15782 continue;
15783 URS.append(Set.begin(), Set.end());
15784 }
15785 return UnresolvedLookupExpr::Create(
15786 SemaRef.Context, /*NamingClass=*/nullptr,
15787 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15788 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15789 }
Michael Kruse945249b2019-09-26 22:53:01 +000015790 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015791 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15792 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015793 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15794 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15795 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15796 return ExprError();
15797 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015798 // Perform argument dependent lookup.
15799 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15800 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15801 // Return the first user-defined mapper with the desired type.
15802 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15803 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15804 if (!D->isInvalidDecl() &&
15805 SemaRef.Context.hasSameType(D->getType(), Type))
15806 return D;
15807 return nullptr;
15808 }))
15809 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15810 // Find the first user-defined mapper with a type derived from the desired
15811 // type.
15812 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15813 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15814 if (!D->isInvalidDecl() &&
15815 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15816 !Type.isMoreQualifiedThan(D->getType()))
15817 return D;
15818 return nullptr;
15819 })) {
15820 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15821 /*DetectVirtual=*/false);
15822 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15823 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15824 VD->getType().getUnqualifiedType()))) {
15825 if (SemaRef.CheckBaseClassAccess(
15826 Loc, VD->getType(), Type, Paths.front(),
15827 /*DiagID=*/0) != Sema::AR_inaccessible) {
15828 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15829 }
15830 }
15831 }
15832 }
15833 // Report error if a mapper is specified, but cannot be found.
15834 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15835 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15836 << Type << MapperId.getName();
15837 return ExprError();
15838 }
15839 return ExprEmpty();
15840}
15841
Samuel Antao661c0902016-05-26 17:39:58 +000015842namespace {
15843// Utility struct that gathers all the related lists associated with a mappable
15844// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015845struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015846 // The list of expressions.
15847 ArrayRef<Expr *> VarList;
15848 // The list of processed expressions.
15849 SmallVector<Expr *, 16> ProcessedVarList;
15850 // The mappble components for each expression.
15851 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15852 // The base declaration of the variable.
15853 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015854 // The reference to the user-defined mapper associated with every expression.
15855 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015856
15857 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15858 // We have a list of components and base declarations for each entry in the
15859 // variable list.
15860 VarComponents.reserve(VarList.size());
15861 VarBaseDeclarations.reserve(VarList.size());
15862 }
15863};
15864}
15865
15866// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015867// \a CKind. In the check process the valid expressions, mappable expression
15868// components, variables, and user-defined mappers are extracted and used to
15869// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15870// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15871// and \a MapperId are expected to be valid if the clause kind is 'map'.
15872static void checkMappableExpressionList(
15873 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15874 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015875 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15876 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015877 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015878 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015879 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15880 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015881 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015882
15883 // If the identifier of user-defined mapper is not specified, it is "default".
15884 // We do not change the actual name in this clause to distinguish whether a
15885 // mapper is specified explicitly, i.e., it is not explicitly specified when
15886 // MapperId.getName() is empty.
15887 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15888 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15889 MapperId.setName(DeclNames.getIdentifier(
15890 &SemaRef.getASTContext().Idents.get("default")));
15891 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015892
15893 // Iterators to find the current unresolved mapper expression.
15894 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15895 bool UpdateUMIt = false;
15896 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015897
Samuel Antao90927002016-04-26 14:54:23 +000015898 // Keep track of the mappable components and base declarations in this clause.
15899 // Each entry in the list is going to have a list of components associated. We
15900 // record each set of the components so that we can build the clause later on.
15901 // In the end we should have the same amount of declarations and component
15902 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015903
Alexey Bataeve3727102018-04-18 15:57:46 +000015904 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015905 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015906 SourceLocation ELoc = RE->getExprLoc();
15907
Michael Kruse4304e9d2019-02-19 16:38:20 +000015908 // Find the current unresolved mapper expression.
15909 if (UpdateUMIt && UMIt != UMEnd) {
15910 UMIt++;
15911 assert(
15912 UMIt != UMEnd &&
15913 "Expect the size of UnresolvedMappers to match with that of VarList");
15914 }
15915 UpdateUMIt = true;
15916 if (UMIt != UMEnd)
15917 UnresolvedMapper = *UMIt;
15918
Alexey Bataeve3727102018-04-18 15:57:46 +000015919 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015920
15921 if (VE->isValueDependent() || VE->isTypeDependent() ||
15922 VE->isInstantiationDependent() ||
15923 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015924 // Try to find the associated user-defined mapper.
15925 ExprResult ER = buildUserDefinedMapperRef(
15926 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15927 VE->getType().getCanonicalType(), UnresolvedMapper);
15928 if (ER.isInvalid())
15929 continue;
15930 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015931 // We can only analyze this information once the missing information is
15932 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015933 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015934 continue;
15935 }
15936
Alexey Bataeve3727102018-04-18 15:57:46 +000015937 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015938
Samuel Antao5de996e2016-01-22 20:21:36 +000015939 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015940 SemaRef.Diag(ELoc,
15941 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015942 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015943 continue;
15944 }
15945
Samuel Antao90927002016-04-26 14:54:23 +000015946 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15947 ValueDecl *CurDeclaration = nullptr;
15948
15949 // Obtain the array or member expression bases if required. Also, fill the
15950 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015951 const Expr *BE = checkMapClauseExpressionBase(
15952 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015953 if (!BE)
15954 continue;
15955
Samuel Antao90927002016-04-26 14:54:23 +000015956 assert(!CurComponents.empty() &&
15957 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015958
Patrick Lystere13b1e32019-01-02 19:28:48 +000015959 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15960 // Add store "this" pointer to class in DSAStackTy for future checking
15961 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015962 // Try to find the associated user-defined mapper.
15963 ExprResult ER = buildUserDefinedMapperRef(
15964 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15965 VE->getType().getCanonicalType(), UnresolvedMapper);
15966 if (ER.isInvalid())
15967 continue;
15968 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015969 // Skip restriction checking for variable or field declarations
15970 MVLI.ProcessedVarList.push_back(RE);
15971 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15972 MVLI.VarComponents.back().append(CurComponents.begin(),
15973 CurComponents.end());
15974 MVLI.VarBaseDeclarations.push_back(nullptr);
15975 continue;
15976 }
15977
Samuel Antao90927002016-04-26 14:54:23 +000015978 // For the following checks, we rely on the base declaration which is
15979 // expected to be associated with the last component. The declaration is
15980 // expected to be a variable or a field (if 'this' is being mapped).
15981 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15982 assert(CurDeclaration && "Null decl on map clause.");
15983 assert(
15984 CurDeclaration->isCanonicalDecl() &&
15985 "Expecting components to have associated only canonical declarations.");
15986
15987 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015988 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015989
15990 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015991 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015992
15993 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015994 // threadprivate variables cannot appear in a map clause.
15995 // OpenMP 4.5 [2.10.5, target update Construct]
15996 // threadprivate variables cannot appear in a from clause.
15997 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015998 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015999 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
16000 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000016001 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016002 continue;
16003 }
16004
Samuel Antao5de996e2016-01-22 20:21:36 +000016005 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
16006 // A list item cannot appear in both a map clause and a data-sharing
16007 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000016008
Samuel Antao5de996e2016-01-22 20:21:36 +000016009 // Check conflicts with other map clause expressions. We check the conflicts
16010 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000016011 // environment, because the restrictions are different. We only have to
16012 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000016013 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016014 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016015 break;
Samuel Antao661c0902016-05-26 17:39:58 +000016016 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000016017 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016018 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016019 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000016020
Samuel Antao661c0902016-05-26 17:39:58 +000016021 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000016022 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16023 // If the type of a list item is a reference to a type T then the type will
16024 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000016025 auto I = llvm::find_if(
16026 CurComponents,
16027 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
16028 return MC.getAssociatedDeclaration();
16029 });
16030 assert(I != CurComponents.end() && "Null decl on map clause.");
Alexey Bataev48bad082020-01-14 14:13:47 -050016031 QualType Type;
16032 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
16033 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
16034 if (ASE) {
16035 Type = ASE->getType().getNonReferenceType();
16036 } else if (OASE) {
16037 QualType BaseType =
16038 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16039 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16040 Type = ATy->getElementType();
16041 else
16042 Type = BaseType->getPointeeType();
16043 Type = Type.getNonReferenceType();
16044 } else {
16045 Type = VE->getType();
16046 }
Samuel Antao5de996e2016-01-22 20:21:36 +000016047
Samuel Antao661c0902016-05-26 17:39:58 +000016048 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
16049 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000016050 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000016051 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000016052 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000016053 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000016054 continue;
16055
Alexey Bataev48bad082020-01-14 14:13:47 -050016056 Type = I->getAssociatedDeclaration()->getType().getNonReferenceType();
16057
Samuel Antao661c0902016-05-26 17:39:58 +000016058 if (CKind == OMPC_map) {
16059 // target enter data
16060 // OpenMP [2.10.2, Restrictions, p. 99]
16061 // A map-type must be specified in all map clauses and must be either
16062 // to or alloc.
16063 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
16064 if (DKind == OMPD_target_enter_data &&
16065 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
16066 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16067 << (IsMapTypeImplicit ? 1 : 0)
16068 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16069 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016070 continue;
16071 }
Samuel Antao661c0902016-05-26 17:39:58 +000016072
16073 // target exit_data
16074 // OpenMP [2.10.3, Restrictions, p. 102]
16075 // A map-type must be specified in all map clauses and must be either
16076 // from, release, or delete.
16077 if (DKind == OMPD_target_exit_data &&
16078 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
16079 MapType == OMPC_MAP_delete)) {
16080 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16081 << (IsMapTypeImplicit ? 1 : 0)
16082 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16083 << getOpenMPDirectiveName(DKind);
16084 continue;
16085 }
16086
16087 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16088 // A list item cannot appear in both a map clause and a data-sharing
16089 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000016090 //
16091 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16092 // A list item cannot appear in both a map clause and a data-sharing
16093 // attribute clause on the same construct unless the construct is a
16094 // combined construct.
16095 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
16096 isOpenMPTargetExecutionDirective(DKind)) ||
16097 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016098 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016099 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000016100 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000016101 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000016102 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000016103 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016104 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000016105 continue;
16106 }
16107 }
Michael Kruse01f670d2019-02-22 22:29:42 +000016108 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016109
Michael Kruse01f670d2019-02-22 22:29:42 +000016110 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000016111 ExprResult ER = buildUserDefinedMapperRef(
16112 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16113 Type.getCanonicalType(), UnresolvedMapper);
16114 if (ER.isInvalid())
16115 continue;
16116 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016117
Samuel Antao90927002016-04-26 14:54:23 +000016118 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000016119 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000016120
16121 // Store the components in the stack so that they can be used to check
16122 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000016123 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
16124 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000016125
16126 // Save the components and declaration to create the clause. For purposes of
16127 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000016128 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000016129 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16130 MVLI.VarComponents.back().append(CurComponents.begin(),
16131 CurComponents.end());
16132 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
16133 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016134 }
Samuel Antao661c0902016-05-26 17:39:58 +000016135}
16136
Michael Kruse4304e9d2019-02-19 16:38:20 +000016137OMPClause *Sema::ActOnOpenMPMapClause(
16138 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16139 ArrayRef<SourceLocation> MapTypeModifiersLoc,
16140 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
16141 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
16142 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
16143 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
16144 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
16145 OMPC_MAP_MODIFIER_unknown,
16146 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000016147 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
16148
16149 // Process map-type-modifiers, flag errors for duplicate modifiers.
16150 unsigned Count = 0;
16151 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
16152 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
16153 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
16154 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
16155 continue;
16156 }
16157 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000016158 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000016159 Modifiers[Count] = MapTypeModifiers[I];
16160 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
16161 ++Count;
16162 }
16163
Michael Kruse4304e9d2019-02-19 16:38:20 +000016164 MappableVarListInfo MVLI(VarList);
16165 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016166 MapperIdScopeSpec, MapperId, UnresolvedMappers,
16167 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000016168
Samuel Antao5de996e2016-01-22 20:21:36 +000016169 // We need to produce a map clause even if we don't have variables so that
16170 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000016171 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
16172 MVLI.VarBaseDeclarations, MVLI.VarComponents,
16173 MVLI.UDMapperList, Modifiers, ModifiersLoc,
16174 MapperIdScopeSpec.getWithLocInContext(Context),
16175 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016176}
Kelvin Li099bb8c2015-11-24 20:50:12 +000016177
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016178QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
16179 TypeResult ParsedType) {
16180 assert(ParsedType.isUsable());
16181
16182 QualType ReductionType = GetTypeFromParser(ParsedType.get());
16183 if (ReductionType.isNull())
16184 return QualType();
16185
16186 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
16187 // A type name in a declare reduction directive cannot be a function type, an
16188 // array type, a reference type, or a type qualified with const, volatile or
16189 // restrict.
16190 if (ReductionType.hasQualifiers()) {
16191 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
16192 return QualType();
16193 }
16194
16195 if (ReductionType->isFunctionType()) {
16196 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
16197 return QualType();
16198 }
16199 if (ReductionType->isReferenceType()) {
16200 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
16201 return QualType();
16202 }
16203 if (ReductionType->isArrayType()) {
16204 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
16205 return QualType();
16206 }
16207 return ReductionType;
16208}
16209
16210Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
16211 Scope *S, DeclContext *DC, DeclarationName Name,
16212 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
16213 AccessSpecifier AS, Decl *PrevDeclInScope) {
16214 SmallVector<Decl *, 8> Decls;
16215 Decls.reserve(ReductionTypes.size());
16216
16217 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000016218 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016219 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
16220 // A reduction-identifier may not be re-declared in the current scope for the
16221 // same type or for a type that is compatible according to the base language
16222 // rules.
16223 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16224 OMPDeclareReductionDecl *PrevDRD = nullptr;
16225 bool InCompoundScope = true;
16226 if (S != nullptr) {
16227 // Find previous declaration with the same name not referenced in other
16228 // declarations.
16229 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16230 InCompoundScope =
16231 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16232 LookupName(Lookup, S);
16233 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16234 /*AllowInlineNamespace=*/false);
16235 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000016236 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016237 while (Filter.hasNext()) {
16238 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
16239 if (InCompoundScope) {
16240 auto I = UsedAsPrevious.find(PrevDecl);
16241 if (I == UsedAsPrevious.end())
16242 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000016243 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016244 UsedAsPrevious[D] = true;
16245 }
16246 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16247 PrevDecl->getLocation();
16248 }
16249 Filter.done();
16250 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016251 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016252 if (!PrevData.second) {
16253 PrevDRD = PrevData.first;
16254 break;
16255 }
16256 }
16257 }
16258 } else if (PrevDeclInScope != nullptr) {
16259 auto *PrevDRDInScope = PrevDRD =
16260 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
16261 do {
16262 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
16263 PrevDRDInScope->getLocation();
16264 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
16265 } while (PrevDRDInScope != nullptr);
16266 }
Alexey Bataeve3727102018-04-18 15:57:46 +000016267 for (const auto &TyData : ReductionTypes) {
16268 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016269 bool Invalid = false;
16270 if (I != PreviousRedeclTypes.end()) {
16271 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
16272 << TyData.first;
16273 Diag(I->second, diag::note_previous_definition);
16274 Invalid = true;
16275 }
16276 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
16277 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
16278 Name, TyData.first, PrevDRD);
16279 DC->addDecl(DRD);
16280 DRD->setAccess(AS);
16281 Decls.push_back(DRD);
16282 if (Invalid)
16283 DRD->setInvalidDecl();
16284 else
16285 PrevDRD = DRD;
16286 }
16287
16288 return DeclGroupPtrTy::make(
16289 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16290}
16291
16292void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16293 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16294
16295 // Enter new function scope.
16296 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016297 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016298 getCurFunction()->setHasOMPDeclareReductionCombiner();
16299
16300 if (S != nullptr)
16301 PushDeclContext(S, DRD);
16302 else
16303 CurContext = DRD;
16304
Faisal Valid143a0c2017-04-01 21:30:49 +000016305 PushExpressionEvaluationContext(
16306 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016307
16308 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016309 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16310 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16311 // uses semantics of argument handles by value, but it should be passed by
16312 // reference. C lang does not support references, so pass all parameters as
16313 // pointers.
16314 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016315 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016316 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016317 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16318 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16319 // uses semantics of argument handles by value, but it should be passed by
16320 // reference. C lang does not support references, so pass all parameters as
16321 // pointers.
16322 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016323 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016324 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16325 if (S != nullptr) {
16326 PushOnScopeChains(OmpInParm, S);
16327 PushOnScopeChains(OmpOutParm, S);
16328 } else {
16329 DRD->addDecl(OmpInParm);
16330 DRD->addDecl(OmpOutParm);
16331 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016332 Expr *InE =
16333 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16334 Expr *OutE =
16335 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16336 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016337}
16338
16339void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16340 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16341 DiscardCleanupsInEvaluationContext();
16342 PopExpressionEvaluationContext();
16343
16344 PopDeclContext();
16345 PopFunctionScopeInfo();
16346
16347 if (Combiner != nullptr)
16348 DRD->setCombiner(Combiner);
16349 else
16350 DRD->setInvalidDecl();
16351}
16352
Alexey Bataev070f43a2017-09-06 14:49:58 +000016353VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016354 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16355
16356 // Enter new function scope.
16357 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016358 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016359
16360 if (S != nullptr)
16361 PushDeclContext(S, DRD);
16362 else
16363 CurContext = DRD;
16364
Faisal Valid143a0c2017-04-01 21:30:49 +000016365 PushExpressionEvaluationContext(
16366 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016367
16368 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016369 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16370 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16371 // uses semantics of argument handles by value, but it should be passed by
16372 // reference. C lang does not support references, so pass all parameters as
16373 // pointers.
16374 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016375 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016376 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016377 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16378 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16379 // uses semantics of argument handles by value, but it should be passed by
16380 // reference. C lang does not support references, so pass all parameters as
16381 // pointers.
16382 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016383 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016384 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016385 if (S != nullptr) {
16386 PushOnScopeChains(OmpPrivParm, S);
16387 PushOnScopeChains(OmpOrigParm, S);
16388 } else {
16389 DRD->addDecl(OmpPrivParm);
16390 DRD->addDecl(OmpOrigParm);
16391 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016392 Expr *OrigE =
16393 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16394 Expr *PrivE =
16395 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16396 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016397 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016398}
16399
Alexey Bataev070f43a2017-09-06 14:49:58 +000016400void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16401 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016402 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16403 DiscardCleanupsInEvaluationContext();
16404 PopExpressionEvaluationContext();
16405
16406 PopDeclContext();
16407 PopFunctionScopeInfo();
16408
Alexey Bataev070f43a2017-09-06 14:49:58 +000016409 if (Initializer != nullptr) {
16410 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16411 } else if (OmpPrivParm->hasInit()) {
16412 DRD->setInitializer(OmpPrivParm->getInit(),
16413 OmpPrivParm->isDirectInit()
16414 ? OMPDeclareReductionDecl::DirectInit
16415 : OMPDeclareReductionDecl::CopyInit);
16416 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016417 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016418 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016419}
16420
16421Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16422 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016423 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016424 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016425 if (S)
16426 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16427 /*AddToContext=*/false);
16428 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016429 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016430 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016431 }
16432 return DeclReductions;
16433}
16434
Michael Kruse251e1482019-02-01 20:25:04 +000016435TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16436 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16437 QualType T = TInfo->getType();
16438 if (D.isInvalidType())
16439 return true;
16440
16441 if (getLangOpts().CPlusPlus) {
16442 // Check that there are no default arguments (C++ only).
16443 CheckExtraCXXDefaultArguments(D);
16444 }
16445
16446 return CreateParsedType(T, TInfo);
16447}
16448
16449QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16450 TypeResult ParsedType) {
16451 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16452
16453 QualType MapperType = GetTypeFromParser(ParsedType.get());
16454 assert(!MapperType.isNull() && "Expect valid mapper type");
16455
16456 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16457 // The type must be of struct, union or class type in C and C++
16458 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16459 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16460 return QualType();
16461 }
16462 return MapperType;
16463}
16464
16465OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16466 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16467 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16468 Decl *PrevDeclInScope) {
16469 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16470 forRedeclarationInCurContext());
16471 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16472 // A mapper-identifier may not be redeclared in the current scope for the
16473 // same type or for a type that is compatible according to the base language
16474 // rules.
16475 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16476 OMPDeclareMapperDecl *PrevDMD = nullptr;
16477 bool InCompoundScope = true;
16478 if (S != nullptr) {
16479 // Find previous declaration with the same name not referenced in other
16480 // declarations.
16481 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16482 InCompoundScope =
16483 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16484 LookupName(Lookup, S);
16485 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16486 /*AllowInlineNamespace=*/false);
16487 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16488 LookupResult::Filter Filter = Lookup.makeFilter();
16489 while (Filter.hasNext()) {
16490 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16491 if (InCompoundScope) {
16492 auto I = UsedAsPrevious.find(PrevDecl);
16493 if (I == UsedAsPrevious.end())
16494 UsedAsPrevious[PrevDecl] = false;
16495 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16496 UsedAsPrevious[D] = true;
16497 }
16498 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16499 PrevDecl->getLocation();
16500 }
16501 Filter.done();
16502 if (InCompoundScope) {
16503 for (const auto &PrevData : UsedAsPrevious) {
16504 if (!PrevData.second) {
16505 PrevDMD = PrevData.first;
16506 break;
16507 }
16508 }
16509 }
16510 } else if (PrevDeclInScope) {
16511 auto *PrevDMDInScope = PrevDMD =
16512 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16513 do {
16514 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16515 PrevDMDInScope->getLocation();
16516 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16517 } while (PrevDMDInScope != nullptr);
16518 }
16519 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16520 bool Invalid = false;
16521 if (I != PreviousRedeclTypes.end()) {
16522 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16523 << MapperType << Name;
16524 Diag(I->second, diag::note_previous_definition);
16525 Invalid = true;
16526 }
16527 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16528 MapperType, VN, PrevDMD);
16529 DC->addDecl(DMD);
16530 DMD->setAccess(AS);
16531 if (Invalid)
16532 DMD->setInvalidDecl();
16533
16534 // Enter new function scope.
16535 PushFunctionScope();
16536 setFunctionHasBranchProtectedScope();
16537
16538 CurContext = DMD;
16539
16540 return DMD;
16541}
16542
16543void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16544 Scope *S,
16545 QualType MapperType,
16546 SourceLocation StartLoc,
16547 DeclarationName VN) {
16548 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16549 if (S)
16550 PushOnScopeChains(VD, S);
16551 else
16552 DMD->addDecl(VD);
16553 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16554 DMD->setMapperVarRef(MapperVarRefExpr);
16555}
16556
16557Sema::DeclGroupPtrTy
16558Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16559 ArrayRef<OMPClause *> ClauseList) {
16560 PopDeclContext();
16561 PopFunctionScopeInfo();
16562
16563 if (D) {
16564 if (S)
16565 PushOnScopeChains(D, S, /*AddToContext=*/false);
16566 D->CreateClauses(Context, ClauseList);
16567 }
16568
16569 return DeclGroupPtrTy::make(DeclGroupRef(D));
16570}
16571
David Majnemer9d168222016-08-05 17:44:54 +000016572OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016573 SourceLocation StartLoc,
16574 SourceLocation LParenLoc,
16575 SourceLocation EndLoc) {
16576 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016577 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016578
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016579 // OpenMP [teams Constrcut, Restrictions]
16580 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016581 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016582 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016583 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016584
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016585 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016586 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016587 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016588 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016589 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016590 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016591 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16592 HelperValStmt = buildPreInits(Context, Captures);
16593 }
16594
16595 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16596 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016597}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016598
16599OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16600 SourceLocation StartLoc,
16601 SourceLocation LParenLoc,
16602 SourceLocation EndLoc) {
16603 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016604 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016605
16606 // OpenMP [teams Constrcut, Restrictions]
16607 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016608 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016609 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016610 return nullptr;
16611
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016612 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016613 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16614 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016615 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016616 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016617 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016618 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16619 HelperValStmt = buildPreInits(Context, Captures);
16620 }
16621
16622 return new (Context) OMPThreadLimitClause(
16623 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016624}
Alexey Bataeva0569352015-12-01 10:17:31 +000016625
16626OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16627 SourceLocation StartLoc,
16628 SourceLocation LParenLoc,
16629 SourceLocation EndLoc) {
16630 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016631 Stmt *HelperValStmt = nullptr;
16632 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016633
16634 // OpenMP [2.9.1, task Constrcut]
16635 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016636 if (!isNonNegativeIntegerValue(
16637 ValExpr, *this, OMPC_priority,
16638 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16639 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016640 return nullptr;
16641
Alexey Bataev31ba4762019-10-16 18:09:37 +000016642 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16643 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016644}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016645
16646OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16647 SourceLocation StartLoc,
16648 SourceLocation LParenLoc,
16649 SourceLocation EndLoc) {
16650 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016651 Stmt *HelperValStmt = nullptr;
16652 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016653
16654 // OpenMP [2.9.2, taskloop Constrcut]
16655 // The parameter of the grainsize clause must be a positive integer
16656 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016657 if (!isNonNegativeIntegerValue(
16658 ValExpr, *this, OMPC_grainsize,
16659 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16660 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016661 return nullptr;
16662
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016663 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16664 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016665}
Alexey Bataev382967a2015-12-08 12:06:20 +000016666
16667OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16668 SourceLocation StartLoc,
16669 SourceLocation LParenLoc,
16670 SourceLocation EndLoc) {
16671 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016672 Stmt *HelperValStmt = nullptr;
16673 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016674
16675 // OpenMP [2.9.2, taskloop Constrcut]
16676 // The parameter of the num_tasks clause must be a positive integer
16677 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016678 if (!isNonNegativeIntegerValue(
16679 ValExpr, *this, OMPC_num_tasks,
16680 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16681 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016682 return nullptr;
16683
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016684 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16685 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016686}
16687
Alexey Bataev28c75412015-12-15 08:19:24 +000016688OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16689 SourceLocation LParenLoc,
16690 SourceLocation EndLoc) {
16691 // OpenMP [2.13.2, critical construct, Description]
16692 // ... where hint-expression is an integer constant expression that evaluates
16693 // to a valid lock hint.
16694 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16695 if (HintExpr.isInvalid())
16696 return nullptr;
16697 return new (Context)
16698 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16699}
16700
Carlo Bertollib4adf552016-01-15 18:50:31 +000016701OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16702 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16703 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16704 SourceLocation EndLoc) {
16705 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16706 std::string Values;
16707 Values += "'";
16708 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16709 Values += "'";
16710 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16711 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16712 return nullptr;
16713 }
16714 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016715 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016716 if (ChunkSize) {
16717 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16718 !ChunkSize->isInstantiationDependent() &&
16719 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016720 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016721 ExprResult Val =
16722 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16723 if (Val.isInvalid())
16724 return nullptr;
16725
16726 ValExpr = Val.get();
16727
16728 // OpenMP [2.7.1, Restrictions]
16729 // chunk_size must be a loop invariant integer expression with a positive
16730 // value.
16731 llvm::APSInt Result;
16732 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16733 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16734 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16735 << "dist_schedule" << ChunkSize->getSourceRange();
16736 return nullptr;
16737 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016738 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016739 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16740 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016741 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016742 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016743 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016744 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16745 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016746 }
16747 }
16748 }
16749
16750 return new (Context)
16751 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016752 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016753}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016754
16755OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16756 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16757 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16758 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016759 if (getLangOpts().OpenMP < 50) {
16760 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16761 Kind != OMPC_DEFAULTMAP_scalar) {
16762 std::string Value;
16763 SourceLocation Loc;
16764 Value += "'";
16765 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16766 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16767 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16768 Loc = MLoc;
16769 } else {
16770 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16771 OMPC_DEFAULTMAP_scalar);
16772 Loc = KindLoc;
16773 }
16774 Value += "'";
16775 Diag(Loc, diag::err_omp_unexpected_clause_value)
16776 << Value << getOpenMPClauseName(OMPC_defaultmap);
16777 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016778 }
cchene06f3e02019-11-15 13:02:06 -050016779 } else {
16780 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16781 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16782 if (!isDefaultmapKind || !isDefaultmapModifier) {
16783 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16784 "'firstprivate', 'none', 'default'";
16785 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16786 if (!isDefaultmapKind && isDefaultmapModifier) {
16787 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16788 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16789 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16790 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16791 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16792 } else {
16793 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16794 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16795 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16796 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16797 }
16798 return nullptr;
16799 }
16800
16801 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
16802 // At most one defaultmap clause for each category can appear on the
16803 // directive.
16804 if (DSAStack->checkDefaultmapCategory(Kind)) {
16805 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
16806 return nullptr;
16807 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016808 }
cchene06f3e02019-11-15 13:02:06 -050016809 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016810
16811 return new (Context)
16812 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16813}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016814
16815bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16816 DeclContext *CurLexicalContext = getCurLexicalContext();
16817 if (!CurLexicalContext->isFileContext() &&
16818 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016819 !CurLexicalContext->isExternCXXContext() &&
16820 !isa<CXXRecordDecl>(CurLexicalContext) &&
16821 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16822 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16823 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016824 Diag(Loc, diag::err_omp_region_not_file_context);
16825 return false;
16826 }
Kelvin Libc38e632018-09-10 02:07:09 +000016827 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016828 return true;
16829}
16830
16831void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016832 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016833 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016834 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016835}
16836
Alexey Bataev729e2422019-08-23 16:11:14 +000016837NamedDecl *
16838Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16839 const DeclarationNameInfo &Id,
16840 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016841 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16842 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16843
16844 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016845 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016846 Lookup.suppressDiagnostics();
16847
16848 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016849 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016850 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016851 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016852 CTK_ErrorRecovery)) {
16853 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16854 << Id.getName());
16855 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016856 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016857 }
16858
16859 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016860 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016861 }
16862
16863 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016864 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16865 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016866 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016867 return nullptr;
16868 }
16869 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16870 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16871 return ND;
16872}
16873
16874void Sema::ActOnOpenMPDeclareTargetName(
16875 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16876 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16877 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16878 isa<FunctionTemplateDecl>(ND)) &&
16879 "Expected variable, function or function template.");
16880
16881 // Diagnose marking after use as it may lead to incorrect diagnosis and
16882 // codegen.
16883 if (LangOpts.OpenMP >= 50 &&
16884 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16885 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16886
16887 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16888 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16889 if (DevTy.hasValue() && *DevTy != DT) {
16890 Diag(Loc, diag::err_omp_device_type_mismatch)
16891 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16892 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16893 return;
16894 }
16895 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16896 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16897 if (!Res) {
16898 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16899 SourceRange(Loc, Loc));
16900 ND->addAttr(A);
16901 if (ASTMutationListener *ML = Context.getASTMutationListener())
16902 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16903 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16904 } else if (*Res != MT) {
16905 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016906 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016907}
16908
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016909static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16910 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016911 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016912 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016913 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016914 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16915 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16916 if (SemaRef.LangOpts.OpenMP >= 50 &&
16917 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16918 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16919 VD->hasGlobalStorage()) {
16920 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16921 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16922 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16923 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16924 // If a lambda declaration and definition appears between a
16925 // declare target directive and the matching end declare target
16926 // directive, all variables that are captured by the lambda
16927 // expression must also appear in a to clause.
16928 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016929 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016930 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16931 << VD << 0 << SR;
16932 return;
16933 }
16934 }
16935 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016936 return;
16937 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16938 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016939}
16940
16941static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16942 Sema &SemaRef, DSAStackTy *Stack,
16943 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016944 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016945 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16946 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016947}
16948
Kelvin Li1ce87c72017-12-12 20:08:12 +000016949void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16950 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016951 if (!D || D->isInvalidDecl())
16952 return;
16953 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016954 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016955 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016956 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016957 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16958 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016959 return;
16960 // 2.10.6: threadprivate variable cannot appear in a declare target
16961 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016962 if (DSAStack->isThreadPrivate(VD)) {
16963 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016964 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016965 return;
16966 }
16967 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016968 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16969 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016970 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016971 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16972 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016973 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016974 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16975 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16976 return;
16977 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016978 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016979 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16980 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16981 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16982 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016983 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016984 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16985 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16986 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016987 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016988 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16989 // Problem if any with var declared with incomplete type will be reported
16990 // as normal, so no need to check it here.
16991 if ((E || !VD->getType()->isIncompleteType()) &&
16992 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16993 return;
16994 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16995 // Checking declaration inside declare target region.
16996 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16997 isa<FunctionTemplateDecl>(D)) {
16998 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016999 Context, OMPDeclareTargetDeclAttr::MT_To,
17000 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000017001 D->addAttr(A);
17002 if (ASTMutationListener *ML = Context.getASTMutationListener())
17003 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
17004 }
17005 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017006 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017007 }
Alexey Bataev30a78212018-09-11 13:59:10 +000017008 if (!E)
17009 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017010 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
17011}
Samuel Antao661c0902016-05-26 17:39:58 +000017012
17013OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000017014 CXXScopeSpec &MapperIdScopeSpec,
17015 DeclarationNameInfo &MapperId,
17016 const OMPVarListLocTy &Locs,
17017 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000017018 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017019 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
17020 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000017021 if (MVLI.ProcessedVarList.empty())
17022 return nullptr;
17023
Michael Kruse01f670d2019-02-22 22:29:42 +000017024 return OMPToClause::Create(
17025 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17026 MVLI.VarComponents, MVLI.UDMapperList,
17027 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000017028}
Samuel Antaoec172c62016-05-26 17:49:04 +000017029
17030OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000017031 CXXScopeSpec &MapperIdScopeSpec,
17032 DeclarationNameInfo &MapperId,
17033 const OMPVarListLocTy &Locs,
17034 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000017035 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017036 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
17037 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000017038 if (MVLI.ProcessedVarList.empty())
17039 return nullptr;
17040
Michael Kruse0336c752019-02-25 20:34:15 +000017041 return OMPFromClause::Create(
17042 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17043 MVLI.VarComponents, MVLI.UDMapperList,
17044 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000017045}
Carlo Bertolli2404b172016-07-13 15:37:16 +000017046
17047OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017048 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000017049 MappableVarListInfo MVLI(VarList);
17050 SmallVector<Expr *, 8> PrivateCopies;
17051 SmallVector<Expr *, 8> Inits;
17052
Alexey Bataeve3727102018-04-18 15:57:46 +000017053 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017054 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
17055 SourceLocation ELoc;
17056 SourceRange ERange;
17057 Expr *SimpleRefExpr = RefExpr;
17058 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17059 if (Res.second) {
17060 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000017061 MVLI.ProcessedVarList.push_back(RefExpr);
17062 PrivateCopies.push_back(nullptr);
17063 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017064 }
17065 ValueDecl *D = Res.first;
17066 if (!D)
17067 continue;
17068
17069 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000017070 Type = Type.getNonReferenceType().getUnqualifiedType();
17071
17072 auto *VD = dyn_cast<VarDecl>(D);
17073
17074 // Item should be a pointer or reference to pointer.
17075 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017076 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
17077 << 0 << RefExpr->getSourceRange();
17078 continue;
17079 }
Samuel Antaocc10b852016-07-28 14:23:26 +000017080
17081 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000017082 auto VDPrivate =
17083 buildVarDecl(*this, ELoc, Type, D->getName(),
17084 D->hasAttrs() ? &D->getAttrs() : nullptr,
17085 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000017086 if (VDPrivate->isInvalidDecl())
17087 continue;
17088
17089 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000017090 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000017091 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
17092
17093 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000017094 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000017095 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000017096 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
17097 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000017098 AddInitializerToDecl(VDPrivate,
17099 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000017100 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000017101
17102 // If required, build a capture to implement the privatization initialized
17103 // with the current list item value.
17104 DeclRefExpr *Ref = nullptr;
17105 if (!VD)
17106 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17107 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
17108 PrivateCopies.push_back(VDPrivateRefExpr);
17109 Inits.push_back(VDInitRefExpr);
17110
17111 // We need to add a data sharing attribute for this variable to make sure it
17112 // is correctly captured. A variable that shows up in a use_device_ptr has
17113 // similar properties of a first private variable.
17114 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
17115
17116 // Create a mappable component for the list item. List items in this clause
17117 // only need a component.
17118 MVLI.VarBaseDeclarations.push_back(D);
17119 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17120 MVLI.VarComponents.back().push_back(
17121 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000017122 }
17123
Samuel Antaocc10b852016-07-28 14:23:26 +000017124 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000017125 return nullptr;
17126
Samuel Antaocc10b852016-07-28 14:23:26 +000017127 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000017128 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
17129 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017130}
Carlo Bertolli70594e92016-07-13 17:16:49 +000017131
17132OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017133 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000017134 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000017135 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000017136 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000017137 SourceLocation ELoc;
17138 SourceRange ERange;
17139 Expr *SimpleRefExpr = RefExpr;
17140 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17141 if (Res.second) {
17142 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000017143 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017144 }
17145 ValueDecl *D = Res.first;
17146 if (!D)
17147 continue;
17148
17149 QualType Type = D->getType();
17150 // item should be a pointer or array or reference to pointer or array
17151 if (!Type.getNonReferenceType()->isPointerType() &&
17152 !Type.getNonReferenceType()->isArrayType()) {
17153 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
17154 << 0 << RefExpr->getSourceRange();
17155 continue;
17156 }
Samuel Antao6890b092016-07-28 14:25:09 +000017157
17158 // Check if the declaration in the clause does not show up in any data
17159 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000017160 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000017161 if (isOpenMPPrivate(DVar.CKind)) {
17162 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17163 << getOpenMPClauseName(DVar.CKind)
17164 << getOpenMPClauseName(OMPC_is_device_ptr)
17165 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000017166 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000017167 continue;
17168 }
17169
Alexey Bataeve3727102018-04-18 15:57:46 +000017170 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000017171 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000017172 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000017173 [&ConflictExpr](
17174 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
17175 OpenMPClauseKind) -> bool {
17176 ConflictExpr = R.front().getAssociatedExpression();
17177 return true;
17178 })) {
17179 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
17180 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
17181 << ConflictExpr->getSourceRange();
17182 continue;
17183 }
17184
17185 // Store the components in the stack so that they can be used to check
17186 // against other clauses later on.
17187 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
17188 DSAStack->addMappableExpressionComponents(
17189 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
17190
17191 // Record the expression we've just processed.
17192 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
17193
17194 // Create a mappable component for the list item. List items in this clause
17195 // only need a component. We use a null declaration to signal fields in
17196 // 'this'.
17197 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
17198 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
17199 "Unexpected device pointer expression!");
17200 MVLI.VarBaseDeclarations.push_back(
17201 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
17202 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17203 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017204 }
17205
Samuel Antao6890b092016-07-28 14:25:09 +000017206 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000017207 return nullptr;
17208
Michael Kruse4304e9d2019-02-19 16:38:20 +000017209 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
17210 MVLI.VarBaseDeclarations,
17211 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017212}
Alexey Bataeve04483e2019-03-27 14:14:31 +000017213
17214OMPClause *Sema::ActOnOpenMPAllocateClause(
17215 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17216 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
17217 if (Allocator) {
17218 // OpenMP [2.11.4 allocate Clause, Description]
17219 // allocator is an expression of omp_allocator_handle_t type.
17220 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
17221 return nullptr;
17222
17223 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
17224 if (AllocatorRes.isInvalid())
17225 return nullptr;
17226 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
17227 DSAStack->getOMPAllocatorHandleT(),
17228 Sema::AA_Initializing,
17229 /*AllowExplicit=*/true);
17230 if (AllocatorRes.isInvalid())
17231 return nullptr;
17232 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000017233 } else {
17234 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
17235 // allocate clauses that appear on a target construct or on constructs in a
17236 // target region must specify an allocator expression unless a requires
17237 // directive with the dynamic_allocators clause is present in the same
17238 // compilation unit.
17239 if (LangOpts.OpenMPIsDevice &&
17240 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
17241 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017242 }
17243 // Analyze and build list of variables.
17244 SmallVector<Expr *, 8> Vars;
17245 for (Expr *RefExpr : VarList) {
17246 assert(RefExpr && "NULL expr in OpenMP private clause.");
17247 SourceLocation ELoc;
17248 SourceRange ERange;
17249 Expr *SimpleRefExpr = RefExpr;
17250 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17251 if (Res.second) {
17252 // It will be analyzed later.
17253 Vars.push_back(RefExpr);
17254 }
17255 ValueDecl *D = Res.first;
17256 if (!D)
17257 continue;
17258
17259 auto *VD = dyn_cast<VarDecl>(D);
17260 DeclRefExpr *Ref = nullptr;
17261 if (!VD && !CurContext->isDependentContext())
17262 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17263 Vars.push_back((VD || CurContext->isDependentContext())
17264 ? RefExpr->IgnoreParens()
17265 : Ref);
17266 }
17267
17268 if (Vars.empty())
17269 return nullptr;
17270
17271 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
17272 ColonLoc, EndLoc, Vars);
17273}
Alexey Bataevb6e70842019-12-16 15:54:17 -050017274
17275OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
17276 SourceLocation StartLoc,
17277 SourceLocation LParenLoc,
17278 SourceLocation EndLoc) {
17279 SmallVector<Expr *, 8> Vars;
17280 for (Expr *RefExpr : VarList) {
17281 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
17282 SourceLocation ELoc;
17283 SourceRange ERange;
17284 Expr *SimpleRefExpr = RefExpr;
17285 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17286 if (Res.second)
17287 // It will be analyzed later.
17288 Vars.push_back(RefExpr);
17289 ValueDecl *D = Res.first;
17290 if (!D)
17291 continue;
17292
Alexey Bataevb6e70842019-12-16 15:54:17 -050017293 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
17294 // A list-item cannot appear in more than one nontemporal clause.
17295 if (const Expr *PrevRef =
17296 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
17297 Diag(ELoc, diag::err_omp_used_in_clause_twice)
17298 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
17299 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17300 << getOpenMPClauseName(OMPC_nontemporal);
17301 continue;
17302 }
17303
Alexey Bataev0860db92019-12-19 10:01:10 -050017304 Vars.push_back(RefExpr);
Alexey Bataevb6e70842019-12-16 15:54:17 -050017305 }
17306
17307 if (Vars.empty())
17308 return nullptr;
17309
17310 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17311 Vars);
17312}