blob: 53840d400164eff916a3454760ecf6a056791531 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000045enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000049};
50
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000051/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000052/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000053class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000054public:
Alexey Bataeve3727102018-04-18 15:57:46 +000055 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000056 OpenMPDirectiveKind DKind = OMPD_unknown;
57 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000058 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000059 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000060 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000061 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000062 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
63 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
64 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000065 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
66 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000067 };
Alexey Bataeve3727102018-04-18 15:57:46 +000068 using OperatorOffsetTy =
69 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000070 using DoacrossDependMapTy =
71 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000072
Alexey Bataev758e55e2013-09-06 18:03:48 +000073private:
Alexey Bataeve3727102018-04-18 15:57:46 +000074 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000075 OpenMPClauseKind Attributes = OMPC_unknown;
76 /// Pointer to a reference expression and a flag which shows that the
77 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000078 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000079 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000080 };
Alexey Bataeve3727102018-04-18 15:57:46 +000081 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
82 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
83 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
84 using LoopControlVariablesMapTy =
85 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000086 /// Struct that associates a component with the clause kind where they are
87 /// found.
88 struct MappedExprComponentTy {
89 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
90 OpenMPClauseKind Kind = OMPC_unknown;
91 };
Alexey Bataeve3727102018-04-18 15:57:46 +000092 using MappedExprComponentsTy =
93 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
94 using CriticalsWithHintsTy =
95 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +000096 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +000097 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +000098 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +000099 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000100 ReductionData() = default;
101 void set(BinaryOperatorKind BO, SourceRange RR) {
102 ReductionRange = RR;
103 ReductionOp = BO;
104 }
105 void set(const Expr *RefExpr, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = RefExpr;
108 }
109 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000110 using DeclReductionMapTy =
111 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
cchene06f3e02019-11-15 13:02:06 -0500112 struct DefaultmapInfo {
113 OpenMPDefaultmapClauseModifier ImplicitBehavior =
114 OMPC_DEFAULTMAP_MODIFIER_unknown;
115 SourceLocation SLoc;
116 DefaultmapInfo() = default;
117 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
118 : ImplicitBehavior(M), SLoc(Loc) {}
119 };
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120
Alexey Bataeve3727102018-04-18 15:57:46 +0000121 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000122 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000123 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000124 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000125 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000126 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000127 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000128 SourceLocation DefaultAttrLoc;
cchene06f3e02019-11-15 13:02:06 -0500129 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000130 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000131 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000132 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000133 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000134 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
135 /// get the data (loop counters etc.) about enclosing loop-based construct.
136 /// This data is required during codegen.
137 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000138 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000139 /// 'ordered' clause, the second one is true if the regions has 'ordered'
140 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000141 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000142 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000143 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000144 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000145 bool NowaitRegion = false;
146 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000147 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000148 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000149 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000150 /// Reference to the taskgroup task_reduction reference expression.
151 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000152 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000153 /// List of globals marked as declare target link in this target region
154 /// (isOpenMPTargetExecutionDirective(Directive) == true).
155 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000156 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000157 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000158 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
159 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000160 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000161 };
162
Alexey Bataeve3727102018-04-18 15:57:46 +0000163 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000164
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000165 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000166 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000167 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
168 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000169 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000170 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000171 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000172 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000173 bool ForceCapturing = false;
Alexey Bataevd1caf932019-09-30 14:05:26 +0000174 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000175 /// captured by reference.
176 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000177 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000178 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000179
Richard Smith375dec52019-05-30 23:21:14 +0000180 /// Iterators over the stack iterate in order from innermost to outermost
181 /// directive.
182 using const_iterator = StackTy::const_reverse_iterator;
183 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000184 return Stack.empty() ? const_iterator()
185 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000186 }
187 const_iterator end() const {
188 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
189 }
190 using iterator = StackTy::reverse_iterator;
191 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000192 return Stack.empty() ? iterator()
193 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000194 }
195 iterator end() {
196 return Stack.empty() ? iterator() : Stack.back().first.rend();
197 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000198
Richard Smith375dec52019-05-30 23:21:14 +0000199 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000200
Alexey Bataev4b465392017-04-26 15:06:24 +0000201 bool isStackEmpty() const {
202 return Stack.empty() ||
203 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000204 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000205 }
Richard Smith375dec52019-05-30 23:21:14 +0000206 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000207 return isStackEmpty() ? 0
208 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000209 }
210
211 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000212 size_t Size = getStackSize();
213 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000214 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000215 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000216 }
217 const SharingMapTy *getTopOfStackOrNull() const {
218 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
219 }
220 SharingMapTy &getTopOfStack() {
221 assert(!isStackEmpty() && "no current directive");
222 return *getTopOfStackOrNull();
223 }
224 const SharingMapTy &getTopOfStack() const {
225 return const_cast<DSAStackTy&>(*this).getTopOfStack();
226 }
227
228 SharingMapTy *getSecondOnStackOrNull() {
229 size_t Size = getStackSize();
230 if (Size <= 1)
231 return nullptr;
232 return &Stack.back().first[Size - 2];
233 }
234 const SharingMapTy *getSecondOnStackOrNull() const {
235 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
236 }
237
238 /// Get the stack element at a certain level (previously returned by
239 /// \c getNestingLevel).
240 ///
241 /// Note that nesting levels count from outermost to innermost, and this is
242 /// the reverse of our iteration order where new inner levels are pushed at
243 /// the front of the stack.
244 SharingMapTy &getStackElemAtLevel(unsigned Level) {
245 assert(Level < getStackSize() && "no such stack element");
246 return Stack.back().first[Level];
247 }
248 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
249 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
250 }
251
252 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
253
254 /// Checks if the variable is a local for OpenMP region.
255 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000256
Kelvin Li1408f912018-09-26 04:28:39 +0000257 /// Vector of previously declared requires directives
258 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000259 /// omp_allocator_handle_t type.
260 QualType OMPAllocatorHandleT;
261 /// Expression for the predefined allocators.
262 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
263 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000264 /// Vector of previously encountered target directives
265 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000266
Alexey Bataev758e55e2013-09-06 18:03:48 +0000267public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000268 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000269
Alexey Bataev27ef9512019-03-20 20:14:22 +0000270 /// Sets omp_allocator_handle_t type.
271 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
272 /// Gets omp_allocator_handle_t type.
273 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
274 /// Sets the given default allocator.
275 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
276 Expr *Allocator) {
277 OMPPredefinedAllocators[AllocatorKind] = Allocator;
278 }
279 /// Returns the specified default allocator.
280 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
281 return OMPPredefinedAllocators[AllocatorKind];
282 }
283
Alexey Bataevaac108a2015-06-23 04:51:00 +0000284 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000285 OpenMPClauseKind getClauseParsingMode() const {
286 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
287 return ClauseKindMode;
288 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000289 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000290
Richard Smith0621a8f2019-05-31 00:45:10 +0000291 bool isBodyComplete() const {
292 const SharingMapTy *Top = getTopOfStackOrNull();
293 return Top && Top->BodyComplete;
294 }
295 void setBodyComplete() {
296 getTopOfStack().BodyComplete = true;
297 }
298
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000299 bool isForceVarCapturing() const { return ForceCapturing; }
300 void setForceVarCapturing(bool V) { ForceCapturing = V; }
301
Alexey Bataev60705422018-10-30 15:50:12 +0000302 void setForceCaptureByReferenceInTargetExecutable(bool V) {
303 ForceCaptureByReferenceInTargetExecutable = V;
304 }
305 bool isForceCaptureByReferenceInTargetExecutable() const {
306 return ForceCaptureByReferenceInTargetExecutable;
307 }
308
Alexey Bataev758e55e2013-09-06 18:03:48 +0000309 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000310 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000311 assert(!IgnoredStackElements &&
312 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000313 if (Stack.empty() ||
314 Stack.back().second != CurrentNonCapturingFunctionScope)
315 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
316 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
317 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000318 }
319
320 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000321 assert(!IgnoredStackElements &&
322 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000323 assert(!Stack.back().first.empty() &&
324 "Data-sharing attributes stack is empty!");
325 Stack.back().first.pop_back();
326 }
327
Richard Smith0621a8f2019-05-31 00:45:10 +0000328 /// RAII object to temporarily leave the scope of a directive when we want to
329 /// logically operate in its parent.
330 class ParentDirectiveScope {
331 DSAStackTy &Self;
332 bool Active;
333 public:
334 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
335 : Self(Self), Active(false) {
336 if (Activate)
337 enable();
338 }
339 ~ParentDirectiveScope() { disable(); }
340 void disable() {
341 if (Active) {
342 --Self.IgnoredStackElements;
343 Active = false;
344 }
345 }
346 void enable() {
347 if (!Active) {
348 ++Self.IgnoredStackElements;
349 Active = true;
350 }
351 }
352 };
353
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000354 /// Marks that we're started loop parsing.
355 void loopInit() {
356 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
357 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000358 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000359 }
360 /// Start capturing of the variables in the loop context.
361 void loopStart() {
362 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
363 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000364 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000365 }
366 /// true, if variables are captured, false otherwise.
367 bool isLoopStarted() const {
368 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
369 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000370 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000371 }
372 /// Marks (or clears) declaration as possibly loop counter.
373 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000374 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000375 D ? D->getCanonicalDecl() : D;
376 }
377 /// Gets the possible loop counter decl.
378 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000379 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000380 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000381 /// Start new OpenMP region stack in new non-capturing function.
382 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000383 assert(!IgnoredStackElements &&
384 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000385 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
386 assert(!isa<CapturingScopeInfo>(CurFnScope));
387 CurrentNonCapturingFunctionScope = CurFnScope;
388 }
389 /// Pop region stack for non-capturing function.
390 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000391 assert(!IgnoredStackElements &&
392 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000393 if (!Stack.empty() && Stack.back().second == OldFSI) {
394 assert(Stack.back().first.empty());
395 Stack.pop_back();
396 }
397 CurrentNonCapturingFunctionScope = nullptr;
398 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
399 if (!isa<CapturingScopeInfo>(FSI)) {
400 CurrentNonCapturingFunctionScope = FSI;
401 break;
402 }
403 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000404 }
405
Alexey Bataeve3727102018-04-18 15:57:46 +0000406 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000407 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000408 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000409 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000410 getCriticalWithHint(const DeclarationNameInfo &Name) const {
411 auto I = Criticals.find(Name.getAsString());
412 if (I != Criticals.end())
413 return I->second;
414 return std::make_pair(nullptr, llvm::APSInt());
415 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000416 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000417 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000418 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000419 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000420
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000421 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000422 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000423 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000424 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000425 /// \return The index of the loop control variable in the list of associated
426 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000427 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000428 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000429 /// parent region.
430 /// \return The index of the loop control variable in the list of associated
431 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000432 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000434 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000435 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000436
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000438 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000439 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000440
Alexey Bataevfa312f32017-07-21 18:48:21 +0000441 /// Adds additional information for the reduction items with the reduction id
442 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000443 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000444 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000445 /// Adds additional information for the reduction items with the reduction id
446 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000447 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000448 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000449 /// Returns the location and reduction operation from the innermost parent
450 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000451 const DSAVarData
452 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
453 BinaryOperatorKind &BOK,
454 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000455 /// Returns the location and reduction operation from the innermost parent
456 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000457 const DSAVarData
458 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
459 const Expr *&ReductionRef,
460 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000461 /// Return reduction reference expression for the current taskgroup.
462 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000463 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000464 "taskgroup reference expression requested for non taskgroup "
465 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000466 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000467 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000468 /// Checks if the given \p VD declaration is actually a taskgroup reduction
469 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000470 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000471 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
472 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000473 ->getDecl() == VD;
474 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000475
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000476 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000477 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000478 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000479 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000480 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000481 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000482 /// match specified \a CPred predicate in any directive which matches \a DPred
483 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000484 const DSAVarData
485 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
486 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
487 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000488 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000489 /// match specified \a CPred predicate in any innermost directive which
490 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000491 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000492 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000493 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
494 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000495 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000496 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000497 /// attributes which match specified \a CPred predicate at the specified
498 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000499 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000500 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000501 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000503 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000504 /// specified \a DPred predicate.
505 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000506 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000507 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000508
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000509 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000510 bool hasDirective(
511 const llvm::function_ref<bool(
512 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
513 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000514 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000516 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000517 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000518 const SharingMapTy *Top = getTopOfStackOrNull();
519 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000521 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000522 OpenMPDirectiveKind getDirective(unsigned Level) const {
523 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000524 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000525 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000526 /// Returns the capture region at the specified level.
527 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
528 unsigned OpenMPCaptureLevel) const {
529 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
530 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
531 return CaptureRegions[OpenMPCaptureLevel];
532 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000533 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000534 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000535 const SharingMapTy *Parent = getSecondOnStackOrNull();
536 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000537 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000538
Kelvin Li1408f912018-09-26 04:28:39 +0000539 /// Add requires decl to internal vector
540 void addRequiresDecl(OMPRequiresDecl *RD) {
541 RequiresDecls.push_back(RD);
542 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000543
Alexey Bataev318f431b2019-03-22 15:25:12 +0000544 /// Checks if the defined 'requires' directive has specified type of clause.
545 template <typename ClauseType>
546 bool hasRequiresDeclWithClause() {
547 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
548 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
549 return isa<ClauseType>(C);
550 });
551 });
552 }
553
Kelvin Li1408f912018-09-26 04:28:39 +0000554 /// Checks for a duplicate clause amongst previously declared requires
555 /// directives
556 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
557 bool IsDuplicate = false;
558 for (OMPClause *CNew : ClauseList) {
559 for (const OMPRequiresDecl *D : RequiresDecls) {
560 for (const OMPClause *CPrev : D->clauselists()) {
561 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
562 SemaRef.Diag(CNew->getBeginLoc(),
563 diag::err_omp_requires_clause_redeclaration)
564 << getOpenMPClauseName(CNew->getClauseKind());
565 SemaRef.Diag(CPrev->getBeginLoc(),
566 diag::note_omp_requires_previous_clause)
567 << getOpenMPClauseName(CPrev->getClauseKind());
568 IsDuplicate = true;
569 }
570 }
571 }
572 }
573 return IsDuplicate;
574 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000575
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000576 /// Add location of previously encountered target to internal vector
577 void addTargetDirLocation(SourceLocation LocStart) {
578 TargetLocations.push_back(LocStart);
579 }
580
581 // Return previously encountered target region locations.
582 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
583 return TargetLocations;
584 }
585
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000586 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000587 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000588 getTopOfStack().DefaultAttr = DSA_none;
589 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000590 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000591 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000592 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000593 getTopOfStack().DefaultAttr = DSA_shared;
594 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000595 }
cchene06f3e02019-11-15 13:02:06 -0500596 /// Set default data mapping attribute to Modifier:Kind
597 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
598 OpenMPDefaultmapClauseKind Kind,
599 SourceLocation Loc) {
600 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
601 DMI.ImplicitBehavior = M;
602 DMI.SLoc = Loc;
603 }
604 /// Check whether the implicit-behavior has been set in defaultmap
605 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
606 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
607 OMPC_DEFAULTMAP_MODIFIER_unknown;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000608 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000609
610 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000611 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000612 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000613 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000614 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000615 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000616 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000617 }
cchene06f3e02019-11-15 13:02:06 -0500618 OpenMPDefaultmapClauseModifier
619 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
620 return isStackEmpty()
621 ? OMPC_DEFAULTMAP_MODIFIER_unknown
622 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000623 }
cchene06f3e02019-11-15 13:02:06 -0500624 OpenMPDefaultmapClauseModifier
625 getDefaultmapModifierAtLevel(unsigned Level,
626 OpenMPDefaultmapClauseKind Kind) const {
627 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000628 }
cchene06f3e02019-11-15 13:02:06 -0500629 bool isDefaultmapCapturedByRef(unsigned Level,
630 OpenMPDefaultmapClauseKind Kind) const {
631 OpenMPDefaultmapClauseModifier M =
632 getDefaultmapModifierAtLevel(Level, Kind);
633 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
634 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
635 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
636 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
637 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
638 }
639 return true;
640 }
641 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
642 OpenMPDefaultmapClauseKind Kind) {
643 switch (Kind) {
644 case OMPC_DEFAULTMAP_scalar:
645 case OMPC_DEFAULTMAP_pointer:
646 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
647 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
648 (M == OMPC_DEFAULTMAP_MODIFIER_default);
649 case OMPC_DEFAULTMAP_aggregate:
650 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000651 default:
652 break;
cchene06f3e02019-11-15 13:02:06 -0500653 }
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000654 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
cchene06f3e02019-11-15 13:02:06 -0500655 }
656 bool mustBeFirstprivateAtLevel(unsigned Level,
657 OpenMPDefaultmapClauseKind Kind) const {
658 OpenMPDefaultmapClauseModifier M =
659 getDefaultmapModifierAtLevel(Level, Kind);
660 return mustBeFirstprivateBase(M, Kind);
661 }
662 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
663 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
664 return mustBeFirstprivateBase(M, Kind);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000665 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000666
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000667 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000668 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000669 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000670 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000671 }
672
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000673 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000674 void setOrderedRegion(bool IsOrdered, const Expr *Param,
675 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000676 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000677 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000678 else
Richard Smith375dec52019-05-30 23:21:14 +0000679 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000680 }
681 /// Returns true, if region is ordered (has associated 'ordered' clause),
682 /// false - otherwise.
683 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000684 if (const SharingMapTy *Top = getTopOfStackOrNull())
685 return Top->OrderedRegion.hasValue();
686 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000687 }
688 /// Returns optional parameter for the ordered region.
689 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000690 if (const SharingMapTy *Top = getTopOfStackOrNull())
691 if (Top->OrderedRegion.hasValue())
692 return Top->OrderedRegion.getValue();
693 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000694 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000695 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000696 /// 'ordered' clause), false - otherwise.
697 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000698 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
699 return Parent->OrderedRegion.hasValue();
700 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000701 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000702 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000703 std::pair<const Expr *, OMPOrderedClause *>
704 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000705 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
706 if (Parent->OrderedRegion.hasValue())
707 return Parent->OrderedRegion.getValue();
708 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000709 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000710 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000711 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000712 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000713 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000714 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000715 /// 'nowait' clause), false - otherwise.
716 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000717 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
718 return Parent->NowaitRegion;
719 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000720 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000721 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000722 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000723 if (SharingMapTy *Parent = getSecondOnStackOrNull())
724 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000725 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000726 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000727 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000728 const SharingMapTy *Top = getTopOfStackOrNull();
729 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000730 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000731
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000732 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000733 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000734 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000735 if (Val > 1)
736 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000737 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000738 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000739 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000740 const SharingMapTy *Top = getTopOfStackOrNull();
741 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000742 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000743 /// Returns true if the construct is associated with multiple loops.
744 bool hasMutipleLoops() const {
745 const SharingMapTy *Top = getTopOfStackOrNull();
746 return Top ? Top->HasMutipleLoops : false;
747 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000748
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000749 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000750 /// region.
751 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000752 if (SharingMapTy *Parent = getSecondOnStackOrNull())
753 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000754 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000755 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000756 bool hasInnerTeamsRegion() const {
757 return getInnerTeamsRegionLoc().isValid();
758 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000759 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000760 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000761 const SharingMapTy *Top = getTopOfStackOrNull();
762 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000763 }
764
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000765 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000766 const SharingMapTy *Top = getTopOfStackOrNull();
767 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000768 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000769 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000770 const SharingMapTy *Top = getTopOfStackOrNull();
771 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000772 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000773
Samuel Antao4c8035b2016-12-12 18:00:20 +0000774 /// Do the check specified in \a Check to all component lists and return true
775 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000776 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000777 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000778 const llvm::function_ref<
779 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000780 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000781 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000782 if (isStackEmpty())
783 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000784 auto SI = begin();
785 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000786
787 if (SI == SE)
788 return false;
789
Alexey Bataeve3727102018-04-18 15:57:46 +0000790 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000791 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000792 else
793 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000794
795 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000796 auto MI = SI->MappedExprComponents.find(VD);
797 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000798 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
799 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000800 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000801 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000802 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000803 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000804 }
805
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000806 /// Do the check specified in \a Check to all component lists at a given level
807 /// and return true if any issue is found.
808 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000809 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000810 const llvm::function_ref<
811 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000812 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000813 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000814 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000815 return false;
816
Richard Smith375dec52019-05-30 23:21:14 +0000817 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
818 auto MI = StackElem.MappedExprComponents.find(VD);
819 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000820 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
821 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000822 if (Check(L, MI->second.Kind))
823 return true;
824 return false;
825 }
826
Samuel Antao4c8035b2016-12-12 18:00:20 +0000827 /// Create a new mappable expression component list associated with a given
828 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000829 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000830 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000831 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
832 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000833 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000834 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000835 MEC.Components.resize(MEC.Components.size() + 1);
836 MEC.Components.back().append(Components.begin(), Components.end());
837 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000838 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000839
840 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000841 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000842 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000843 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000844 void addDoacrossDependClause(OMPDependClause *C,
845 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000846 SharingMapTy *Parent = getSecondOnStackOrNull();
847 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
848 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000849 }
850 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
851 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000852 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000853 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000854 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000855 return llvm::make_range(Ref.begin(), Ref.end());
856 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000857 return llvm::make_range(StackElem.DoacrossDepends.end(),
858 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000859 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000860
861 // Store types of classes which have been explicitly mapped
862 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000863 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000864 StackElem.MappedClassesQualTypes.insert(QT);
865 }
866
867 // Return set of mapped classes types
868 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000869 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000870 return StackElem.MappedClassesQualTypes.count(QT) != 0;
871 }
872
Alexey Bataeva495c642019-03-11 19:51:42 +0000873 /// Adds global declare target to the parent target region.
874 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
875 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
876 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
877 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000878 for (auto &Elem : *this) {
879 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
880 Elem.DeclareTargetLinkVarDecls.push_back(E);
881 return;
882 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000883 }
884 }
885
886 /// Returns the list of globals with declare target link if current directive
887 /// is target.
888 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
889 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
890 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000891 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000892 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000893};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000894
895bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
896 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
897}
898
899bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000900 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
901 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000902}
Alexey Bataeve3727102018-04-18 15:57:46 +0000903
Alexey Bataeved09d242014-05-28 05:53:51 +0000904} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000905
Alexey Bataeve3727102018-04-18 15:57:46 +0000906static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000907 if (const auto *FE = dyn_cast<FullExpr>(E))
908 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000909
Alexey Bataeve3727102018-04-18 15:57:46 +0000910 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +0100911 E = MTE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000912
Alexey Bataeve3727102018-04-18 15:57:46 +0000913 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000914 E = Binder->getSubExpr();
915
Alexey Bataeve3727102018-04-18 15:57:46 +0000916 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000917 E = ICE->getSubExprAsWritten();
918 return E->IgnoreParens();
919}
920
Alexey Bataeve3727102018-04-18 15:57:46 +0000921static Expr *getExprAsWritten(Expr *E) {
922 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
923}
924
925static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
926 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
927 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000928 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000929 const auto *VD = dyn_cast<VarDecl>(D);
930 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000931 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000932 VD = VD->getCanonicalDecl();
933 D = VD;
934 } else {
935 assert(FD);
936 FD = FD->getCanonicalDecl();
937 D = FD;
938 }
939 return D;
940}
941
Alexey Bataeve3727102018-04-18 15:57:46 +0000942static ValueDecl *getCanonicalDecl(ValueDecl *D) {
943 return const_cast<ValueDecl *>(
944 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
945}
946
Richard Smith375dec52019-05-30 23:21:14 +0000947DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000948 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000949 D = getCanonicalDecl(D);
950 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000951 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000952 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000953 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000954 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
955 // in a region but not in construct]
956 // File-scope or namespace-scope variables referenced in called routines
957 // in the region are shared unless they appear in a threadprivate
958 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000959 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000960 DVar.CKind = OMPC_shared;
961
962 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
963 // in a region but not in construct]
964 // Variables with static storage duration that are declared in called
965 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000966 if (VD && VD->hasGlobalStorage())
967 DVar.CKind = OMPC_shared;
968
969 // Non-static data members are shared by default.
970 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000971 DVar.CKind = OMPC_shared;
972
Alexey Bataev758e55e2013-09-06 18:03:48 +0000973 return DVar;
974 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000975
Alexey Bataevec3da872014-01-31 05:15:34 +0000976 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
977 // in a Construct, C/C++, predetermined, p.1]
978 // Variables with automatic storage duration that are declared in a scope
979 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000980 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
981 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000982 DVar.CKind = OMPC_private;
983 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000984 }
985
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000986 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000987 // Explicitly specified attributes and local variables with predetermined
988 // attributes.
989 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000990 const DSAInfo &Data = Iter->SharingMap.lookup(D);
991 DVar.RefExpr = Data.RefExpr.getPointer();
992 DVar.PrivateCopy = Data.PrivateCopy;
993 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000994 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000995 return DVar;
996 }
997
998 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
999 // in a Construct, C/C++, implicitly determined, p.1]
1000 // In a parallel or task construct, the data-sharing attributes of these
1001 // variables are determined by the default clause, if present.
1002 switch (Iter->DefaultAttr) {
1003 case DSA_shared:
1004 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001005 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001006 return DVar;
1007 case DSA_none:
1008 return DVar;
1009 case DSA_unspecified:
1010 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1011 // in a Construct, implicitly determined, p.2]
1012 // In a parallel construct, if no default clause is present, these
1013 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +00001014 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001015 if ((isOpenMPParallelDirective(DVar.DKind) &&
1016 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001017 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001018 DVar.CKind = OMPC_shared;
1019 return DVar;
1020 }
1021
1022 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1023 // in a Construct, implicitly determined, p.4]
1024 // In a task construct, if no default clause is present, a variable that in
1025 // the enclosing context is determined to be shared by all implicit tasks
1026 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001027 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001028 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +00001029 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001030 do {
1031 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001032 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +00001033 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +00001034 // In a task construct, if no default clause is present, a variable
1035 // whose data-sharing attribute is not determined by the rules above is
1036 // firstprivate.
1037 DVarTemp = getDSA(I, D);
1038 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001039 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001040 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001041 return DVar;
1042 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001043 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +00001044 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +00001045 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001046 return DVar;
1047 }
1048 }
1049 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1050 // in a Construct, implicitly determined, p.3]
1051 // For constructs other than task, if no default clause is present, these
1052 // variables inherit their data-sharing attributes from the enclosing
1053 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001054 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001055}
1056
Alexey Bataeve3727102018-04-18 15:57:46 +00001057const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1058 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001059 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001060 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001061 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001062 auto It = StackElem.AlignedMap.find(D);
1063 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001064 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001065 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001066 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001067 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001068 assert(It->second && "Unexpected nullptr expr in the aligned map");
1069 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001070}
1071
Alexey Bataeve3727102018-04-18 15:57:46 +00001072void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001073 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001074 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001075 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001076 StackElem.LCVMap.try_emplace(
1077 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001078}
1079
Alexey Bataeve3727102018-04-18 15:57:46 +00001080const DSAStackTy::LCDeclInfo
1081DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001082 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001083 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001084 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001085 auto It = StackElem.LCVMap.find(D);
1086 if (It != StackElem.LCVMap.end())
1087 return It->second;
1088 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001089}
1090
Alexey Bataeve3727102018-04-18 15:57:46 +00001091const DSAStackTy::LCDeclInfo
1092DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001093 const SharingMapTy *Parent = getSecondOnStackOrNull();
1094 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001095 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001096 auto It = Parent->LCVMap.find(D);
1097 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001098 return It->second;
1099 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001100}
1101
Alexey Bataeve3727102018-04-18 15:57:46 +00001102const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001103 const SharingMapTy *Parent = getSecondOnStackOrNull();
1104 assert(Parent && "Data-sharing attributes stack is empty");
1105 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001106 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001107 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001108 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001109 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001110 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001111}
1112
Alexey Bataeve3727102018-04-18 15:57:46 +00001113void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001114 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001115 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001116 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001117 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001118 Data.Attributes = A;
1119 Data.RefExpr.setPointer(E);
1120 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001121 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001122 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001123 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1124 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1125 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1126 (isLoopControlVariable(D).first && A == OMPC_private));
1127 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1128 Data.RefExpr.setInt(/*IntVal=*/true);
1129 return;
1130 }
1131 const bool IsLastprivate =
1132 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1133 Data.Attributes = A;
1134 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1135 Data.PrivateCopy = PrivateCopy;
1136 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001137 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001138 Data.Attributes = A;
1139 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1140 Data.PrivateCopy = nullptr;
1141 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001142 }
1143}
1144
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001145/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001146static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001147 StringRef Name, const AttrVec *Attrs = nullptr,
1148 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001149 DeclContext *DC = SemaRef.CurContext;
1150 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1151 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001152 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001153 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1154 if (Attrs) {
1155 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1156 I != E; ++I)
1157 Decl->addAttr(*I);
1158 }
1159 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001160 if (OrigRef) {
1161 Decl->addAttr(
1162 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1163 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001164 return Decl;
1165}
1166
1167static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1168 SourceLocation Loc,
1169 bool RefersToCapture = false) {
1170 D->setReferenced();
1171 D->markUsed(S.Context);
1172 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1173 SourceLocation(), D, RefersToCapture, Loc, Ty,
1174 VK_LValue);
1175}
1176
Alexey Bataeve3727102018-04-18 15:57:46 +00001177void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001178 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001179 D = getCanonicalDecl(D);
1180 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001181 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001182 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001183 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001184 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001185 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001186 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001187 "Additional reduction info may be specified only once for reduction "
1188 "items.");
1189 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001190 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001191 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001192 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001193 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1194 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001195 TaskgroupReductionRef =
1196 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001197 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001198}
1199
Alexey Bataeve3727102018-04-18 15:57:46 +00001200void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001201 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001202 D = getCanonicalDecl(D);
1203 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001204 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001205 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001206 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001207 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001208 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001209 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001210 "Additional reduction info may be specified only once for reduction "
1211 "items.");
1212 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001213 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001214 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001215 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001216 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1217 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001218 TaskgroupReductionRef =
1219 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001220 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001221}
1222
Alexey Bataeve3727102018-04-18 15:57:46 +00001223const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1224 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1225 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001226 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001227 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001228 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001229 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001230 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001231 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001232 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001233 if (!ReductionData.ReductionOp ||
1234 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001235 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001236 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001237 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001238 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1239 "expression for the descriptor is not "
1240 "set.");
1241 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001242 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1243 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001244 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001245 return DSAVarData();
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, const Expr *&ReductionRef,
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;
1262 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
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
Richard Smith375dec52019-05-30 23:21:14 +00001273bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001274 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001275 for (const_iterator E = end(); I != E; ++I) {
1276 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1277 isOpenMPTargetExecutionDirective(I->Directive)) {
1278 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1279 Scope *CurScope = getCurScope();
1280 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1281 CurScope = CurScope->getParent();
1282 return CurScope != TopScope;
1283 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001284 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001285 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001286}
1287
Joel E. Dennyd2649292019-01-04 22:11:56 +00001288static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1289 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001290 bool *IsClassType = nullptr) {
1291 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001292 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001293 bool IsConstant = Type.isConstant(Context);
1294 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001295 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1296 ? Type->getAsCXXRecordDecl()
1297 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001298 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1299 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1300 RD = CTD->getTemplatedDecl();
1301 if (IsClassType)
1302 *IsClassType = RD;
1303 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1304 RD->hasDefinition() && RD->hasMutableFields());
1305}
1306
Joel E. Dennyd2649292019-01-04 22:11:56 +00001307static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1308 QualType Type, OpenMPClauseKind CKind,
1309 SourceLocation ELoc,
1310 bool AcceptIfMutable = true,
1311 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001312 ASTContext &Context = SemaRef.getASTContext();
1313 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001314 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1315 unsigned Diag = ListItemNotVar
1316 ? diag::err_omp_const_list_item
1317 : IsClassType ? diag::err_omp_const_not_mutable_variable
1318 : diag::err_omp_const_variable;
1319 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1320 if (!ListItemNotVar && D) {
1321 const VarDecl *VD = dyn_cast<VarDecl>(D);
1322 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1323 VarDecl::DeclarationOnly;
1324 SemaRef.Diag(D->getLocation(),
1325 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1326 << D;
1327 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001328 return true;
1329 }
1330 return false;
1331}
1332
Alexey Bataeve3727102018-04-18 15:57:46 +00001333const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1334 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001335 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001336 DSAVarData DVar;
1337
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001338 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001339 auto TI = Threadprivates.find(D);
1340 if (TI != Threadprivates.end()) {
1341 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001342 DVar.CKind = OMPC_threadprivate;
1343 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001344 }
1345 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001346 DVar.RefExpr = buildDeclRefExpr(
1347 SemaRef, VD, D->getType().getNonReferenceType(),
1348 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1349 DVar.CKind = OMPC_threadprivate;
1350 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001351 return DVar;
1352 }
1353 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1354 // in a Construct, C/C++, predetermined, p.1]
1355 // Variables appearing in threadprivate directives are threadprivate.
1356 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1357 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1358 SemaRef.getLangOpts().OpenMPUseTLS &&
1359 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1360 (VD && VD->getStorageClass() == SC_Register &&
1361 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1362 DVar.RefExpr = buildDeclRefExpr(
1363 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1364 DVar.CKind = OMPC_threadprivate;
1365 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1366 return DVar;
1367 }
1368 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1369 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1370 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001371 const_iterator IterTarget =
1372 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1373 return isOpenMPTargetExecutionDirective(Data.Directive);
1374 });
1375 if (IterTarget != end()) {
1376 const_iterator ParentIterTarget = IterTarget + 1;
1377 for (const_iterator Iter = begin();
1378 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001379 if (isOpenMPLocal(VD, Iter)) {
1380 DVar.RefExpr =
1381 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1382 D->getLocation());
1383 DVar.CKind = OMPC_threadprivate;
1384 return DVar;
1385 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001386 }
Richard Smith375dec52019-05-30 23:21:14 +00001387 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001388 auto DSAIter = IterTarget->SharingMap.find(D);
1389 if (DSAIter != IterTarget->SharingMap.end() &&
1390 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1391 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1392 DVar.CKind = OMPC_threadprivate;
1393 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001394 }
Richard Smith375dec52019-05-30 23:21:14 +00001395 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001396 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001397 D, std::distance(ParentIterTarget, End),
1398 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001399 DVar.RefExpr =
1400 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1401 IterTarget->ConstructLoc);
1402 DVar.CKind = OMPC_threadprivate;
1403 return DVar;
1404 }
1405 }
1406 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001407 }
1408
Alexey Bataev4b465392017-04-26 15:06:24 +00001409 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001410 // Not in OpenMP execution region and top scope was already checked.
1411 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001412
Alexey Bataev758e55e2013-09-06 18:03:48 +00001413 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001414 // in a Construct, C/C++, predetermined, p.4]
1415 // Static data members are shared.
1416 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1417 // in a Construct, C/C++, predetermined, p.7]
1418 // Variables with static storage duration that are declared in a scope
1419 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001420 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001421 // Check for explicitly specified attributes.
1422 const_iterator I = begin();
1423 const_iterator EndI = end();
1424 if (FromParent && I != EndI)
1425 ++I;
1426 auto It = I->SharingMap.find(D);
1427 if (It != I->SharingMap.end()) {
1428 const DSAInfo &Data = It->getSecond();
1429 DVar.RefExpr = Data.RefExpr.getPointer();
1430 DVar.PrivateCopy = Data.PrivateCopy;
1431 DVar.CKind = Data.Attributes;
1432 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1433 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001434 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001435 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001436
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001437 DVar.CKind = OMPC_shared;
1438 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001439 }
1440
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001441 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001442 // The predetermined shared attribute for const-qualified types having no
1443 // mutable members was removed after OpenMP 3.1.
1444 if (SemaRef.LangOpts.OpenMP <= 31) {
1445 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1446 // in a Construct, C/C++, predetermined, p.6]
1447 // Variables with const qualified type having no mutable member are
1448 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001449 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001450 // Variables with const-qualified type having no mutable member may be
1451 // listed in a firstprivate clause, even if they are static data members.
1452 DSAVarData DVarTemp = hasInnermostDSA(
1453 D,
1454 [](OpenMPClauseKind C) {
1455 return C == OMPC_firstprivate || C == OMPC_shared;
1456 },
1457 MatchesAlways, FromParent);
1458 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1459 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001460
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001461 DVar.CKind = OMPC_shared;
1462 return DVar;
1463 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001464 }
1465
Alexey Bataev758e55e2013-09-06 18:03:48 +00001466 // Explicitly specified attributes and local variables with predetermined
1467 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001468 const_iterator I = begin();
1469 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001470 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001471 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001472 auto It = I->SharingMap.find(D);
1473 if (It != I->SharingMap.end()) {
1474 const DSAInfo &Data = It->getSecond();
1475 DVar.RefExpr = Data.RefExpr.getPointer();
1476 DVar.PrivateCopy = Data.PrivateCopy;
1477 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001478 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001479 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001480 }
1481
1482 return DVar;
1483}
1484
Alexey Bataeve3727102018-04-18 15:57:46 +00001485const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1486 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001487 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001488 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001489 return getDSA(I, D);
1490 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001491 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001492 const_iterator StartI = begin();
1493 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001494 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001495 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001496 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001497}
1498
Alexey Bataeve3727102018-04-18 15:57:46 +00001499const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001500DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001501 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1502 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001503 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001504 if (isStackEmpty())
1505 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001506 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001507 const_iterator I = begin();
1508 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001509 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001510 ++I;
1511 for (; I != EndI; ++I) {
1512 if (!DPred(I->Directive) &&
1513 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001514 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001515 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001516 DSAVarData DVar = getDSA(NewI, D);
1517 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001518 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001519 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001520 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001521}
1522
Alexey Bataeve3727102018-04-18 15:57:46 +00001523const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001524 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1525 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001526 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001527 if (isStackEmpty())
1528 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001529 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001530 const_iterator StartI = begin();
1531 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001532 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001533 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001534 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001535 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001536 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001537 DSAVarData DVar = getDSA(NewI, D);
1538 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001539}
1540
Alexey Bataevaac108a2015-06-23 04:51:00 +00001541bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001542 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1543 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001544 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001545 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001546 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001547 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1548 auto I = StackElem.SharingMap.find(D);
1549 if (I != StackElem.SharingMap.end() &&
1550 I->getSecond().RefExpr.getPointer() &&
1551 CPred(I->getSecond().Attributes) &&
1552 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001553 return true;
1554 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001555 auto LI = StackElem.LCVMap.find(D);
1556 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001557 return CPred(OMPC_private);
1558 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001559}
1560
Samuel Antao4be30e92015-10-02 17:14:03 +00001561bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001562 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1563 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001564 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001565 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001566 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1567 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001568}
1569
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001570bool DSAStackTy::hasDirective(
1571 const llvm::function_ref<bool(OpenMPDirectiveKind,
1572 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001573 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001574 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001575 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001576 size_t Skip = FromParent ? 2 : 1;
1577 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1578 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001579 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1580 return true;
1581 }
1582 return false;
1583}
1584
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585void Sema::InitDataSharingAttributesStack() {
1586 VarDataSharingAttributesStack = new DSAStackTy(*this);
1587}
1588
1589#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1590
Alexey Bataev4b465392017-04-26 15:06:24 +00001591void Sema::pushOpenMPFunctionRegion() {
1592 DSAStack->pushFunction();
1593}
1594
1595void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1596 DSAStack->popFunction(OldFSI);
1597}
1598
Alexey Bataevc416e642019-02-08 18:02:25 +00001599static bool isOpenMPDeviceDelayedContext(Sema &S) {
1600 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1601 "Expected OpenMP device compilation.");
1602 return !S.isInOpenMPTargetExecutionDirective() &&
1603 !S.isInOpenMPDeclareTargetContext();
1604}
1605
Alexey Bataev729e2422019-08-23 16:11:14 +00001606namespace {
1607/// Status of the function emission on the host/device.
1608enum class FunctionEmissionStatus {
1609 Emitted,
1610 Discarded,
1611 Unknown,
1612};
1613} // anonymous namespace
1614
Alexey Bataevc416e642019-02-08 18:02:25 +00001615Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1616 unsigned DiagID) {
1617 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1618 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001619 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001620 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1621 switch (FES) {
1622 case FunctionEmissionStatus::Emitted:
1623 Kind = DeviceDiagBuilder::K_Immediate;
1624 break;
1625 case FunctionEmissionStatus::Unknown:
1626 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1627 : DeviceDiagBuilder::K_Immediate;
1628 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001629 case FunctionEmissionStatus::TemplateDiscarded:
1630 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001631 Kind = DeviceDiagBuilder::K_Nop;
1632 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001633 case FunctionEmissionStatus::CUDADiscarded:
1634 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1635 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001636 }
1637
1638 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1639}
1640
Alexey Bataev729e2422019-08-23 16:11:14 +00001641Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1642 unsigned DiagID) {
1643 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1644 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001645 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001646 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1647 switch (FES) {
1648 case FunctionEmissionStatus::Emitted:
1649 Kind = DeviceDiagBuilder::K_Immediate;
1650 break;
1651 case FunctionEmissionStatus::Unknown:
1652 Kind = DeviceDiagBuilder::K_Deferred;
1653 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001654 case FunctionEmissionStatus::TemplateDiscarded:
1655 case FunctionEmissionStatus::OMPDiscarded:
1656 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001657 Kind = DeviceDiagBuilder::K_Nop;
1658 break;
1659 }
1660
1661 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001662}
1663
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001664void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1665 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001666 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1667 "Expected OpenMP device compilation.");
1668 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001669 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001670 FunctionDecl *Caller = getCurFunctionDecl();
1671
Alexey Bataev729e2422019-08-23 16:11:14 +00001672 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001673 if (Caller) {
1674 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1675 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1676 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1677 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1678 "CUDADiscarded unexpected in OpenMP device function check");
1679 if ((CallerS == FunctionEmissionStatus::Emitted ||
1680 (!isOpenMPDeviceDelayedContext(*this) &&
1681 CallerS == FunctionEmissionStatus::Unknown)) &&
1682 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1683 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1684 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1685 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1686 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1687 diag::note_omp_marked_device_type_here)
1688 << HostDevTy;
1689 return;
1690 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001691 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001692 // If the caller is known-emitted, mark the callee as known-emitted.
1693 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001694 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1695 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001696 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001697 markKnownEmitted(*this, Caller, Callee, Loc,
1698 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001699 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001700 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001701 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001702 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001703 else if (Caller)
1704 DeviceCallGraph[Caller].insert({Callee, Loc});
1705}
1706
Alexey Bataev729e2422019-08-23 16:11:14 +00001707void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1708 bool CheckCaller) {
1709 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1710 "Expected OpenMP host compilation.");
1711 assert(Callee && "Callee may not be null.");
1712 Callee = Callee->getMostRecentDecl();
1713 FunctionDecl *Caller = getCurFunctionDecl();
1714
1715 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001716 if (Caller) {
1717 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1718 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1719 assert(
1720 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1721 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1722 "CUDADiscarded unexpected in OpenMP host function check");
1723 if (CallerS == FunctionEmissionStatus::Emitted &&
1724 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1725 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1726 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1727 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1728 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1729 diag::note_omp_marked_device_type_here)
1730 << NoHostDevTy;
1731 return;
1732 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001733 }
1734 // If the caller is known-emitted, mark the callee as known-emitted.
1735 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001736 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1737 if ((!CheckCaller && !Caller) ||
1738 (Caller &&
1739 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1740 markKnownEmitted(
1741 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1742 return CheckCaller &&
1743 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1744 });
1745 else if (Caller)
1746 DeviceCallGraph[Caller].insert({Callee, Loc});
1747 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001748}
1749
Alexey Bataev123ad192019-02-27 20:29:45 +00001750void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1751 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1752 "OpenMP device compilation mode is expected.");
1753 QualType Ty = E->getType();
1754 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001755 ((Ty->isFloat128Type() ||
1756 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1757 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001758 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1759 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001760 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1761 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1762 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001763}
1764
cchene06f3e02019-11-15 13:02:06 -05001765static OpenMPDefaultmapClauseKind
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001766getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1767 if (LO.OpenMP <= 45) {
1768 if (VD->getType().getNonReferenceType()->isScalarType())
1769 return OMPC_DEFAULTMAP_scalar;
1770 return OMPC_DEFAULTMAP_aggregate;
1771 }
cchene06f3e02019-11-15 13:02:06 -05001772 if (VD->getType().getNonReferenceType()->isAnyPointerType())
1773 return OMPC_DEFAULTMAP_pointer;
1774 if (VD->getType().getNonReferenceType()->isScalarType())
1775 return OMPC_DEFAULTMAP_scalar;
1776 return OMPC_DEFAULTMAP_aggregate;
1777}
1778
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001779bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1780 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001781 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1782
Alexey Bataeve3727102018-04-18 15:57:46 +00001783 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001784 bool IsByRef = true;
1785
1786 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001787 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001788 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001789
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001790 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001791 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001792 // This table summarizes how a given variable should be passed to the device
1793 // given its type and the clauses where it appears. This table is based on
1794 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1795 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1796 //
1797 // =========================================================================
1798 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1799 // | |(tofrom:scalar)| | pvt | | | |
1800 // =========================================================================
1801 // | scl | | | | - | | bycopy|
1802 // | scl | | - | x | - | - | bycopy|
1803 // | scl | | x | - | - | - | null |
1804 // | scl | x | | | - | | byref |
1805 // | scl | x | - | x | - | - | bycopy|
1806 // | scl | x | x | - | - | - | null |
1807 // | scl | | - | - | - | x | byref |
1808 // | scl | x | - | - | - | x | byref |
1809 //
1810 // | agg | n.a. | | | - | | byref |
1811 // | agg | n.a. | - | x | - | - | byref |
1812 // | agg | n.a. | x | - | - | - | null |
1813 // | agg | n.a. | - | - | - | x | byref |
1814 // | agg | n.a. | - | - | - | x[] | byref |
1815 //
1816 // | ptr | n.a. | | | - | | bycopy|
1817 // | ptr | n.a. | - | x | - | - | bycopy|
1818 // | ptr | n.a. | x | - | - | - | null |
1819 // | ptr | n.a. | - | - | - | x | byref |
1820 // | ptr | n.a. | - | - | - | x[] | bycopy|
1821 // | ptr | n.a. | - | - | x | | bycopy|
1822 // | ptr | n.a. | - | - | x | x | bycopy|
1823 // | ptr | n.a. | - | - | x | x[] | bycopy|
1824 // =========================================================================
1825 // Legend:
1826 // scl - scalar
1827 // ptr - pointer
1828 // agg - aggregate
1829 // x - applies
1830 // - - invalid in this combination
1831 // [] - mapped with an array section
1832 // byref - should be mapped by reference
1833 // byval - should be mapped by value
1834 // null - initialize a local variable to null on the device
1835 //
1836 // Observations:
1837 // - All scalar declarations that show up in a map clause have to be passed
1838 // by reference, because they may have been mapped in the enclosing data
1839 // environment.
1840 // - If the scalar value does not fit the size of uintptr, it has to be
1841 // passed by reference, regardless the result in the table above.
1842 // - For pointers mapped by value that have either an implicit map or an
1843 // array section, the runtime library may pass the NULL value to the
1844 // device instead of the value passed to it by the compiler.
1845
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001846 if (Ty->isReferenceType())
1847 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001848
1849 // Locate map clauses and see if the variable being captured is referred to
1850 // in any of those clauses. Here we only care about variables, not fields,
1851 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001852 bool IsVariableAssociatedWithSection = false;
1853
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001854 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001855 D, Level,
1856 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1857 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001858 MapExprComponents,
1859 OpenMPClauseKind WhereFoundClauseKind) {
1860 // Only the map clause information influences how a variable is
1861 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001862 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001863 if (WhereFoundClauseKind != OMPC_map)
1864 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001865
1866 auto EI = MapExprComponents.rbegin();
1867 auto EE = MapExprComponents.rend();
1868
1869 assert(EI != EE && "Invalid map expression!");
1870
1871 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1872 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1873
1874 ++EI;
1875 if (EI == EE)
1876 return false;
1877
1878 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1879 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1880 isa<MemberExpr>(EI->getAssociatedExpression())) {
1881 IsVariableAssociatedWithSection = true;
1882 // There is nothing more we need to know about this variable.
1883 return true;
1884 }
1885
1886 // Keep looking for more map info.
1887 return false;
1888 });
1889
1890 if (IsVariableUsedInMapClause) {
1891 // If variable is identified in a map clause it is always captured by
1892 // reference except if it is a pointer that is dereferenced somehow.
1893 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1894 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001895 // By default, all the data that has a scalar type is mapped by copy
1896 // (except for reduction variables).
cchene06f3e02019-11-15 13:02:06 -05001897 // Defaultmap scalar is mutual exclusive to defaultmap pointer
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001898 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001899 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1900 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001901 !Ty->isScalarType() ||
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001902 DSAStack->isDefaultmapCapturedByRef(
1903 Level, getVariableCategoryFromDecl(LangOpts, D)) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001904 DSAStack->hasExplicitDSA(
1905 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001906 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001907 }
1908
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001909 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001910 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001911 ((IsVariableUsedInMapClause &&
1912 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1913 OMPD_target) ||
1914 !DSAStack->hasExplicitDSA(
1915 D,
1916 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1917 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001918 // If the variable is artificial and must be captured by value - try to
1919 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001920 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1921 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001922 }
1923
Samuel Antao86ace552016-04-27 22:40:57 +00001924 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001925 // and alignment, because the runtime library only deals with uintptr types.
1926 // If it does not fit the uintptr size, we need to pass the data by reference
1927 // instead.
1928 if (!IsByRef &&
1929 (Ctx.getTypeSizeInChars(Ty) >
1930 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001931 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001932 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001933 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001934
1935 return IsByRef;
1936}
1937
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001938unsigned Sema::getOpenMPNestingLevel() const {
1939 assert(getLangOpts().OpenMP);
1940 return DSAStack->getNestingLevel();
1941}
1942
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001943bool Sema::isInOpenMPTargetExecutionDirective() const {
1944 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1945 !DSAStack->isClauseParsingMode()) ||
1946 DSAStack->hasDirective(
1947 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1948 SourceLocation) -> bool {
1949 return isOpenMPTargetExecutionDirective(K);
1950 },
1951 false);
1952}
1953
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001954VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1955 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001956 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001957 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001958
Alexey Bataev7c860692019-10-25 16:35:32 -04001959 auto *VD = dyn_cast<VarDecl>(D);
1960 // Do not capture constexpr variables.
1961 if (VD && VD->isConstexpr())
1962 return nullptr;
1963
Richard Smith0621a8f2019-05-31 00:45:10 +00001964 // If we want to determine whether the variable should be captured from the
1965 // perspective of the current capturing scope, and we've already left all the
1966 // capturing scopes of the top directive on the stack, check from the
1967 // perspective of its parent directive (if any) instead.
1968 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1969 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1970
Samuel Antao4be30e92015-10-02 17:14:03 +00001971 // If we are attempting to capture a global variable in a directive with
1972 // 'target' we return true so that this global is also mapped to the device.
1973 //
Richard Smith0621a8f2019-05-31 00:45:10 +00001974 if (VD && !VD->hasLocalStorage() &&
1975 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1976 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001977 // Try to mark variable as declare target if it is used in capturing
1978 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00001979 if (LangOpts.OpenMP <= 45 &&
1980 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001981 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001982 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001983 } else if (isInOpenMPTargetExecutionDirective()) {
1984 // If the declaration is enclosed in a 'declare target' directive,
1985 // then it should not be captured.
1986 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001987 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001988 return nullptr;
1989 return VD;
1990 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001991 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001992
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001993 if (CheckScopeInfo) {
1994 bool OpenMPFound = false;
1995 for (unsigned I = StopAt + 1; I > 0; --I) {
1996 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1997 if(!isa<CapturingScopeInfo>(FSI))
1998 return nullptr;
1999 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2000 if (RSI->CapRegionKind == CR_OpenMP) {
2001 OpenMPFound = true;
2002 break;
2003 }
2004 }
2005 if (!OpenMPFound)
2006 return nullptr;
2007 }
2008
Alexey Bataev48977c32015-08-04 08:10:48 +00002009 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2010 (!DSAStack->isClauseParsingMode() ||
2011 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002012 auto &&Info = DSAStack->isLoopControlVariable(D);
2013 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002014 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002015 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002016 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002017 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00002018 DSAStackTy::DSAVarData DVarPrivate =
2019 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00002022 // Threadprivate variables must not be captured.
2023 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
2024 return nullptr;
2025 // The variable is not private or it is the variable in the directive with
2026 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002027 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
2028 [](OpenMPDirectiveKind) { return true; },
2029 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002030 if (DVarPrivate.CKind != OMPC_unknown ||
2031 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002032 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002033 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00002034 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00002035}
2036
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002037void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2038 unsigned Level) const {
2039 SmallVector<OpenMPDirectiveKind, 4> Regions;
2040 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2041 FunctionScopesIndex -= Regions.size();
2042}
2043
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002044void Sema::startOpenMPLoop() {
2045 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2046 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2047 DSAStack->loopInit();
2048}
2049
Alexey Bataevbef93a92019-10-07 18:54:57 +00002050void Sema::startOpenMPCXXRangeFor() {
2051 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2052 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2053 DSAStack->resetPossibleLoopCounter();
2054 DSAStack->loopStart();
2055 }
2056}
2057
Alexey Bataeve3727102018-04-18 15:57:46 +00002058bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002059 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002060 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2061 if (DSAStack->getAssociatedLoops() > 0 &&
2062 !DSAStack->isLoopStarted()) {
2063 DSAStack->resetPossibleLoopCounter(D);
2064 DSAStack->loopStart();
2065 return true;
2066 }
2067 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2068 DSAStack->isLoopControlVariable(D).first) &&
2069 !DSAStack->hasExplicitDSA(
2070 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2071 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2072 return true;
2073 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002074 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2075 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2076 DSAStack->isForceVarCapturing() &&
2077 !DSAStack->hasExplicitDSA(
2078 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2079 return true;
2080 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002081 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002082 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002083 (DSAStack->isClauseParsingMode() &&
2084 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002085 // Consider taskgroup reduction descriptor variable a private to avoid
2086 // possible capture in the region.
2087 (DSAStack->hasExplicitDirective(
2088 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2089 Level) &&
2090 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002091}
2092
Alexey Bataeve3727102018-04-18 15:57:46 +00002093void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2094 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002095 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2096 D = getCanonicalDecl(D);
2097 OpenMPClauseKind OMPC = OMPC_unknown;
2098 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2099 const unsigned NewLevel = I - 1;
2100 if (DSAStack->hasExplicitDSA(D,
2101 [&OMPC](const OpenMPClauseKind K) {
2102 if (isOpenMPPrivate(K)) {
2103 OMPC = K;
2104 return true;
2105 }
2106 return false;
2107 },
2108 NewLevel))
2109 break;
2110 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2111 D, NewLevel,
2112 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2113 OpenMPClauseKind) { return true; })) {
2114 OMPC = OMPC_map;
2115 break;
2116 }
2117 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2118 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002119 OMPC = OMPC_map;
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002120 if (DSAStack->mustBeFirstprivateAtLevel(
2121 NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002122 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002123 break;
2124 }
2125 }
2126 if (OMPC != OMPC_unknown)
2127 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2128}
2129
Alexey Bataeve3727102018-04-18 15:57:46 +00002130bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2131 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002132 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2133 // Return true if the current level is no longer enclosed in a target region.
2134
Alexey Bataeve3727102018-04-18 15:57:46 +00002135 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002136 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002137 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2138 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00002139}
2140
Alexey Bataeved09d242014-05-28 05:53:51 +00002141void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002142
Alexey Bataev729e2422019-08-23 16:11:14 +00002143void Sema::finalizeOpenMPDelayedAnalysis() {
2144 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2145 // Diagnose implicit declare target functions and their callees.
2146 for (const auto &CallerCallees : DeviceCallGraph) {
2147 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2148 OMPDeclareTargetDeclAttr::getDeviceType(
2149 CallerCallees.getFirst()->getMostRecentDecl());
2150 // Ignore host functions during device analyzis.
2151 if (LangOpts.OpenMPIsDevice && DevTy &&
2152 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2153 continue;
2154 // Ignore nohost functions during host analyzis.
2155 if (!LangOpts.OpenMPIsDevice && DevTy &&
2156 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2157 continue;
2158 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2159 &Callee : CallerCallees.getSecond()) {
2160 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2161 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2162 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2163 if (LangOpts.OpenMPIsDevice && DevTy &&
2164 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2165 // Diagnose host function called during device codegen.
2166 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2167 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2168 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2169 << HostDevTy << 0;
2170 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2171 diag::note_omp_marked_device_type_here)
2172 << HostDevTy;
2173 continue;
2174 }
2175 if (!LangOpts.OpenMPIsDevice && DevTy &&
2176 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2177 // Diagnose nohost function called during host codegen.
2178 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2179 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2180 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2181 << NoHostDevTy << 1;
2182 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2183 diag::note_omp_marked_device_type_here)
2184 << NoHostDevTy;
2185 continue;
2186 }
2187 }
2188 }
2189}
2190
Alexey Bataev758e55e2013-09-06 18:03:48 +00002191void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2192 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002193 Scope *CurScope, SourceLocation Loc) {
2194 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002195 PushExpressionEvaluationContext(
2196 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002197}
2198
Alexey Bataevaac108a2015-06-23 04:51:00 +00002199void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2200 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002201}
2202
Alexey Bataevaac108a2015-06-23 04:51:00 +00002203void Sema::EndOpenMPClause() {
2204 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002205}
2206
Alexey Bataeve106f252019-04-01 14:25:31 +00002207static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2208 ArrayRef<OMPClause *> Clauses);
2209
Alexey Bataev758e55e2013-09-06 18:03:48 +00002210void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002211 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2212 // A variable of class type (or array thereof) that appears in a lastprivate
2213 // clause requires an accessible, unambiguous default constructor for the
2214 // class type, unless the list item is also specified in a firstprivate
2215 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002216 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2217 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002218 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2219 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002220 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002221 if (DE->isValueDependent() || DE->isTypeDependent()) {
2222 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002223 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002224 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002225 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002226 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002227 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002228 const DSAStackTy::DSAVarData DVar =
2229 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002230 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002231 // Generate helper private variable and initialize it with the
2232 // default value. The address of the original variable is replaced
2233 // by the address of the new private variable in CodeGen. This new
2234 // variable is not added to IdResolver, so the code in the OpenMP
2235 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002236 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002237 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002238 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002239 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002240 if (VDPrivate->isInvalidDecl()) {
2241 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002242 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002243 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002244 PrivateCopies.push_back(buildDeclRefExpr(
2245 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002246 } else {
2247 // The variable is also a firstprivate, so initialization sequence
2248 // for private copy is generated already.
2249 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002250 }
2251 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002252 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002253 }
2254 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002255 // Check allocate clauses.
2256 if (!CurContext->isDependentContext())
2257 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002258 }
2259
Alexey Bataev758e55e2013-09-06 18:03:48 +00002260 DSAStack->pop();
2261 DiscardCleanupsInEvaluationContext();
2262 PopExpressionEvaluationContext();
2263}
2264
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002265static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2266 Expr *NumIterations, Sema &SemaRef,
2267 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002268
Alexey Bataeva769e072013-03-22 06:34:35 +00002269namespace {
2270
Alexey Bataeve3727102018-04-18 15:57:46 +00002271class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002272private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002273 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002274
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002275public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002276 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002277 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002278 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002279 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002280 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002281 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2282 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002283 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002284 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002285 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002286
2287 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002288 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002289 }
2290
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002291};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002292
Alexey Bataeve3727102018-04-18 15:57:46 +00002293class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002294private:
2295 Sema &SemaRef;
2296
2297public:
2298 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2299 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2300 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002301 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2302 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002303 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2304 SemaRef.getCurScope());
2305 }
2306 return false;
2307 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002308
2309 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002310 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002311 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002312};
2313
Alexey Bataeved09d242014-05-28 05:53:51 +00002314} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002315
2316ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2317 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002318 const DeclarationNameInfo &Id,
2319 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002320 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2321 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2322
2323 if (Lookup.isAmbiguous())
2324 return ExprError();
2325
2326 VarDecl *VD;
2327 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002328 VarDeclFilterCCC CCC(*this);
2329 if (TypoCorrection Corrected =
2330 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2331 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002332 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002333 PDiag(Lookup.empty()
2334 ? diag::err_undeclared_var_use_suggest
2335 : diag::err_omp_expected_var_arg_suggest)
2336 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002337 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002338 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002339 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2340 : diag::err_omp_expected_var_arg)
2341 << Id.getName();
2342 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002343 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002344 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2345 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2346 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2347 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002348 }
2349 Lookup.suppressDiagnostics();
2350
2351 // OpenMP [2.9.2, Syntax, C/C++]
2352 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002353 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002354 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002355 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002356 bool IsDecl =
2357 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002358 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002359 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2360 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002361 return ExprError();
2362 }
2363
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002364 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002365 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002366 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2367 // A threadprivate directive for file-scope variables must appear outside
2368 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002369 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2370 !getCurLexicalContext()->isTranslationUnit()) {
2371 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002372 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002373 bool IsDecl =
2374 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2375 Diag(VD->getLocation(),
2376 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2377 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002378 return ExprError();
2379 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002380 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2381 // A threadprivate directive for static class member variables must appear
2382 // in the class definition, in the same scope in which the member
2383 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002384 if (CanonicalVD->isStaticDataMember() &&
2385 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2386 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002387 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002388 bool IsDecl =
2389 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2390 Diag(VD->getLocation(),
2391 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2392 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002393 return ExprError();
2394 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002395 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2396 // A threadprivate directive for namespace-scope variables must appear
2397 // outside any definition or declaration other than the namespace
2398 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002399 if (CanonicalVD->getDeclContext()->isNamespace() &&
2400 (!getCurLexicalContext()->isFileContext() ||
2401 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2402 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002403 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002404 bool IsDecl =
2405 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2406 Diag(VD->getLocation(),
2407 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2408 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002409 return ExprError();
2410 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002411 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2412 // A threadprivate directive for static block-scope variables must appear
2413 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002414 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002415 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002416 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002417 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002418 bool IsDecl =
2419 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2420 Diag(VD->getLocation(),
2421 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2422 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002423 return ExprError();
2424 }
2425
2426 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2427 // A threadprivate directive must lexically precede all references to any
2428 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002429 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2430 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002431 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002432 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002433 return ExprError();
2434 }
2435
2436 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002437 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2438 SourceLocation(), VD,
2439 /*RefersToEnclosingVariableOrCapture=*/false,
2440 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002441}
2442
Alexey Bataeved09d242014-05-28 05:53:51 +00002443Sema::DeclGroupPtrTy
2444Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2445 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002446 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002447 CurContext->addDecl(D);
2448 return DeclGroupPtrTy::make(DeclGroupRef(D));
2449 }
David Blaikie0403cb12016-01-15 23:43:25 +00002450 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002451}
2452
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002453namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002454class LocalVarRefChecker final
2455 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002456 Sema &SemaRef;
2457
2458public:
2459 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002460 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002461 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002462 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002463 diag::err_omp_local_var_in_threadprivate_init)
2464 << E->getSourceRange();
2465 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2466 << VD << VD->getSourceRange();
2467 return true;
2468 }
2469 }
2470 return false;
2471 }
2472 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002473 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002474 if (Child && Visit(Child))
2475 return true;
2476 }
2477 return false;
2478 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002479 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002480};
2481} // namespace
2482
Alexey Bataeved09d242014-05-28 05:53:51 +00002483OMPThreadPrivateDecl *
2484Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002485 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002486 for (Expr *RefExpr : VarList) {
2487 auto *DE = cast<DeclRefExpr>(RefExpr);
2488 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002489 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002490
Alexey Bataev376b4a42016-02-09 09:41:09 +00002491 // Mark variable as used.
2492 VD->setReferenced();
2493 VD->markUsed(Context);
2494
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002495 QualType QType = VD->getType();
2496 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2497 // It will be analyzed later.
2498 Vars.push_back(DE);
2499 continue;
2500 }
2501
Alexey Bataeva769e072013-03-22 06:34:35 +00002502 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2503 // A threadprivate variable must not have an incomplete type.
2504 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002505 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002506 continue;
2507 }
2508
2509 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2510 // A threadprivate variable must not have a reference type.
2511 if (VD->getType()->isReferenceType()) {
2512 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002513 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2514 bool IsDecl =
2515 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2516 Diag(VD->getLocation(),
2517 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2518 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002519 continue;
2520 }
2521
Samuel Antaof8b50122015-07-13 22:54:53 +00002522 // Check if this is a TLS variable. If TLS is not being supported, produce
2523 // the corresponding diagnostic.
2524 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2525 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2526 getLangOpts().OpenMPUseTLS &&
2527 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002528 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2529 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002530 Diag(ILoc, diag::err_omp_var_thread_local)
2531 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002532 bool IsDecl =
2533 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2534 Diag(VD->getLocation(),
2535 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2536 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002537 continue;
2538 }
2539
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002540 // Check if initial value of threadprivate variable reference variable with
2541 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002542 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002543 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002544 if (Checker.Visit(Init))
2545 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002546 }
2547
Alexey Bataeved09d242014-05-28 05:53:51 +00002548 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002549 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002550 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2551 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002552 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002553 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002554 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002555 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002556 if (!Vars.empty()) {
2557 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2558 Vars);
2559 D->setAccess(AS_public);
2560 }
2561 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002562}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002563
Alexey Bataev27ef9512019-03-20 20:14:22 +00002564static OMPAllocateDeclAttr::AllocatorTypeTy
2565getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2566 if (!Allocator)
2567 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2568 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2569 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002570 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002571 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002572 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002573 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002574 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2575 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2576 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002577 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002578 llvm::FoldingSetNodeID AEId, DAEId;
2579 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2580 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2581 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002582 AllocatorKindRes = AllocatorKind;
2583 break;
2584 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002585 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002586 return AllocatorKindRes;
2587}
2588
Alexey Bataeve106f252019-04-01 14:25:31 +00002589static bool checkPreviousOMPAllocateAttribute(
2590 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2591 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2592 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2593 return false;
2594 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2595 Expr *PrevAllocator = A->getAllocator();
2596 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2597 getAllocatorKind(S, Stack, PrevAllocator);
2598 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2599 if (AllocatorsMatch &&
2600 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2601 Allocator && PrevAllocator) {
2602 const Expr *AE = Allocator->IgnoreParenImpCasts();
2603 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2604 llvm::FoldingSetNodeID AEId, PAEId;
2605 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2606 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2607 AllocatorsMatch = AEId == PAEId;
2608 }
2609 if (!AllocatorsMatch) {
2610 SmallString<256> AllocatorBuffer;
2611 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2612 if (Allocator)
2613 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2614 SmallString<256> PrevAllocatorBuffer;
2615 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2616 if (PrevAllocator)
2617 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2618 S.getPrintingPolicy());
2619
2620 SourceLocation AllocatorLoc =
2621 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2622 SourceRange AllocatorRange =
2623 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2624 SourceLocation PrevAllocatorLoc =
2625 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2626 SourceRange PrevAllocatorRange =
2627 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2628 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2629 << (Allocator ? 1 : 0) << AllocatorStream.str()
2630 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2631 << AllocatorRange;
2632 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2633 << PrevAllocatorRange;
2634 return true;
2635 }
2636 return false;
2637}
2638
2639static void
2640applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2641 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2642 Expr *Allocator, SourceRange SR) {
2643 if (VD->hasAttr<OMPAllocateDeclAttr>())
2644 return;
2645 if (Allocator &&
2646 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2647 Allocator->isInstantiationDependent() ||
2648 Allocator->containsUnexpandedParameterPack()))
2649 return;
2650 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2651 Allocator, SR);
2652 VD->addAttr(A);
2653 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2654 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2655}
2656
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002657Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2658 SourceLocation Loc, ArrayRef<Expr *> VarList,
2659 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2660 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2661 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002662 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002663 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2664 // allocate directives that appear in a target region must specify an
2665 // allocator clause unless a requires directive with the dynamic_allocators
2666 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002667 if (LangOpts.OpenMPIsDevice &&
2668 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002669 targetDiag(Loc, diag::err_expected_allocator_clause);
2670 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002671 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002672 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002673 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2674 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002675 SmallVector<Expr *, 8> Vars;
2676 for (Expr *RefExpr : VarList) {
2677 auto *DE = cast<DeclRefExpr>(RefExpr);
2678 auto *VD = cast<VarDecl>(DE->getDecl());
2679
2680 // Check if this is a TLS variable or global register.
2681 if (VD->getTLSKind() != VarDecl::TLS_None ||
2682 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2683 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2684 !VD->isLocalVarDecl()))
2685 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002686
Alexey Bataev282555a2019-03-19 20:33:44 +00002687 // If the used several times in the allocate directive, the same allocator
2688 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002689 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2690 AllocatorKind, Allocator))
2691 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002692
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002693 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2694 // If a list item has a static storage type, the allocator expression in the
2695 // allocator clause must be a constant expression that evaluates to one of
2696 // the predefined memory allocator values.
2697 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002698 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002699 Diag(Allocator->getExprLoc(),
2700 diag::err_omp_expected_predefined_allocator)
2701 << Allocator->getSourceRange();
2702 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2703 VarDecl::DeclarationOnly;
2704 Diag(VD->getLocation(),
2705 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2706 << VD;
2707 continue;
2708 }
2709 }
2710
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002711 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002712 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2713 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002714 }
2715 if (Vars.empty())
2716 return nullptr;
2717 if (!Owner)
2718 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002719 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002720 D->setAccess(AS_public);
2721 Owner->addDecl(D);
2722 return DeclGroupPtrTy::make(DeclGroupRef(D));
2723}
2724
2725Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002726Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2727 ArrayRef<OMPClause *> ClauseList) {
2728 OMPRequiresDecl *D = nullptr;
2729 if (!CurContext->isFileContext()) {
2730 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2731 } else {
2732 D = CheckOMPRequiresDecl(Loc, ClauseList);
2733 if (D) {
2734 CurContext->addDecl(D);
2735 DSAStack->addRequiresDecl(D);
2736 }
2737 }
2738 return DeclGroupPtrTy::make(DeclGroupRef(D));
2739}
2740
2741OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2742 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002743 /// For target specific clauses, the requires directive cannot be
2744 /// specified after the handling of any of the target regions in the
2745 /// current compilation unit.
2746 ArrayRef<SourceLocation> TargetLocations =
2747 DSAStack->getEncounteredTargetLocs();
2748 if (!TargetLocations.empty()) {
2749 for (const OMPClause *CNew : ClauseList) {
2750 // Check if any of the requires clauses affect target regions.
2751 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2752 isa<OMPUnifiedAddressClause>(CNew) ||
2753 isa<OMPReverseOffloadClause>(CNew) ||
2754 isa<OMPDynamicAllocatorsClause>(CNew)) {
2755 Diag(Loc, diag::err_omp_target_before_requires)
2756 << getOpenMPClauseName(CNew->getClauseKind());
2757 for (SourceLocation TargetLoc : TargetLocations) {
2758 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2759 }
2760 }
2761 }
2762 }
2763
Kelvin Li1408f912018-09-26 04:28:39 +00002764 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2765 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2766 ClauseList);
2767 return nullptr;
2768}
2769
Alexey Bataeve3727102018-04-18 15:57:46 +00002770static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2771 const ValueDecl *D,
2772 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002773 bool IsLoopIterVar = false) {
2774 if (DVar.RefExpr) {
2775 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2776 << getOpenMPClauseName(DVar.CKind);
2777 return;
2778 }
2779 enum {
2780 PDSA_StaticMemberShared,
2781 PDSA_StaticLocalVarShared,
2782 PDSA_LoopIterVarPrivate,
2783 PDSA_LoopIterVarLinear,
2784 PDSA_LoopIterVarLastprivate,
2785 PDSA_ConstVarShared,
2786 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002787 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002788 PDSA_LocalVarPrivate,
2789 PDSA_Implicit
2790 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002791 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002792 auto ReportLoc = D->getLocation();
2793 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002794 if (IsLoopIterVar) {
2795 if (DVar.CKind == OMPC_private)
2796 Reason = PDSA_LoopIterVarPrivate;
2797 else if (DVar.CKind == OMPC_lastprivate)
2798 Reason = PDSA_LoopIterVarLastprivate;
2799 else
2800 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002801 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2802 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002803 Reason = PDSA_TaskVarFirstprivate;
2804 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002805 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002806 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002807 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002808 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002809 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002810 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002811 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002812 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002813 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002814 ReportHint = true;
2815 Reason = PDSA_LocalVarPrivate;
2816 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002817 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002818 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002819 << Reason << ReportHint
2820 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2821 } else if (DVar.ImplicitDSALoc.isValid()) {
2822 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2823 << getOpenMPClauseName(DVar.CKind);
2824 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002825}
2826
cchene06f3e02019-11-15 13:02:06 -05002827static OpenMPMapClauseKind
2828getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
2829 bool IsAggregateOrDeclareTarget) {
2830 OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
2831 switch (M) {
2832 case OMPC_DEFAULTMAP_MODIFIER_alloc:
2833 Kind = OMPC_MAP_alloc;
2834 break;
2835 case OMPC_DEFAULTMAP_MODIFIER_to:
2836 Kind = OMPC_MAP_to;
2837 break;
2838 case OMPC_DEFAULTMAP_MODIFIER_from:
2839 Kind = OMPC_MAP_from;
2840 break;
2841 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
2842 Kind = OMPC_MAP_tofrom;
2843 break;
2844 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
2845 case OMPC_DEFAULTMAP_MODIFIER_last:
2846 llvm_unreachable("Unexpected defaultmap implicit behavior");
2847 case OMPC_DEFAULTMAP_MODIFIER_none:
2848 case OMPC_DEFAULTMAP_MODIFIER_default:
2849 case OMPC_DEFAULTMAP_MODIFIER_unknown:
2850 // IsAggregateOrDeclareTarget could be true if:
2851 // 1. the implicit behavior for aggregate is tofrom
2852 // 2. it's a declare target link
2853 if (IsAggregateOrDeclareTarget) {
2854 Kind = OMPC_MAP_tofrom;
2855 break;
2856 }
2857 llvm_unreachable("Unexpected defaultmap implicit behavior");
2858 }
2859 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
2860 return Kind;
2861}
2862
Alexey Bataev758e55e2013-09-06 18:03:48 +00002863namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002864class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002865 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002866 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002867 bool ErrorFound = false;
Alexey Bataevc09c0652019-10-29 10:06:11 -04002868 bool TryCaptureCXXThisMembers = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00002869 CapturedStmt *CS = nullptr;
2870 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
cchene06f3e02019-11-15 13:02:06 -05002871 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
Alexey Bataeve3727102018-04-18 15:57:46 +00002872 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2873 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002874
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002875 void VisitSubCaptures(OMPExecutableDirective *S) {
2876 // Check implicitly captured variables.
2877 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2878 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002879 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataevc09c0652019-10-29 10:06:11 -04002880 // Try to capture inner this->member references to generate correct mappings
2881 // and diagnostics.
2882 if (TryCaptureCXXThisMembers ||
2883 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2884 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2885 [](const CapturedStmt::Capture &C) {
2886 return C.capturesThis();
2887 }))) {
2888 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2889 TryCaptureCXXThisMembers = true;
2890 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2891 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2892 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002893 }
2894
Alexey Bataev758e55e2013-09-06 18:03:48 +00002895public:
2896 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataevc09c0652019-10-29 10:06:11 -04002897 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
2898 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
2899 E->isInstantiationDependent())
Alexey Bataev07b79c22016-04-29 09:56:11 +00002900 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002901 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002902 // Check the datasharing rules for the expressions in the clauses.
2903 if (!CS) {
2904 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2905 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2906 Visit(CED->getInit());
2907 return;
2908 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002909 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2910 // Do not analyze internal variables and do not enclose them into
2911 // implicit clauses.
2912 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002913 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002914 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002915 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002916 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002917
Alexey Bataeve3727102018-04-18 15:57:46 +00002918 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002919 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002920 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002921 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002922
Alexey Bataevafe50572017-10-06 17:00:28 +00002923 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002924 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002925 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002926 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002927 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2928 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002929 return;
2930
Alexey Bataeve3727102018-04-18 15:57:46 +00002931 SourceLocation ELoc = E->getExprLoc();
2932 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002933 // The default(none) clause requires that each variable that is referenced
2934 // in the construct, and does not have a predetermined data-sharing
2935 // attribute, must have its data-sharing attribute explicitly determined
2936 // by being listed in a data-sharing attribute clause.
2937 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002938 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002939 VarsWithInheritedDSA.count(VD) == 0) {
2940 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002941 return;
2942 }
2943
cchene06f3e02019-11-15 13:02:06 -05002944 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
2945 // If implicit-behavior is none, each variable referenced in the
2946 // construct that does not have a predetermined data-sharing attribute
2947 // and does not appear in a to or link clause on a declare target
2948 // directive must be listed in a data-mapping attribute clause, a
2949 // data-haring attribute clause (including a data-sharing attribute
2950 // clause on a combined construct where target. is one of the
2951 // constituent constructs), or an is_device_ptr clause.
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002952 OpenMPDefaultmapClauseKind ClauseKind =
2953 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
cchene06f3e02019-11-15 13:02:06 -05002954 if (SemaRef.getLangOpts().OpenMP >= 50) {
2955 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
2956 OMPC_DEFAULTMAP_MODIFIER_none;
2957 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
2958 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
2959 // Only check for data-mapping attribute and is_device_ptr here
2960 // since we have already make sure that the declaration does not
2961 // have a data-sharing attribute above
2962 if (!Stack->checkMappableExprComponentListsForDecl(
2963 VD, /*CurrentRegionOnly=*/true,
2964 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
2965 MapExprComponents,
2966 OpenMPClauseKind) {
2967 auto MI = MapExprComponents.rbegin();
2968 auto ME = MapExprComponents.rend();
2969 return MI != ME && MI->getAssociatedDeclaration() == VD;
2970 })) {
2971 VarsWithInheritedDSA[VD] = E;
2972 return;
2973 }
2974 }
2975 }
2976
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002977 if (isOpenMPTargetExecutionDirective(DKind) &&
2978 !Stack->isLoopControlVariable(VD).first) {
2979 if (!Stack->checkMappableExprComponentListsForDecl(
2980 VD, /*CurrentRegionOnly=*/true,
2981 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2982 StackComponents,
2983 OpenMPClauseKind) {
2984 // Variable is used if it has been marked as an array, array
2985 // section or the variable iself.
2986 return StackComponents.size() == 1 ||
2987 std::all_of(
2988 std::next(StackComponents.rbegin()),
2989 StackComponents.rend(),
2990 [](const OMPClauseMappableExprCommon::
2991 MappableComponent &MC) {
2992 return MC.getAssociatedDeclaration() ==
2993 nullptr &&
2994 (isa<OMPArraySectionExpr>(
2995 MC.getAssociatedExpression()) ||
2996 isa<ArraySubscriptExpr>(
2997 MC.getAssociatedExpression()));
2998 });
2999 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003000 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003001 // By default lambdas are captured as firstprivates.
3002 if (const auto *RD =
3003 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003004 IsFirstprivate = RD->isLambda();
3005 IsFirstprivate =
cchene06f3e02019-11-15 13:02:06 -05003006 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3007 if (IsFirstprivate) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003008 ImplicitFirstprivate.emplace_back(E);
cchene06f3e02019-11-15 13:02:06 -05003009 } else {
3010 OpenMPDefaultmapClauseModifier M =
3011 Stack->getDefaultmapModifier(ClauseKind);
3012 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3013 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3014 ImplicitMap[Kind].emplace_back(E);
3015 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003016 return;
3017 }
3018 }
3019
Alexey Bataev758e55e2013-09-06 18:03:48 +00003020 // OpenMP [2.9.3.6, Restrictions, p.2]
3021 // A list item that appears in a reduction clause of the innermost
3022 // enclosing worksharing or parallel construct may not be accessed in an
3023 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003024 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003025 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3026 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003027 return isOpenMPParallelDirective(K) ||
3028 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3029 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00003030 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003031 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00003032 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00003033 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003034 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00003035 return;
3036 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003037
3038 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003039 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003040 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00003041 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003042 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00003043 return;
3044 }
3045
3046 // Store implicitly used globals with declare target link for parent
3047 // target.
3048 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3049 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3050 Stack->addToParentTargetRegionLinkGlobals(E);
3051 return;
3052 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003053 }
3054 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003055 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00003056 if (E->isTypeDependent() || E->isValueDependent() ||
3057 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3058 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003059 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003060 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00003061 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003062 if (!FD)
3063 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003064 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003065 // Check if the variable has explicit DSA set and stop analysis if it
3066 // so.
3067 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3068 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003069
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003070 if (isOpenMPTargetExecutionDirective(DKind) &&
3071 !Stack->isLoopControlVariable(FD).first &&
3072 !Stack->checkMappableExprComponentListsForDecl(
3073 FD, /*CurrentRegionOnly=*/true,
3074 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3075 StackComponents,
3076 OpenMPClauseKind) {
3077 return isa<CXXThisExpr>(
3078 cast<MemberExpr>(
3079 StackComponents.back().getAssociatedExpression())
3080 ->getBase()
3081 ->IgnoreParens());
3082 })) {
3083 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3084 // A bit-field cannot appear in a map clause.
3085 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003086 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003087 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00003088
3089 // Check to see if the member expression is referencing a class that
3090 // has already been explicitly mapped
3091 if (Stack->isClassPreviouslyMapped(TE->getType()))
3092 return;
3093
cchene06f3e02019-11-15 13:02:06 -05003094 OpenMPDefaultmapClauseModifier Modifier =
3095 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3096 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3097 Modifier, /*IsAggregateOrDeclareTarget*/ true);
3098 ImplicitMap[Kind].emplace_back(E);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003099 return;
3100 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003101
Alexey Bataeve3727102018-04-18 15:57:46 +00003102 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003103 // OpenMP [2.9.3.6, Restrictions, p.2]
3104 // A list item that appears in a reduction clause of the innermost
3105 // enclosing worksharing or parallel construct may not be accessed in
3106 // an explicit task.
3107 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003108 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3109 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003110 return isOpenMPParallelDirective(K) ||
3111 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3112 },
3113 /*FromParent=*/true);
3114 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3115 ErrorFound = true;
3116 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003117 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003118 return;
3119 }
3120
3121 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003122 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003123 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00003124 !Stack->isLoopControlVariable(FD).first) {
3125 // Check if there is a captured expression for the current field in the
3126 // region. Do not mark it as firstprivate unless there is no captured
3127 // expression.
3128 // TODO: try to make it firstprivate.
3129 if (DVar.CKind != OMPC_unknown)
3130 ImplicitFirstprivate.push_back(E);
3131 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003132 return;
3133 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003134 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003135 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00003136 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003137 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003138 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003139 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003140 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3141 if (!Stack->checkMappableExprComponentListsForDecl(
3142 VD, /*CurrentRegionOnly=*/true,
3143 [&CurComponents](
3144 OMPClauseMappableExprCommon::MappableExprComponentListRef
3145 StackComponents,
3146 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003147 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003148 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003149 for (const auto &SC : llvm::reverse(StackComponents)) {
3150 // Do both expressions have the same kind?
3151 if (CCI->getAssociatedExpression()->getStmtClass() !=
3152 SC.getAssociatedExpression()->getStmtClass())
3153 if (!(isa<OMPArraySectionExpr>(
3154 SC.getAssociatedExpression()) &&
3155 isa<ArraySubscriptExpr>(
3156 CCI->getAssociatedExpression())))
3157 return false;
3158
Alexey Bataeve3727102018-04-18 15:57:46 +00003159 const Decl *CCD = CCI->getAssociatedDeclaration();
3160 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003161 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3162 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3163 if (SCD != CCD)
3164 return false;
3165 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003166 if (CCI == CCE)
3167 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003168 }
3169 return true;
3170 })) {
3171 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003172 }
Alexey Bataevc09c0652019-10-29 10:06:11 -04003173 } else if (!TryCaptureCXXThisMembers) {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003174 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003175 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003176 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003177 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003178 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003179 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003180 // for task|target directives.
3181 // Skip analysis of arguments of implicitly defined map clause for target
3182 // directives.
3183 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3184 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003185 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003186 if (CC)
3187 Visit(CC);
3188 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003189 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003190 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003191 // Check implicitly captured variables.
3192 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003193 }
3194 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003195 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003196 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003197 // Check implicitly captured variables in the task-based directives to
3198 // check if they must be firstprivatized.
3199 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003200 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003201 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003202 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003203
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003204 void visitSubCaptures(CapturedStmt *S) {
3205 for (const CapturedStmt::Capture &Cap : S->captures()) {
3206 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3207 continue;
3208 VarDecl *VD = Cap.getCapturedVar();
3209 // Do not try to map the variable if it or its sub-component was mapped
3210 // already.
3211 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3212 Stack->checkMappableExprComponentListsForDecl(
3213 VD, /*CurrentRegionOnly=*/true,
3214 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3215 OpenMPClauseKind) { return true; }))
3216 continue;
3217 DeclRefExpr *DRE = buildDeclRefExpr(
3218 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3219 Cap.getLocation(), /*RefersToCapture=*/true);
3220 Visit(DRE);
3221 }
3222 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003223 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003224 ArrayRef<Expr *> getImplicitFirstprivate() const {
3225 return ImplicitFirstprivate;
3226 }
cchene06f3e02019-11-15 13:02:06 -05003227 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3228 return ImplicitMap[Kind];
3229 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003230 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003231 return VarsWithInheritedDSA;
3232 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003233
Alexey Bataev7ff55242014-06-19 09:13:45 +00003234 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003235 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3236 // Process declare target link variables for the target directives.
3237 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3238 for (DeclRefExpr *E : Stack->getLinkGlobals())
3239 Visit(E);
3240 }
3241 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003242};
Alexey Bataeved09d242014-05-28 05:53:51 +00003243} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003244
Alexey Bataevbae9a792014-06-27 10:37:06 +00003245void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003246 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003247 case OMPD_parallel:
3248 case OMPD_parallel_for:
3249 case OMPD_parallel_for_simd:
3250 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003251 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003252 case OMPD_teams_distribute:
3253 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003254 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003255 QualType KmpInt32PtrTy =
3256 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003257 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003258 std::make_pair(".global_tid.", KmpInt32PtrTy),
3259 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3260 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003261 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003262 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3263 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003264 break;
3265 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003266 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003267 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003268 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003269 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003270 case OMPD_target_teams_distribute:
3271 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003272 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3273 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3274 QualType KmpInt32PtrTy =
3275 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3276 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003277 FunctionProtoType::ExtProtoInfo EPI;
3278 EPI.Variadic = true;
3279 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3280 Sema::CapturedParamNameType Params[] = {
3281 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003282 std::make_pair(".part_id.", KmpInt32PtrTy),
3283 std::make_pair(".privates.", VoidPtrTy),
3284 std::make_pair(
3285 ".copy_fn.",
3286 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003287 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3288 std::make_pair(StringRef(), QualType()) // __context with shared vars
3289 };
3290 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003291 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003292 // Mark this captured region as inlined, because we don't use outlined
3293 // function directly.
3294 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3295 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003296 Context, {}, AttributeCommonInfo::AS_Keyword,
3297 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003298 Sema::CapturedParamNameType ParamsTarget[] = {
3299 std::make_pair(StringRef(), QualType()) // __context with shared vars
3300 };
3301 // Start a captured region for 'target' with no implicit parameters.
3302 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003303 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003304 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003305 std::make_pair(".global_tid.", KmpInt32PtrTy),
3306 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3307 std::make_pair(StringRef(), QualType()) // __context with shared vars
3308 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003309 // Start a captured region for 'teams' or 'parallel'. Both regions have
3310 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003311 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003312 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003313 break;
3314 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003315 case OMPD_target:
3316 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003317 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3318 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3319 QualType KmpInt32PtrTy =
3320 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3321 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003322 FunctionProtoType::ExtProtoInfo EPI;
3323 EPI.Variadic = true;
3324 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3325 Sema::CapturedParamNameType Params[] = {
3326 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003327 std::make_pair(".part_id.", KmpInt32PtrTy),
3328 std::make_pair(".privates.", VoidPtrTy),
3329 std::make_pair(
3330 ".copy_fn.",
3331 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003332 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3333 std::make_pair(StringRef(), QualType()) // __context with shared vars
3334 };
3335 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003336 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003337 // Mark this captured region as inlined, because we don't use outlined
3338 // function directly.
3339 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3340 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003341 Context, {}, AttributeCommonInfo::AS_Keyword,
3342 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003343 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003344 std::make_pair(StringRef(), QualType()),
3345 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003346 break;
3347 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003348 case OMPD_simd:
3349 case OMPD_for:
3350 case OMPD_for_simd:
3351 case OMPD_sections:
3352 case OMPD_section:
3353 case OMPD_single:
3354 case OMPD_master:
3355 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003356 case OMPD_taskgroup:
3357 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003358 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003359 case OMPD_ordered:
3360 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003361 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003362 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003363 std::make_pair(StringRef(), QualType()) // __context with shared vars
3364 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003365 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3366 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003367 break;
3368 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003369 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003370 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3371 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3372 QualType KmpInt32PtrTy =
3373 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3374 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003375 FunctionProtoType::ExtProtoInfo EPI;
3376 EPI.Variadic = true;
3377 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003378 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003379 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003380 std::make_pair(".part_id.", KmpInt32PtrTy),
3381 std::make_pair(".privates.", VoidPtrTy),
3382 std::make_pair(
3383 ".copy_fn.",
3384 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003385 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003386 std::make_pair(StringRef(), QualType()) // __context with shared vars
3387 };
3388 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3389 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003390 // Mark this captured region as inlined, because we don't use outlined
3391 // function directly.
3392 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3393 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003394 Context, {}, AttributeCommonInfo::AS_Keyword,
3395 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003396 break;
3397 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003398 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003399 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003400 case OMPD_master_taskloop:
3401 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003402 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003403 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3404 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003405 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003406 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3407 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003408 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003409 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3410 .withConst();
3411 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3412 QualType KmpInt32PtrTy =
3413 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3414 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003415 FunctionProtoType::ExtProtoInfo EPI;
3416 EPI.Variadic = true;
3417 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003418 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003419 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003420 std::make_pair(".part_id.", KmpInt32PtrTy),
3421 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003422 std::make_pair(
3423 ".copy_fn.",
3424 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3425 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3426 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003427 std::make_pair(".ub.", KmpUInt64Ty),
3428 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003429 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003430 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003431 std::make_pair(StringRef(), QualType()) // __context with shared vars
3432 };
3433 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3434 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003435 // Mark this captured region as inlined, because we don't use outlined
3436 // function directly.
3437 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3438 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003439 Context, {}, AttributeCommonInfo::AS_Keyword,
3440 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003441 break;
3442 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04003443 case OMPD_parallel_master_taskloop:
3444 case OMPD_parallel_master_taskloop_simd: {
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003445 QualType KmpInt32Ty =
3446 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3447 .withConst();
3448 QualType KmpUInt64Ty =
3449 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3450 .withConst();
3451 QualType KmpInt64Ty =
3452 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3453 .withConst();
3454 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3455 QualType KmpInt32PtrTy =
3456 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3457 Sema::CapturedParamNameType ParamsParallel[] = {
3458 std::make_pair(".global_tid.", KmpInt32PtrTy),
3459 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3460 std::make_pair(StringRef(), QualType()) // __context with shared vars
3461 };
3462 // Start a captured region for 'parallel'.
3463 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3464 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3465 QualType Args[] = {VoidPtrTy};
3466 FunctionProtoType::ExtProtoInfo EPI;
3467 EPI.Variadic = true;
3468 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3469 Sema::CapturedParamNameType Params[] = {
3470 std::make_pair(".global_tid.", KmpInt32Ty),
3471 std::make_pair(".part_id.", KmpInt32PtrTy),
3472 std::make_pair(".privates.", VoidPtrTy),
3473 std::make_pair(
3474 ".copy_fn.",
3475 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3476 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3477 std::make_pair(".lb.", KmpUInt64Ty),
3478 std::make_pair(".ub.", KmpUInt64Ty),
3479 std::make_pair(".st.", KmpInt64Ty),
3480 std::make_pair(".liter.", KmpInt32Ty),
3481 std::make_pair(".reductions.", VoidPtrTy),
3482 std::make_pair(StringRef(), QualType()) // __context with shared vars
3483 };
3484 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3485 Params, /*OpenMPCaptureLevel=*/2);
3486 // Mark this captured region as inlined, because we don't use outlined
3487 // function directly.
3488 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3489 AlwaysInlineAttr::CreateImplicit(
3490 Context, {}, AttributeCommonInfo::AS_Keyword,
3491 AlwaysInlineAttr::Keyword_forceinline));
3492 break;
3493 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003494 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003495 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003496 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003497 QualType KmpInt32PtrTy =
3498 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3499 Sema::CapturedParamNameType Params[] = {
3500 std::make_pair(".global_tid.", KmpInt32PtrTy),
3501 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003502 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3503 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003504 std::make_pair(StringRef(), QualType()) // __context with shared vars
3505 };
3506 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3507 Params);
3508 break;
3509 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003510 case OMPD_target_teams_distribute_parallel_for:
3511 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003512 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003513 QualType KmpInt32PtrTy =
3514 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003515 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003516
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003517 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003518 FunctionProtoType::ExtProtoInfo EPI;
3519 EPI.Variadic = true;
3520 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3521 Sema::CapturedParamNameType Params[] = {
3522 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003523 std::make_pair(".part_id.", KmpInt32PtrTy),
3524 std::make_pair(".privates.", VoidPtrTy),
3525 std::make_pair(
3526 ".copy_fn.",
3527 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003528 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3529 std::make_pair(StringRef(), QualType()) // __context with shared vars
3530 };
3531 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003532 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003533 // Mark this captured region as inlined, because we don't use outlined
3534 // function directly.
3535 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3536 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003537 Context, {}, AttributeCommonInfo::AS_Keyword,
3538 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003539 Sema::CapturedParamNameType ParamsTarget[] = {
3540 std::make_pair(StringRef(), QualType()) // __context with shared vars
3541 };
3542 // Start a captured region for 'target' with no implicit parameters.
3543 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003544 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003545
3546 Sema::CapturedParamNameType ParamsTeams[] = {
3547 std::make_pair(".global_tid.", KmpInt32PtrTy),
3548 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3549 std::make_pair(StringRef(), QualType()) // __context with shared vars
3550 };
3551 // Start a captured region for 'target' with no implicit parameters.
3552 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003553 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003554
3555 Sema::CapturedParamNameType ParamsParallel[] = {
3556 std::make_pair(".global_tid.", KmpInt32PtrTy),
3557 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003558 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3559 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003560 std::make_pair(StringRef(), QualType()) // __context with shared vars
3561 };
3562 // Start a captured region for 'teams' or 'parallel'. Both regions have
3563 // the same implicit parameters.
3564 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003565 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003566 break;
3567 }
3568
Alexey Bataev46506272017-12-05 17:41:34 +00003569 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003570 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003571 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003572 QualType KmpInt32PtrTy =
3573 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3574
3575 Sema::CapturedParamNameType ParamsTeams[] = {
3576 std::make_pair(".global_tid.", KmpInt32PtrTy),
3577 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3578 std::make_pair(StringRef(), QualType()) // __context with shared vars
3579 };
3580 // Start a captured region for 'target' with no implicit parameters.
3581 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003582 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003583
3584 Sema::CapturedParamNameType ParamsParallel[] = {
3585 std::make_pair(".global_tid.", KmpInt32PtrTy),
3586 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003587 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3588 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003589 std::make_pair(StringRef(), QualType()) // __context with shared vars
3590 };
3591 // Start a captured region for 'teams' or 'parallel'. Both regions have
3592 // the same implicit parameters.
3593 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003594 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003595 break;
3596 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003597 case OMPD_target_update:
3598 case OMPD_target_enter_data:
3599 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003600 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3601 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3602 QualType KmpInt32PtrTy =
3603 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3604 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003605 FunctionProtoType::ExtProtoInfo EPI;
3606 EPI.Variadic = true;
3607 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3608 Sema::CapturedParamNameType Params[] = {
3609 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003610 std::make_pair(".part_id.", KmpInt32PtrTy),
3611 std::make_pair(".privates.", VoidPtrTy),
3612 std::make_pair(
3613 ".copy_fn.",
3614 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003615 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3616 std::make_pair(StringRef(), QualType()) // __context with shared vars
3617 };
3618 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3619 Params);
3620 // Mark this captured region as inlined, because we don't use outlined
3621 // function directly.
3622 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3623 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003624 Context, {}, AttributeCommonInfo::AS_Keyword,
3625 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003626 break;
3627 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003628 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003629 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003630 case OMPD_taskyield:
3631 case OMPD_barrier:
3632 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003633 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003634 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003635 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003636 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003637 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003638 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003639 case OMPD_declare_target:
3640 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003641 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003642 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003643 llvm_unreachable("OpenMP Directive is not allowed");
3644 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003645 llvm_unreachable("Unknown OpenMP directive");
3646 }
3647}
3648
Alexey Bataev0e100032019-10-14 16:44:01 +00003649int Sema::getNumberOfConstructScopes(unsigned Level) const {
3650 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3651}
3652
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003653int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3654 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3655 getOpenMPCaptureRegions(CaptureRegions, DKind);
3656 return CaptureRegions.size();
3657}
3658
Alexey Bataev3392d762016-02-16 11:18:12 +00003659static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003660 Expr *CaptureExpr, bool WithInit,
3661 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003662 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003663 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003664 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003665 QualType Ty = Init->getType();
3666 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003667 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003668 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003669 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003670 Ty = C.getPointerType(Ty);
3671 ExprResult Res =
3672 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3673 if (!Res.isUsable())
3674 return nullptr;
3675 Init = Res.get();
3676 }
Alexey Bataev61205072016-03-02 04:57:40 +00003677 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003678 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003679 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003680 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003681 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003682 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003683 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003684 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003685 return CED;
3686}
3687
Alexey Bataev61205072016-03-02 04:57:40 +00003688static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3689 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003690 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003691 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003692 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003693 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003694 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3695 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003696 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003697 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003698}
3699
Alexey Bataev5a3af132016-03-29 08:58:54 +00003700static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003701 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003702 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003703 OMPCapturedExprDecl *CD = buildCaptureDecl(
3704 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3705 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003706 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3707 CaptureExpr->getExprLoc());
3708 }
3709 ExprResult Res = Ref;
3710 if (!S.getLangOpts().CPlusPlus &&
3711 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003712 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003713 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003714 if (!Res.isUsable())
3715 return ExprError();
3716 }
3717 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003718}
3719
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003720namespace {
3721// OpenMP directives parsed in this section are represented as a
3722// CapturedStatement with an associated statement. If a syntax error
3723// is detected during the parsing of the associated statement, the
3724// compiler must abort processing and close the CapturedStatement.
3725//
3726// Combined directives such as 'target parallel' have more than one
3727// nested CapturedStatements. This RAII ensures that we unwind out
3728// of all the nested CapturedStatements when an error is found.
3729class CaptureRegionUnwinderRAII {
3730private:
3731 Sema &S;
3732 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003733 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003734
3735public:
3736 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3737 OpenMPDirectiveKind DKind)
3738 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3739 ~CaptureRegionUnwinderRAII() {
3740 if (ErrorFound) {
3741 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3742 while (--ThisCaptureLevel >= 0)
3743 S.ActOnCapturedRegionError();
3744 }
3745 }
3746};
3747} // namespace
3748
Alexey Bataevb600ae32019-07-01 17:46:52 +00003749void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3750 // Capture variables captured by reference in lambdas for target-based
3751 // directives.
3752 if (!CurContext->isDependentContext() &&
3753 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3754 isOpenMPTargetDataManagementDirective(
3755 DSAStack->getCurrentDirective()))) {
3756 QualType Type = V->getType();
3757 if (const auto *RD = Type.getCanonicalType()
3758 .getNonReferenceType()
3759 ->getAsCXXRecordDecl()) {
3760 bool SavedForceCaptureByReferenceInTargetExecutable =
3761 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3762 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3763 /*V=*/true);
3764 if (RD->isLambda()) {
3765 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3766 FieldDecl *ThisCapture;
3767 RD->getCaptureFields(Captures, ThisCapture);
3768 for (const LambdaCapture &LC : RD->captures()) {
3769 if (LC.getCaptureKind() == LCK_ByRef) {
3770 VarDecl *VD = LC.getCapturedVar();
3771 DeclContext *VDC = VD->getDeclContext();
3772 if (!VDC->Encloses(CurContext))
3773 continue;
3774 MarkVariableReferenced(LC.getLocation(), VD);
3775 } else if (LC.getCaptureKind() == LCK_This) {
3776 QualType ThisTy = getCurrentThisType();
3777 if (!ThisTy.isNull() &&
3778 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3779 CheckCXXThisCapture(LC.getLocation());
3780 }
3781 }
3782 }
3783 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3784 SavedForceCaptureByReferenceInTargetExecutable);
3785 }
3786 }
3787}
3788
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003789StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3790 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003791 bool ErrorFound = false;
3792 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3793 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003794 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003795 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003796 return StmtError();
3797 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003798
Alexey Bataev2ba67042017-11-28 21:11:44 +00003799 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3800 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003801 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003802 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003803 SmallVector<const OMPLinearClause *, 4> LCs;
3804 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003805 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003806 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003807 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3808 Clause->getClauseKind() == OMPC_in_reduction) {
3809 // Capture taskgroup task_reduction descriptors inside the tasking regions
3810 // with the corresponding in_reduction items.
3811 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003812 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003813 if (E)
3814 MarkDeclarationsReferencedInExpr(E);
3815 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003816 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003817 Clause->getClauseKind() == OMPC_copyprivate ||
3818 (getLangOpts().OpenMPUseTLS &&
3819 getASTContext().getTargetInfo().isTLSSupported() &&
3820 Clause->getClauseKind() == OMPC_copyin)) {
3821 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003822 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003823 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003824 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003825 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003826 }
3827 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003828 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003829 } else if (CaptureRegions.size() > 1 ||
3830 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003831 if (auto *C = OMPClauseWithPreInit::get(Clause))
3832 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003833 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003834 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003835 MarkDeclarationsReferencedInExpr(E);
3836 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003837 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003838 if (Clause->getClauseKind() == OMPC_schedule)
3839 SC = cast<OMPScheduleClause>(Clause);
3840 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003841 OC = cast<OMPOrderedClause>(Clause);
3842 else if (Clause->getClauseKind() == OMPC_linear)
3843 LCs.push_back(cast<OMPLinearClause>(Clause));
3844 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003845 // OpenMP, 2.7.1 Loop Construct, Restrictions
3846 // The nonmonotonic modifier cannot be specified if an ordered clause is
3847 // specified.
3848 if (SC &&
3849 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3850 SC->getSecondScheduleModifier() ==
3851 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3852 OC) {
3853 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3854 ? SC->getFirstScheduleModifierLoc()
3855 : SC->getSecondScheduleModifierLoc(),
3856 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003857 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003858 ErrorFound = true;
3859 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003860 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003861 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003862 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003863 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003864 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003865 ErrorFound = true;
3866 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003867 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3868 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3869 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003870 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003871 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3872 ErrorFound = true;
3873 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003874 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003875 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003876 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003877 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003878 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003879 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003880 // Mark all variables in private list clauses as used in inner region.
3881 // Required for proper codegen of combined directives.
3882 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003883 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003884 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003885 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3886 // Find the particular capture region for the clause if the
3887 // directive is a combined one with multiple capture regions.
3888 // If the directive is not a combined one, the capture region
3889 // associated with the clause is OMPD_unknown and is generated
3890 // only once.
3891 if (CaptureRegion == ThisCaptureRegion ||
3892 CaptureRegion == OMPD_unknown) {
3893 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003894 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003895 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3896 }
3897 }
3898 }
3899 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003900 if (++CompletedRegions == CaptureRegions.size())
3901 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003902 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003903 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003904 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003905}
3906
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003907static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3908 OpenMPDirectiveKind CancelRegion,
3909 SourceLocation StartLoc) {
3910 // CancelRegion is only needed for cancel and cancellation_point.
3911 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3912 return false;
3913
3914 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3915 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3916 return false;
3917
3918 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3919 << getOpenMPDirectiveName(CancelRegion);
3920 return true;
3921}
3922
Alexey Bataeve3727102018-04-18 15:57:46 +00003923static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003924 OpenMPDirectiveKind CurrentRegion,
3925 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003926 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003927 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003928 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003929 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3930 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003931 bool NestingProhibited = false;
3932 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003933 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003934 enum {
3935 NoRecommend,
3936 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003937 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003938 ShouldBeInTargetRegion,
3939 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003940 } Recommend = NoRecommend;
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003941 if (isOpenMPSimdDirective(ParentRegion) &&
3942 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
3943 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
3944 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003945 // OpenMP [2.16, Nesting of Regions]
3946 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003947 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003948 // An ordered construct with the simd clause is the only OpenMP
3949 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003950 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003951 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3952 // message.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003953 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
3954 // The only OpenMP constructs that can be encountered during execution of
3955 // a simd region are the atomic construct, the loop construct, the simd
3956 // construct and the ordered construct with the simd clause.
Kelvin Lifd8b5742016-07-01 14:30:25 +00003957 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3958 ? diag::err_omp_prohibited_region_simd
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003959 : diag::warn_omp_nesting_simd)
3960 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
Kelvin Lifd8b5742016-07-01 14:30:25 +00003961 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003962 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003963 if (ParentRegion == OMPD_atomic) {
3964 // OpenMP [2.16, Nesting of Regions]
3965 // OpenMP constructs may not be nested inside an atomic region.
3966 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3967 return true;
3968 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003969 if (CurrentRegion == OMPD_section) {
3970 // OpenMP [2.7.2, sections Construct, Restrictions]
3971 // Orphaned section directives are prohibited. That is, the section
3972 // directives must appear within the sections construct and must not be
3973 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003974 if (ParentRegion != OMPD_sections &&
3975 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003976 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3977 << (ParentRegion != OMPD_unknown)
3978 << getOpenMPDirectiveName(ParentRegion);
3979 return true;
3980 }
3981 return false;
3982 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003983 // Allow some constructs (except teams and cancellation constructs) to be
3984 // orphaned (they could be used in functions, called from OpenMP regions
3985 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003986 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003987 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3988 CurrentRegion != OMPD_cancellation_point &&
3989 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003990 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003991 if (CurrentRegion == OMPD_cancellation_point ||
3992 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003993 // OpenMP [2.16, Nesting of Regions]
3994 // A cancellation point construct for which construct-type-clause is
3995 // taskgroup must be nested inside a task construct. A cancellation
3996 // point construct for which construct-type-clause is not taskgroup must
3997 // be closely nested inside an OpenMP construct that matches the type
3998 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003999 // A cancel construct for which construct-type-clause is taskgroup must be
4000 // nested inside a task construct. A cancel construct for which
4001 // construct-type-clause is not taskgroup must be closely nested inside an
4002 // OpenMP construct that matches the type specified in
4003 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004004 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004005 !((CancelRegion == OMPD_parallel &&
4006 (ParentRegion == OMPD_parallel ||
4007 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00004008 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004009 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004010 ParentRegion == OMPD_target_parallel_for ||
4011 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004012 ParentRegion == OMPD_teams_distribute_parallel_for ||
4013 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004014 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
4015 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00004016 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4017 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00004018 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004019 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00004020 // OpenMP [2.16, Nesting of Regions]
4021 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004022 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00004023 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004024 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004025 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4026 // OpenMP [2.16, Nesting of Regions]
4027 // A critical region may not be nested (closely or otherwise) inside a
4028 // critical region with the same name. Note that this restriction is not
4029 // sufficient to prevent deadlock.
4030 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00004031 bool DeadLock = Stack->hasDirective(
4032 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4033 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00004034 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00004035 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4036 PreviousCriticalLoc = Loc;
4037 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004038 }
4039 return false;
David Majnemer9d168222016-08-05 17:44:54 +00004040 },
4041 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004042 if (DeadLock) {
4043 SemaRef.Diag(StartLoc,
4044 diag::err_omp_prohibited_region_critical_same_name)
4045 << CurrentName.getName();
4046 if (PreviousCriticalLoc.isValid())
4047 SemaRef.Diag(PreviousCriticalLoc,
4048 diag::note_omp_previous_critical_region);
4049 return true;
4050 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004051 } else if (CurrentRegion == OMPD_barrier) {
4052 // OpenMP [2.16, Nesting of Regions]
4053 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004054 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004055 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4056 isOpenMPTaskingDirective(ParentRegion) ||
4057 ParentRegion == OMPD_master ||
4058 ParentRegion == OMPD_critical ||
4059 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00004060 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00004061 !isOpenMPParallelDirective(CurrentRegion) &&
4062 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004063 // OpenMP [2.16, Nesting of Regions]
4064 // A worksharing region may not be closely nested inside a worksharing,
4065 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004066 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4067 isOpenMPTaskingDirective(ParentRegion) ||
4068 ParentRegion == OMPD_master ||
4069 ParentRegion == OMPD_critical ||
4070 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004071 Recommend = ShouldBeInParallelRegion;
4072 } else if (CurrentRegion == OMPD_ordered) {
4073 // OpenMP [2.16, Nesting of Regions]
4074 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00004075 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004076 // An ordered region must be closely nested inside a loop region (or
4077 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004078 // OpenMP [2.8.1,simd Construct, Restrictions]
4079 // An ordered construct with the simd clause is the only OpenMP construct
4080 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004081 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004082 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004083 !(isOpenMPSimdDirective(ParentRegion) ||
4084 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004085 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00004086 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004087 // OpenMP [2.16, Nesting of Regions]
4088 // If specified, a teams construct must be contained within a target
4089 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00004090 NestingProhibited =
4091 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4092 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4093 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00004094 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004095 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004096 }
Kelvin Libf594a52016-12-17 05:48:59 +00004097 if (!NestingProhibited &&
4098 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4099 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4100 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004101 // OpenMP [2.16, Nesting of Regions]
4102 // distribute, parallel, parallel sections, parallel workshare, and the
4103 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4104 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004105 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4106 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00004107 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004108 }
David Majnemer9d168222016-08-05 17:44:54 +00004109 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00004110 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004111 // OpenMP 4.5 [2.17 Nesting of Regions]
4112 // The region associated with the distribute construct must be strictly
4113 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00004114 NestingProhibited =
4115 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004116 Recommend = ShouldBeInTeamsRegion;
4117 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004118 if (!NestingProhibited &&
4119 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4120 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4121 // OpenMP 4.5 [2.17 Nesting of Regions]
4122 // If a target, target update, target data, target enter data, or
4123 // target exit data construct is encountered during execution of a
4124 // target region, the behavior is unspecified.
4125 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004126 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00004127 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004128 if (isOpenMPTargetExecutionDirective(K)) {
4129 OffendingRegion = K;
4130 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004131 }
4132 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004133 },
4134 false /* don't skip top directive */);
4135 CloseNesting = false;
4136 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004137 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00004138 if (OrphanSeen) {
4139 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4140 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4141 } else {
4142 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4143 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4144 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4145 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004146 return true;
4147 }
4148 }
4149 return false;
4150}
4151
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004152static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4153 ArrayRef<OMPClause *> Clauses,
4154 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4155 bool ErrorFound = false;
4156 unsigned NamedModifiersNumber = 0;
4157 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
4158 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004159 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004160 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004161 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4162 // At most one if clause without a directive-name-modifier can appear on
4163 // the directive.
4164 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4165 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004166 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004167 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4168 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4169 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004170 } else if (CurNM != OMPD_unknown) {
4171 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004172 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004173 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004174 FoundNameModifiers[CurNM] = IC;
4175 if (CurNM == OMPD_unknown)
4176 continue;
4177 // Check if the specified name modifier is allowed for the current
4178 // directive.
4179 // At most one if clause with the particular directive-name-modifier can
4180 // appear on the directive.
4181 bool MatchFound = false;
4182 for (auto NM : AllowedNameModifiers) {
4183 if (CurNM == NM) {
4184 MatchFound = true;
4185 break;
4186 }
4187 }
4188 if (!MatchFound) {
4189 S.Diag(IC->getNameModifierLoc(),
4190 diag::err_omp_wrong_if_directive_name_modifier)
4191 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4192 ErrorFound = true;
4193 }
4194 }
4195 }
4196 // If any if clause on the directive includes a directive-name-modifier then
4197 // all if clauses on the directive must include a directive-name-modifier.
4198 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4199 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004200 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004201 diag::err_omp_no_more_if_clause);
4202 } else {
4203 std::string Values;
4204 std::string Sep(", ");
4205 unsigned AllowedCnt = 0;
4206 unsigned TotalAllowedNum =
4207 AllowedNameModifiers.size() - NamedModifiersNumber;
4208 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4209 ++Cnt) {
4210 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4211 if (!FoundNameModifiers[NM]) {
4212 Values += "'";
4213 Values += getOpenMPDirectiveName(NM);
4214 Values += "'";
4215 if (AllowedCnt + 2 == TotalAllowedNum)
4216 Values += " or ";
4217 else if (AllowedCnt + 1 != TotalAllowedNum)
4218 Values += Sep;
4219 ++AllowedCnt;
4220 }
4221 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004222 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004223 diag::err_omp_unnamed_if_clause)
4224 << (TotalAllowedNum > 1) << Values;
4225 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004226 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004227 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4228 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004229 ErrorFound = true;
4230 }
4231 return ErrorFound;
4232}
4233
Alexey Bataeve106f252019-04-01 14:25:31 +00004234static std::pair<ValueDecl *, bool>
4235getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4236 SourceRange &ERange, bool AllowArraySection = false) {
4237 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4238 RefExpr->containsUnexpandedParameterPack())
4239 return std::make_pair(nullptr, true);
4240
4241 // OpenMP [3.1, C/C++]
4242 // A list item is a variable name.
4243 // OpenMP [2.9.3.3, Restrictions, p.1]
4244 // A variable that is part of another variable (as an array or
4245 // structure element) cannot appear in a private clause.
4246 RefExpr = RefExpr->IgnoreParens();
4247 enum {
4248 NoArrayExpr = -1,
4249 ArraySubscript = 0,
4250 OMPArraySection = 1
4251 } IsArrayExpr = NoArrayExpr;
4252 if (AllowArraySection) {
4253 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4254 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4255 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4256 Base = TempASE->getBase()->IgnoreParenImpCasts();
4257 RefExpr = Base;
4258 IsArrayExpr = ArraySubscript;
4259 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4260 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4261 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4262 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4263 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4264 Base = TempASE->getBase()->IgnoreParenImpCasts();
4265 RefExpr = Base;
4266 IsArrayExpr = OMPArraySection;
4267 }
4268 }
4269 ELoc = RefExpr->getExprLoc();
4270 ERange = RefExpr->getSourceRange();
4271 RefExpr = RefExpr->IgnoreParenImpCasts();
4272 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4273 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4274 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4275 (S.getCurrentThisType().isNull() || !ME ||
4276 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4277 !isa<FieldDecl>(ME->getMemberDecl()))) {
4278 if (IsArrayExpr != NoArrayExpr) {
4279 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4280 << ERange;
4281 } else {
4282 S.Diag(ELoc,
4283 AllowArraySection
4284 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4285 : diag::err_omp_expected_var_name_member_expr)
4286 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4287 }
4288 return std::make_pair(nullptr, false);
4289 }
4290 return std::make_pair(
4291 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4292}
4293
4294static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004295 ArrayRef<OMPClause *> Clauses) {
4296 assert(!S.CurContext->isDependentContext() &&
4297 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004298 auto AllocateRange =
4299 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004300 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4301 DeclToCopy;
4302 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4303 return isOpenMPPrivate(C->getClauseKind());
4304 });
4305 for (OMPClause *Cl : PrivateRange) {
4306 MutableArrayRef<Expr *>::iterator I, It, Et;
4307 if (Cl->getClauseKind() == OMPC_private) {
4308 auto *PC = cast<OMPPrivateClause>(Cl);
4309 I = PC->private_copies().begin();
4310 It = PC->varlist_begin();
4311 Et = PC->varlist_end();
4312 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4313 auto *PC = cast<OMPFirstprivateClause>(Cl);
4314 I = PC->private_copies().begin();
4315 It = PC->varlist_begin();
4316 Et = PC->varlist_end();
4317 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4318 auto *PC = cast<OMPLastprivateClause>(Cl);
4319 I = PC->private_copies().begin();
4320 It = PC->varlist_begin();
4321 Et = PC->varlist_end();
4322 } else if (Cl->getClauseKind() == OMPC_linear) {
4323 auto *PC = cast<OMPLinearClause>(Cl);
4324 I = PC->privates().begin();
4325 It = PC->varlist_begin();
4326 Et = PC->varlist_end();
4327 } else if (Cl->getClauseKind() == OMPC_reduction) {
4328 auto *PC = cast<OMPReductionClause>(Cl);
4329 I = PC->privates().begin();
4330 It = PC->varlist_begin();
4331 Et = PC->varlist_end();
4332 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4333 auto *PC = cast<OMPTaskReductionClause>(Cl);
4334 I = PC->privates().begin();
4335 It = PC->varlist_begin();
4336 Et = PC->varlist_end();
4337 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4338 auto *PC = cast<OMPInReductionClause>(Cl);
4339 I = PC->privates().begin();
4340 It = PC->varlist_begin();
4341 Et = PC->varlist_end();
4342 } else {
4343 llvm_unreachable("Expected private clause.");
4344 }
4345 for (Expr *E : llvm::make_range(It, Et)) {
4346 if (!*I) {
4347 ++I;
4348 continue;
4349 }
4350 SourceLocation ELoc;
4351 SourceRange ERange;
4352 Expr *SimpleRefExpr = E;
4353 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4354 /*AllowArraySection=*/true);
4355 DeclToCopy.try_emplace(Res.first,
4356 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4357 ++I;
4358 }
4359 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004360 for (OMPClause *C : AllocateRange) {
4361 auto *AC = cast<OMPAllocateClause>(C);
4362 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4363 getAllocatorKind(S, Stack, AC->getAllocator());
4364 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4365 // For task, taskloop or target directives, allocation requests to memory
4366 // allocators with the trait access set to thread result in unspecified
4367 // behavior.
4368 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4369 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4370 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4371 S.Diag(AC->getAllocator()->getExprLoc(),
4372 diag::warn_omp_allocate_thread_on_task_target_directive)
4373 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004374 }
4375 for (Expr *E : AC->varlists()) {
4376 SourceLocation ELoc;
4377 SourceRange ERange;
4378 Expr *SimpleRefExpr = E;
4379 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4380 ValueDecl *VD = Res.first;
4381 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4382 if (!isOpenMPPrivate(Data.CKind)) {
4383 S.Diag(E->getExprLoc(),
4384 diag::err_omp_expected_private_copy_for_allocate);
4385 continue;
4386 }
4387 VarDecl *PrivateVD = DeclToCopy[VD];
4388 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4389 AllocatorKind, AC->getAllocator()))
4390 continue;
4391 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4392 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004393 }
4394 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004395}
4396
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004397StmtResult Sema::ActOnOpenMPExecutableDirective(
4398 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4399 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4400 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004401 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004402 // First check CancelRegion which is then used in checkNestingOfRegions.
4403 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4404 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004405 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004406 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004407
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004408 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004409 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004410 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004411 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004412 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004413 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4414
4415 // Check default data sharing attributes for referenced variables.
4416 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004417 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4418 Stmt *S = AStmt;
4419 while (--ThisCaptureLevel >= 0)
4420 S = cast<CapturedStmt>(S)->getCapturedStmt();
4421 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004422 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4423 !isOpenMPTaskingDirective(Kind)) {
4424 // Visit subcaptures to generate implicit clauses for captured vars.
4425 auto *CS = cast<CapturedStmt>(AStmt);
4426 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4427 getOpenMPCaptureRegions(CaptureRegions, Kind);
4428 // Ignore outer tasking regions for target directives.
4429 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4430 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4431 DSAChecker.visitSubCaptures(CS);
4432 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004433 if (DSAChecker.isErrorFound())
4434 return StmtError();
4435 // Generate list of implicitly defined firstprivate variables.
4436 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004437
Alexey Bataev88202be2017-07-27 13:20:36 +00004438 SmallVector<Expr *, 4> ImplicitFirstprivates(
4439 DSAChecker.getImplicitFirstprivate().begin(),
4440 DSAChecker.getImplicitFirstprivate().end());
cchene06f3e02019-11-15 13:02:06 -05004441 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4442 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4443 ArrayRef<Expr *> ImplicitMap =
4444 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4445 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4446 }
Alexey Bataev88202be2017-07-27 13:20:36 +00004447 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004448 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004449 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004450 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004451 if (E)
4452 ImplicitFirstprivates.emplace_back(E);
4453 }
4454 }
4455 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004456 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004457 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4458 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004459 ClausesWithImplicit.push_back(Implicit);
4460 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004461 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004462 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004463 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004464 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004465 }
cchene06f3e02019-11-15 13:02:06 -05004466 int ClauseKindCnt = -1;
4467 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4468 ++ClauseKindCnt;
4469 if (ImplicitMap.empty())
4470 continue;
Michael Kruse4304e9d2019-02-19 16:38:20 +00004471 CXXScopeSpec MapperIdScopeSpec;
4472 DeclarationNameInfo MapperId;
cchene06f3e02019-11-15 13:02:06 -05004473 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004474 if (OMPClause *Implicit = ActOnOpenMPMapClause(
cchene06f3e02019-11-15 13:02:06 -05004475 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4476 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4477 ImplicitMap, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004478 ClausesWithImplicit.emplace_back(Implicit);
4479 ErrorFound |=
cchene06f3e02019-11-15 13:02:06 -05004480 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004481 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004482 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004483 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004484 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004485 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004486
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004487 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004488 switch (Kind) {
4489 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004490 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4491 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004492 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004493 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004494 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004495 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4496 VarsWithInheritedDSA);
Alexey Bataevd08c0562019-11-19 12:07:54 -05004497 if (LangOpts.OpenMP >= 50)
4498 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004499 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004500 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004501 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4502 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004503 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004504 case OMPD_for_simd:
4505 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4506 EndLoc, VarsWithInheritedDSA);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05004507 if (LangOpts.OpenMP >= 50)
4508 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004509 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004510 case OMPD_sections:
4511 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4512 EndLoc);
4513 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004514 case OMPD_section:
4515 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004516 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004517 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4518 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004519 case OMPD_single:
4520 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4521 EndLoc);
4522 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004523 case OMPD_master:
4524 assert(ClausesWithImplicit.empty() &&
4525 "No clauses are allowed for 'omp master' directive");
4526 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4527 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004528 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004529 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4530 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004531 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004532 case OMPD_parallel_for:
4533 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4534 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004535 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004536 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004537 case OMPD_parallel_for_simd:
4538 Res = ActOnOpenMPParallelForSimdDirective(
4539 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004540 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004541 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004542 case OMPD_parallel_sections:
4543 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4544 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004545 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004546 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004547 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004548 Res =
4549 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004550 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004551 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004552 case OMPD_taskyield:
4553 assert(ClausesWithImplicit.empty() &&
4554 "No clauses are allowed for 'omp taskyield' directive");
4555 assert(AStmt == nullptr &&
4556 "No associated statement allowed for 'omp taskyield' directive");
4557 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4558 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004559 case OMPD_barrier:
4560 assert(ClausesWithImplicit.empty() &&
4561 "No clauses are allowed for 'omp barrier' directive");
4562 assert(AStmt == nullptr &&
4563 "No associated statement allowed for 'omp barrier' directive");
4564 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4565 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004566 case OMPD_taskwait:
4567 assert(ClausesWithImplicit.empty() &&
4568 "No clauses are allowed for 'omp taskwait' directive");
4569 assert(AStmt == nullptr &&
4570 "No associated statement allowed for 'omp taskwait' directive");
4571 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4572 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004573 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004574 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4575 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004576 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004577 case OMPD_flush:
4578 assert(AStmt == nullptr &&
4579 "No associated statement allowed for 'omp flush' directive");
4580 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4581 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004582 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004583 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4584 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004585 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004586 case OMPD_atomic:
4587 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4588 EndLoc);
4589 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004590 case OMPD_teams:
4591 Res =
4592 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4593 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004594 case OMPD_target:
4595 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4596 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004597 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004598 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004599 case OMPD_target_parallel:
4600 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4601 StartLoc, EndLoc);
4602 AllowedNameModifiers.push_back(OMPD_target);
4603 AllowedNameModifiers.push_back(OMPD_parallel);
4604 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004605 case OMPD_target_parallel_for:
4606 Res = ActOnOpenMPTargetParallelForDirective(
4607 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4608 AllowedNameModifiers.push_back(OMPD_target);
4609 AllowedNameModifiers.push_back(OMPD_parallel);
4610 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004611 case OMPD_cancellation_point:
4612 assert(ClausesWithImplicit.empty() &&
4613 "No clauses are allowed for 'omp cancellation point' directive");
4614 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4615 "cancellation point' directive");
4616 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4617 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004618 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004619 assert(AStmt == nullptr &&
4620 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004621 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4622 CancelRegion);
4623 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004624 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004625 case OMPD_target_data:
4626 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4627 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004628 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004629 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004630 case OMPD_target_enter_data:
4631 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004632 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004633 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4634 break;
Samuel Antao72590762016-01-19 20:04:50 +00004635 case OMPD_target_exit_data:
4636 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004637 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004638 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4639 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004640 case OMPD_taskloop:
4641 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4642 EndLoc, VarsWithInheritedDSA);
4643 AllowedNameModifiers.push_back(OMPD_taskloop);
4644 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004645 case OMPD_taskloop_simd:
4646 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4647 EndLoc, VarsWithInheritedDSA);
4648 AllowedNameModifiers.push_back(OMPD_taskloop);
4649 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004650 case OMPD_master_taskloop:
4651 Res = ActOnOpenMPMasterTaskLoopDirective(
4652 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4653 AllowedNameModifiers.push_back(OMPD_taskloop);
4654 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004655 case OMPD_master_taskloop_simd:
4656 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4657 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4658 AllowedNameModifiers.push_back(OMPD_taskloop);
4659 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004660 case OMPD_parallel_master_taskloop:
4661 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4662 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4663 AllowedNameModifiers.push_back(OMPD_taskloop);
4664 AllowedNameModifiers.push_back(OMPD_parallel);
4665 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004666 case OMPD_parallel_master_taskloop_simd:
4667 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4668 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4669 AllowedNameModifiers.push_back(OMPD_taskloop);
4670 AllowedNameModifiers.push_back(OMPD_parallel);
4671 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004672 case OMPD_distribute:
4673 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4674 EndLoc, VarsWithInheritedDSA);
4675 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004676 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004677 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4678 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004679 AllowedNameModifiers.push_back(OMPD_target_update);
4680 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004681 case OMPD_distribute_parallel_for:
4682 Res = ActOnOpenMPDistributeParallelForDirective(
4683 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4684 AllowedNameModifiers.push_back(OMPD_parallel);
4685 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004686 case OMPD_distribute_parallel_for_simd:
4687 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4688 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4689 AllowedNameModifiers.push_back(OMPD_parallel);
4690 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004691 case OMPD_distribute_simd:
4692 Res = ActOnOpenMPDistributeSimdDirective(
4693 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4694 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004695 case OMPD_target_parallel_for_simd:
4696 Res = ActOnOpenMPTargetParallelForSimdDirective(
4697 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4698 AllowedNameModifiers.push_back(OMPD_target);
4699 AllowedNameModifiers.push_back(OMPD_parallel);
4700 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004701 case OMPD_target_simd:
4702 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4703 EndLoc, VarsWithInheritedDSA);
4704 AllowedNameModifiers.push_back(OMPD_target);
4705 break;
Kelvin Li02532872016-08-05 14:37:37 +00004706 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004707 Res = ActOnOpenMPTeamsDistributeDirective(
4708 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004709 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004710 case OMPD_teams_distribute_simd:
4711 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4712 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4713 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004714 case OMPD_teams_distribute_parallel_for_simd:
4715 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4716 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4717 AllowedNameModifiers.push_back(OMPD_parallel);
4718 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004719 case OMPD_teams_distribute_parallel_for:
4720 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4721 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4722 AllowedNameModifiers.push_back(OMPD_parallel);
4723 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004724 case OMPD_target_teams:
4725 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4726 EndLoc);
4727 AllowedNameModifiers.push_back(OMPD_target);
4728 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004729 case OMPD_target_teams_distribute:
4730 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4731 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4732 AllowedNameModifiers.push_back(OMPD_target);
4733 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004734 case OMPD_target_teams_distribute_parallel_for:
4735 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4736 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4737 AllowedNameModifiers.push_back(OMPD_target);
4738 AllowedNameModifiers.push_back(OMPD_parallel);
4739 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004740 case OMPD_target_teams_distribute_parallel_for_simd:
4741 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4742 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4743 AllowedNameModifiers.push_back(OMPD_target);
4744 AllowedNameModifiers.push_back(OMPD_parallel);
4745 break;
Kelvin Lida681182017-01-10 18:08:18 +00004746 case OMPD_target_teams_distribute_simd:
4747 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4748 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4749 AllowedNameModifiers.push_back(OMPD_target);
4750 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004751 case OMPD_declare_target:
4752 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004753 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004754 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004755 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004756 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004757 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004758 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004759 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004760 llvm_unreachable("OpenMP Directive is not allowed");
4761 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004762 llvm_unreachable("Unknown OpenMP directive");
4763 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004764
Roman Lebedevb5700602019-03-20 16:32:36 +00004765 ErrorFound = Res.isInvalid() || ErrorFound;
4766
Alexey Bataev412254a2019-05-09 18:44:53 +00004767 // Check variables in the clauses if default(none) was specified.
4768 if (DSAStack->getDefaultDSA() == DSA_none) {
4769 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4770 for (OMPClause *C : Clauses) {
4771 switch (C->getClauseKind()) {
4772 case OMPC_num_threads:
4773 case OMPC_dist_schedule:
4774 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004775 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004776 break;
4777 continue;
4778 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004779 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004780 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4781 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004782 if (isOpenMPParallelDirective(Kind) &&
4783 isOpenMPTaskLoopDirective(Kind) &&
4784 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4785 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004786 continue;
4787 case OMPC_schedule:
4788 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004789 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004790 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004791 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004792 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004793 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004794 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004795 break;
4796 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004797 case OMPC_ordered:
4798 case OMPC_device:
4799 case OMPC_num_teams:
4800 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004801 case OMPC_hint:
4802 case OMPC_collapse:
4803 case OMPC_safelen:
4804 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004805 case OMPC_default:
4806 case OMPC_proc_bind:
4807 case OMPC_private:
4808 case OMPC_firstprivate:
4809 case OMPC_lastprivate:
4810 case OMPC_shared:
4811 case OMPC_reduction:
4812 case OMPC_task_reduction:
4813 case OMPC_in_reduction:
4814 case OMPC_linear:
4815 case OMPC_aligned:
4816 case OMPC_copyin:
4817 case OMPC_copyprivate:
4818 case OMPC_nowait:
4819 case OMPC_untied:
4820 case OMPC_mergeable:
4821 case OMPC_allocate:
4822 case OMPC_read:
4823 case OMPC_write:
4824 case OMPC_update:
4825 case OMPC_capture:
4826 case OMPC_seq_cst:
4827 case OMPC_depend:
4828 case OMPC_threads:
4829 case OMPC_simd:
4830 case OMPC_map:
4831 case OMPC_nogroup:
4832 case OMPC_defaultmap:
4833 case OMPC_to:
4834 case OMPC_from:
4835 case OMPC_use_device_ptr:
4836 case OMPC_is_device_ptr:
4837 continue;
4838 case OMPC_allocator:
4839 case OMPC_flush:
4840 case OMPC_threadprivate:
4841 case OMPC_uniform:
4842 case OMPC_unknown:
4843 case OMPC_unified_address:
4844 case OMPC_unified_shared_memory:
4845 case OMPC_reverse_offload:
4846 case OMPC_dynamic_allocators:
4847 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004848 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004849 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004850 llvm_unreachable("Unexpected clause");
4851 }
4852 for (Stmt *CC : C->children()) {
4853 if (CC)
4854 DSAChecker.Visit(CC);
4855 }
4856 }
4857 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4858 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4859 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004860 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004861 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4862 continue;
4863 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05004864 if (DSAStack->getDefaultDSA() == DSA_none) {
4865 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4866 << P.first << P.second->getSourceRange();
4867 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4868 } else if (getLangOpts().OpenMP >= 50) {
4869 Diag(P.second->getExprLoc(),
4870 diag::err_omp_defaultmap_no_attr_for_variable)
4871 << P.first << P.second->getSourceRange();
4872 Diag(DSAStack->getDefaultDSALocation(),
4873 diag::note_omp_defaultmap_attr_none);
4874 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00004875 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004876
4877 if (!AllowedNameModifiers.empty())
4878 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4879 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004880
Alexey Bataeved09d242014-05-28 05:53:51 +00004881 if (ErrorFound)
4882 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004883
4884 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4885 Res.getAs<OMPExecutableDirective>()
4886 ->getStructuredBlock()
4887 ->setIsOMPStructuredBlock(true);
4888 }
4889
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004890 if (!CurContext->isDependentContext() &&
4891 isOpenMPTargetExecutionDirective(Kind) &&
4892 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4893 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4894 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4895 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4896 // Register target to DSA Stack.
4897 DSAStack->addTargetDirLocation(StartLoc);
4898 }
4899
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004900 return Res;
4901}
4902
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004903Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4904 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004905 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004906 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4907 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004908 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004909 assert(Linears.size() == LinModifiers.size());
4910 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004911 if (!DG || DG.get().isNull())
4912 return DeclGroupPtrTy();
4913
Alexey Bataevd158cf62019-09-13 20:18:17 +00004914 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004915 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004916 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4917 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004918 return DG;
4919 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004920 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004921 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4922 ADecl = FTD->getTemplatedDecl();
4923
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004924 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4925 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004926 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004927 return DeclGroupPtrTy();
4928 }
4929
Alexey Bataev2af33e32016-04-07 12:45:37 +00004930 // OpenMP [2.8.2, declare simd construct, Description]
4931 // The parameter of the simdlen clause must be a constant positive integer
4932 // expression.
4933 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004934 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004935 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004936 // OpenMP [2.8.2, declare simd construct, Description]
4937 // The special this pointer can be used as if was one of the arguments to the
4938 // function in any of the linear, aligned, or uniform clauses.
4939 // The uniform clause declares one or more arguments to have an invariant
4940 // value for all concurrent invocations of the function in the execution of a
4941 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004942 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4943 const Expr *UniformedLinearThis = nullptr;
4944 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004945 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004946 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4947 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004948 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4949 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004950 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004951 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004952 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004953 }
4954 if (isa<CXXThisExpr>(E)) {
4955 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004956 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004957 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004958 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4959 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004960 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004961 // OpenMP [2.8.2, declare simd construct, Description]
4962 // The aligned clause declares that the object to which each list item points
4963 // is aligned to the number of bytes expressed in the optional parameter of
4964 // the aligned clause.
4965 // The special this pointer can be used as if was one of the arguments to the
4966 // function in any of the linear, aligned, or uniform clauses.
4967 // The type of list items appearing in the aligned clause must be array,
4968 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004969 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4970 const Expr *AlignedThis = nullptr;
4971 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004972 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004973 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4974 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4975 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004976 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4977 FD->getParamDecl(PVD->getFunctionScopeIndex())
4978 ->getCanonicalDecl() == CanonPVD) {
4979 // OpenMP [2.8.1, simd construct, Restrictions]
4980 // A list-item cannot appear in more than one aligned clause.
4981 if (AlignedArgs.count(CanonPVD) > 0) {
4982 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4983 << 1 << E->getSourceRange();
4984 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4985 diag::note_omp_explicit_dsa)
4986 << getOpenMPClauseName(OMPC_aligned);
4987 continue;
4988 }
4989 AlignedArgs[CanonPVD] = E;
4990 QualType QTy = PVD->getType()
4991 .getNonReferenceType()
4992 .getUnqualifiedType()
4993 .getCanonicalType();
4994 const Type *Ty = QTy.getTypePtrOrNull();
4995 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4996 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4997 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4998 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4999 }
5000 continue;
5001 }
5002 }
5003 if (isa<CXXThisExpr>(E)) {
5004 if (AlignedThis) {
5005 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
5006 << 2 << E->getSourceRange();
5007 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5008 << getOpenMPClauseName(OMPC_aligned);
5009 }
5010 AlignedThis = E;
5011 continue;
5012 }
5013 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5014 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5015 }
5016 // The optional parameter of the aligned clause, alignment, must be a constant
5017 // positive integer expression. If no optional parameter is specified,
5018 // implementation-defined default alignments for SIMD instructions on the
5019 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005020 SmallVector<const Expr *, 4> NewAligns;
5021 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005022 ExprResult Align;
5023 if (E)
5024 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5025 NewAligns.push_back(Align.get());
5026 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005027 // OpenMP [2.8.2, declare simd construct, Description]
5028 // The linear clause declares one or more list items to be private to a SIMD
5029 // lane and to have a linear relationship with respect to the iteration space
5030 // of a loop.
5031 // The special this pointer can be used as if was one of the arguments to the
5032 // function in any of the linear, aligned, or uniform clauses.
5033 // When a linear-step expression is specified in a linear clause it must be
5034 // either a constant integer expression or an integer-typed parameter that is
5035 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005036 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005037 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5038 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005039 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005040 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5041 ++MI;
5042 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005043 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5044 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5045 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005046 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5047 FD->getParamDecl(PVD->getFunctionScopeIndex())
5048 ->getCanonicalDecl() == CanonPVD) {
5049 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5050 // A list-item cannot appear in more than one linear clause.
5051 if (LinearArgs.count(CanonPVD) > 0) {
5052 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5053 << getOpenMPClauseName(OMPC_linear)
5054 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5055 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5056 diag::note_omp_explicit_dsa)
5057 << getOpenMPClauseName(OMPC_linear);
5058 continue;
5059 }
5060 // Each argument can appear in at most one uniform or linear clause.
5061 if (UniformedArgs.count(CanonPVD) > 0) {
5062 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5063 << getOpenMPClauseName(OMPC_linear)
5064 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5065 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5066 diag::note_omp_explicit_dsa)
5067 << getOpenMPClauseName(OMPC_uniform);
5068 continue;
5069 }
5070 LinearArgs[CanonPVD] = E;
5071 if (E->isValueDependent() || E->isTypeDependent() ||
5072 E->isInstantiationDependent() ||
5073 E->containsUnexpandedParameterPack())
5074 continue;
5075 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5076 PVD->getOriginalType());
5077 continue;
5078 }
5079 }
5080 if (isa<CXXThisExpr>(E)) {
5081 if (UniformedLinearThis) {
5082 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5083 << getOpenMPClauseName(OMPC_linear)
5084 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5085 << E->getSourceRange();
5086 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5087 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5088 : OMPC_linear);
5089 continue;
5090 }
5091 UniformedLinearThis = E;
5092 if (E->isValueDependent() || E->isTypeDependent() ||
5093 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5094 continue;
5095 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5096 E->getType());
5097 continue;
5098 }
5099 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5100 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5101 }
5102 Expr *Step = nullptr;
5103 Expr *NewStep = nullptr;
5104 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005105 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005106 // Skip the same step expression, it was checked already.
5107 if (Step == E || !E) {
5108 NewSteps.push_back(E ? NewStep : nullptr);
5109 continue;
5110 }
5111 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005112 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5113 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5114 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005115 if (UniformedArgs.count(CanonPVD) == 0) {
5116 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5117 << Step->getSourceRange();
5118 } else if (E->isValueDependent() || E->isTypeDependent() ||
5119 E->isInstantiationDependent() ||
5120 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005121 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005122 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005123 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005124 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5125 << Step->getSourceRange();
5126 }
5127 continue;
5128 }
5129 NewStep = Step;
5130 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5131 !Step->isInstantiationDependent() &&
5132 !Step->containsUnexpandedParameterPack()) {
5133 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5134 .get();
5135 if (NewStep)
5136 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5137 }
5138 NewSteps.push_back(NewStep);
5139 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005140 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5141 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005142 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005143 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5144 const_cast<Expr **>(Linears.data()), Linears.size(),
5145 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5146 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005147 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005148 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005149}
5150
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005151Optional<std::pair<FunctionDecl *, Expr *>>
5152Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5153 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005154 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005155 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005156
5157 const int VariantId = 1;
5158 // Must be applied only to single decl.
5159 if (!DG.get().isSingleDecl()) {
5160 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5161 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005162 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005163 }
5164 Decl *ADecl = DG.get().getSingleDecl();
5165 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5166 ADecl = FTD->getTemplatedDecl();
5167
5168 // Decl must be a function.
5169 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5170 if (!FD) {
5171 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5172 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005173 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005174 }
5175
5176 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5177 return FD->hasAttrs() &&
5178 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5179 FD->hasAttr<TargetAttr>());
5180 };
5181 // OpenMP is not compatible with CPU-specific attributes.
5182 if (HasMultiVersionAttributes(FD)) {
5183 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5184 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005185 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005186 }
5187
5188 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005189 if (FD->isUsed(false))
5190 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005191 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005192
5193 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005194 const FunctionDecl *Definition;
5195 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5196 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005197 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5198 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005199
5200 // The VariantRef must point to function.
5201 if (!VariantRef) {
5202 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005203 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005204 }
5205
5206 // Do not check templates, wait until instantiation.
5207 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5208 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005209 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5210 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005211
5212 // Convert VariantRef expression to the type of the original function to
5213 // resolve possible conflicts.
5214 ExprResult VariantRefCast;
5215 if (LangOpts.CPlusPlus) {
5216 QualType FnPtrType;
5217 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5218 if (Method && !Method->isStatic()) {
5219 const Type *ClassType =
5220 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5221 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5222 ExprResult ER;
5223 {
5224 // Build adrr_of unary op to correctly handle type checks for member
5225 // functions.
5226 Sema::TentativeAnalysisScope Trap(*this);
5227 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5228 VariantRef);
5229 }
5230 if (!ER.isUsable()) {
5231 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5232 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005233 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005234 }
5235 VariantRef = ER.get();
5236 } else {
5237 FnPtrType = Context.getPointerType(FD->getType());
5238 }
5239 ImplicitConversionSequence ICS =
5240 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5241 /*SuppressUserConversions=*/false,
5242 /*AllowExplicit=*/false,
5243 /*InOverloadResolution=*/false,
5244 /*CStyle=*/false,
5245 /*AllowObjCWritebackConversion=*/false);
5246 if (ICS.isFailure()) {
5247 Diag(VariantRef->getExprLoc(),
5248 diag::err_omp_declare_variant_incompat_types)
5249 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005250 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005251 }
5252 VariantRefCast = PerformImplicitConversion(
5253 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5254 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005255 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005256 // Drop previously built artificial addr_of unary op for member functions.
5257 if (Method && !Method->isStatic()) {
5258 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5259 if (auto *UO = dyn_cast<UnaryOperator>(
5260 PossibleAddrOfVariantRef->IgnoreImplicit()))
5261 VariantRefCast = UO->getSubExpr();
5262 }
5263 } else {
5264 VariantRefCast = VariantRef;
5265 }
5266
5267 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5268 if (!ER.isUsable() ||
5269 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5270 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5271 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005272 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005273 }
5274
5275 // The VariantRef must point to function.
5276 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5277 if (!DRE) {
5278 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5279 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005280 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005281 }
5282 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5283 if (!NewFD) {
5284 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5285 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005286 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005287 }
5288
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005289 // Check if variant function is not marked with declare variant directive.
5290 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5291 Diag(VariantRef->getExprLoc(),
5292 diag::warn_omp_declare_variant_marked_as_declare_variant)
5293 << VariantRef->getSourceRange();
5294 SourceRange SR =
5295 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5296 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005297 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005298 }
5299
Alexey Bataevd158cf62019-09-13 20:18:17 +00005300 enum DoesntSupport {
5301 VirtFuncs = 1,
5302 Constructors = 3,
5303 Destructors = 4,
5304 DeletedFuncs = 5,
5305 DefaultedFuncs = 6,
5306 ConstexprFuncs = 7,
5307 ConstevalFuncs = 8,
5308 };
5309 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5310 if (CXXFD->isVirtual()) {
5311 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5312 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005313 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005314 }
5315
5316 if (isa<CXXConstructorDecl>(FD)) {
5317 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5318 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005319 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005320 }
5321
5322 if (isa<CXXDestructorDecl>(FD)) {
5323 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5324 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005325 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005326 }
5327 }
5328
5329 if (FD->isDeleted()) {
5330 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5331 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005332 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005333 }
5334
5335 if (FD->isDefaulted()) {
5336 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5337 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005338 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005339 }
5340
5341 if (FD->isConstexpr()) {
5342 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5343 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005344 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005345 }
5346
5347 // Check general compatibility.
5348 if (areMultiversionVariantFunctionsCompatible(
5349 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5350 PartialDiagnosticAt(
5351 SR.getBegin(),
5352 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5353 PartialDiagnosticAt(
5354 VariantRef->getExprLoc(),
5355 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5356 PartialDiagnosticAt(VariantRef->getExprLoc(),
5357 PDiag(diag::err_omp_declare_variant_diff)
5358 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005359 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5360 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005361 return None;
5362 return std::make_pair(FD, cast<Expr>(DRE));
5363}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005364
Alexey Bataev9ff34742019-09-25 19:43:37 +00005365void Sema::ActOnOpenMPDeclareVariantDirective(
5366 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005367 ArrayRef<OMPCtxSelectorData> Data) {
5368 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005369 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005370 SmallVector<Expr *, 4> CtxScores;
5371 SmallVector<unsigned, 4> CtxSets;
5372 SmallVector<unsigned, 4> Ctxs;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005373 SmallVector<StringRef, 4> ImplVendors, DeviceKinds;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005374 bool IsError = false;
5375 for (const OMPCtxSelectorData &D : Data) {
5376 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5377 OpenMPContextSelectorKind Ctx = D.Ctx;
5378 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5379 return;
5380 Expr *Score = nullptr;
5381 if (D.Score.isUsable()) {
5382 Score = D.Score.get();
5383 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5384 !Score->isInstantiationDependent() &&
5385 !Score->containsUnexpandedParameterPack()) {
5386 Score =
5387 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5388 .get();
5389 if (Score)
5390 Score = VerifyIntegerConstantExpression(Score).get();
5391 }
5392 } else {
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005393 // OpenMP 5.0, 2.3.3 Matching and Scoring Context Selectors.
5394 // The kind, arch, and isa selectors are given the values 2^l, 2^(l+1) and
5395 // 2^(l+2), respectively, where l is the number of traits in the construct
5396 // set.
5397 // TODO: implement correct logic for isa and arch traits.
5398 // TODO: take the construct context set into account when it is
5399 // implemented.
5400 int L = 0; // Currently set the number of traits in construct set to 0,
5401 // since the construct trait set in not supported yet.
5402 if (CtxSet == OMP_CTX_SET_device && Ctx == OMP_CTX_kind)
5403 Score = ActOnIntegerConstant(SourceLocation(), std::pow(2, L)).get();
5404 else
5405 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005406 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005407 switch (CtxSet) {
5408 case OMP_CTX_SET_implementation:
5409 switch (Ctx) {
5410 case OMP_CTX_vendor:
5411 ImplVendors.append(D.Names.begin(), D.Names.end());
5412 break;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005413 case OMP_CTX_kind:
5414 case OMP_CTX_unknown:
5415 llvm_unreachable("Unexpected context selector kind.");
5416 }
5417 break;
5418 case OMP_CTX_SET_device:
5419 switch (Ctx) {
5420 case OMP_CTX_kind:
5421 DeviceKinds.append(D.Names.begin(), D.Names.end());
5422 break;
5423 case OMP_CTX_vendor:
Alexey Bataevfde11e92019-11-07 11:03:10 -05005424 case OMP_CTX_unknown:
5425 llvm_unreachable("Unexpected context selector kind.");
5426 }
5427 break;
5428 case OMP_CTX_SET_unknown:
5429 llvm_unreachable("Unexpected context selector set kind.");
5430 }
5431 IsError = IsError || !Score;
5432 CtxSets.push_back(CtxSet);
5433 Ctxs.push_back(Ctx);
5434 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005435 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005436 if (!IsError) {
5437 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5438 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5439 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005440 ImplVendors.begin(), ImplVendors.size(), DeviceKinds.begin(),
5441 DeviceKinds.size(), SR);
Alexey Bataevfde11e92019-11-07 11:03:10 -05005442 FD->addAttr(NewAttr);
5443 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005444}
5445
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005446void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5447 FunctionDecl *Func,
5448 bool MightBeOdrUse) {
5449 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5450
5451 if (!Func->isDependentContext() && Func->hasAttrs()) {
5452 for (OMPDeclareVariantAttr *A :
5453 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5454 // TODO: add checks for active OpenMP context where possible.
5455 Expr *VariantRef = A->getVariantFuncRef();
5456 auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
5457 auto *F = cast<FunctionDecl>(DRE->getDecl());
5458 if (!F->isDefined() && F->isTemplateInstantiation())
5459 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5460 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5461 }
5462 }
5463}
5464
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005465StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5466 Stmt *AStmt,
5467 SourceLocation StartLoc,
5468 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005469 if (!AStmt)
5470 return StmtError();
5471
Alexey Bataeve3727102018-04-18 15:57:46 +00005472 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005473 // 1.2.2 OpenMP Language Terminology
5474 // Structured block - An executable statement with a single entry at the
5475 // top and a single exit at the bottom.
5476 // The point of exit cannot be a branch out of the structured block.
5477 // longjmp() and throw() must not violate the entry/exit criteria.
5478 CS->getCapturedDecl()->setNothrow();
5479
Reid Kleckner87a31802018-03-12 21:43:02 +00005480 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005481
Alexey Bataev25e5b442015-09-15 12:52:43 +00005482 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5483 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005484}
5485
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005486namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005487/// Iteration space of a single for loop.
5488struct LoopIterationSpace final {
5489 /// True if the condition operator is the strict compare operator (<, > or
5490 /// !=).
5491 bool IsStrictCompare = false;
5492 /// Condition of the loop.
5493 Expr *PreCond = nullptr;
5494 /// This expression calculates the number of iterations in the loop.
5495 /// It is always possible to calculate it before starting the loop.
5496 Expr *NumIterations = nullptr;
5497 /// The loop counter variable.
5498 Expr *CounterVar = nullptr;
5499 /// Private loop counter variable.
5500 Expr *PrivateCounterVar = nullptr;
5501 /// This is initializer for the initial value of #CounterVar.
5502 Expr *CounterInit = nullptr;
5503 /// This is step for the #CounterVar used to generate its update:
5504 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5505 Expr *CounterStep = nullptr;
5506 /// Should step be subtracted?
5507 bool Subtract = false;
5508 /// Source range of the loop init.
5509 SourceRange InitSrcRange;
5510 /// Source range of the loop condition.
5511 SourceRange CondSrcRange;
5512 /// Source range of the loop increment.
5513 SourceRange IncSrcRange;
5514 /// Minimum value that can have the loop control variable. Used to support
5515 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5516 /// since only such variables can be used in non-loop invariant expressions.
5517 Expr *MinValue = nullptr;
5518 /// Maximum value that can have the loop control variable. Used to support
5519 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5520 /// since only such variables can be used in non-loop invariant expressions.
5521 Expr *MaxValue = nullptr;
5522 /// true, if the lower bound depends on the outer loop control var.
5523 bool IsNonRectangularLB = false;
5524 /// true, if the upper bound depends on the outer loop control var.
5525 bool IsNonRectangularUB = false;
5526 /// Index of the loop this loop depends on and forms non-rectangular loop
5527 /// nest.
5528 unsigned LoopDependentIdx = 0;
5529 /// Final condition for the non-rectangular loop nest support. It is used to
5530 /// check that the number of iterations for this particular counter must be
5531 /// finished.
5532 Expr *FinalCondition = nullptr;
5533};
5534
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005535/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005536/// extracting iteration space of each loop in the loop nest, that will be used
5537/// for IR generation.
5538class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005539 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005540 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005541 /// Data-sharing stack.
5542 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005543 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005544 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005545 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005546 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005547 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005548 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005549 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005550 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005551 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005552 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005553 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005554 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005555 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005556 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005557 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005558 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005559 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005560 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005561 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005562 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005563 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005564 /// Var < UB
5565 /// Var <= UB
5566 /// UB > Var
5567 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005568 /// This will have no value when the condition is !=
5569 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005570 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005571 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005572 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005573 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005574 /// The outer loop counter this loop depends on (if any).
5575 const ValueDecl *DepDecl = nullptr;
5576 /// Contains number of loop (starts from 1) on which loop counter init
5577 /// expression of this loop depends on.
5578 Optional<unsigned> InitDependOnLC;
5579 /// Contains number of loop (starts from 1) on which loop counter condition
5580 /// expression of this loop depends on.
5581 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005582 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005583 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005584 /// Original condition required for checking of the exit condition for
5585 /// non-rectangular loop.
5586 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005587
5588public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005589 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5590 SourceLocation DefaultLoc)
5591 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5592 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005593 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005594 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005595 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005596 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005597 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005598 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005599 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005600 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005601 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005602 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005603 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005604 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005605 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005606 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005607 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005608 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005609 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005610 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005611 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005612 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005613 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005614 /// True, if the compare operator is strict (<, > or !=).
5615 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005616 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005617 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005618 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005619 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005620 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005621 Expr *
5622 buildPreCond(Scope *S, Expr *Cond,
5623 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005624 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005625 DeclRefExpr *
5626 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5627 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005628 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005629 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005630 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005631 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005632 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005633 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005634 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005635 /// Build loop data with counter value for depend clauses in ordered
5636 /// directives.
5637 Expr *
5638 buildOrderedLoopData(Scope *S, Expr *Counter,
5639 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5640 SourceLocation Loc, Expr *Inc = nullptr,
5641 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005642 /// Builds the minimum value for the loop counter.
5643 std::pair<Expr *, Expr *> buildMinMaxValues(
5644 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5645 /// Builds final condition for the non-rectangular loops.
5646 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005647 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005648 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005649 /// Returns true if the initializer forms non-rectangular loop.
5650 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5651 /// Returns true if the condition forms non-rectangular loop.
5652 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5653 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5654 unsigned getLoopDependentIdx() const {
5655 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5656 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005657
5658private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005659 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005660 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005661 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005662 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005663 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5664 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005665 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005666 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5667 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005668 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005669 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005670};
5671
Alexey Bataeve3727102018-04-18 15:57:46 +00005672bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005673 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005674 assert(!LB && !UB && !Step);
5675 return false;
5676 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005677 return LCDecl->getType()->isDependentType() ||
5678 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5679 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005680}
5681
Alexey Bataeve3727102018-04-18 15:57:46 +00005682bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005683 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005684 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005685 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005686 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005687 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005688 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005689 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005690 LCDecl = getCanonicalDecl(NewLCDecl);
5691 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005692 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5693 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005694 if ((Ctor->isCopyOrMoveConstructor() ||
5695 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5696 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005697 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005698 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005699 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005700 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005701 return false;
5702}
5703
Alexey Bataev316ccf62019-01-29 18:51:58 +00005704bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5705 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005706 bool StrictOp, SourceRange SR,
5707 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005708 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005709 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5710 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005711 if (!NewUB)
5712 return true;
5713 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005714 if (LessOp)
5715 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005716 TestIsStrictOp = StrictOp;
5717 ConditionSrcRange = SR;
5718 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005719 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005720 return false;
5721}
5722
Alexey Bataeve3727102018-04-18 15:57:46 +00005723bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005724 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005725 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005726 if (!NewStep)
5727 return true;
5728 if (!NewStep->isValueDependent()) {
5729 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005730 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005731 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5732 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005733 if (Val.isInvalid())
5734 return true;
5735 NewStep = Val.get();
5736
5737 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5738 // If test-expr is of form var relational-op b and relational-op is < or
5739 // <= then incr-expr must cause var to increase on each iteration of the
5740 // loop. If test-expr is of form var relational-op b and relational-op is
5741 // > or >= then incr-expr must cause var to decrease on each iteration of
5742 // the loop.
5743 // If test-expr is of form b relational-op var and relational-op is < or
5744 // <= then incr-expr must cause var to decrease on each iteration of the
5745 // loop. If test-expr is of form b relational-op var and relational-op is
5746 // > or >= then incr-expr must cause var to increase on each iteration of
5747 // the loop.
5748 llvm::APSInt Result;
5749 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5750 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5751 bool IsConstNeg =
5752 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005753 bool IsConstPos =
5754 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005755 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005756
5757 // != with increment is treated as <; != with decrement is treated as >
5758 if (!TestIsLessOp.hasValue())
5759 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005760 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005761 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005762 (IsConstNeg || (IsUnsigned && Subtract)) :
5763 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005764 SemaRef.Diag(NewStep->getExprLoc(),
5765 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005766 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005767 SemaRef.Diag(ConditionLoc,
5768 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005769 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005770 return true;
5771 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005772 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005773 NewStep =
5774 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5775 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005776 Subtract = !Subtract;
5777 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005778 }
5779
5780 Step = NewStep;
5781 SubtractStep = Subtract;
5782 return false;
5783}
5784
Alexey Bataev622af1d2019-04-24 19:58:30 +00005785namespace {
5786/// Checker for the non-rectangular loops. Checks if the initializer or
5787/// condition expression references loop counter variable.
5788class LoopCounterRefChecker final
5789 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5790 Sema &SemaRef;
5791 DSAStackTy &Stack;
5792 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005793 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005794 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005795 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005796 unsigned BaseLoopId = 0;
5797 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5798 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5799 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5800 << (IsInitializer ? 0 : 1);
5801 return false;
5802 }
5803 const auto &&Data = Stack.isLoopControlVariable(VD);
5804 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5805 // The type of the loop iterator on which we depend may not have a random
5806 // access iterator type.
5807 if (Data.first && VD->getType()->isRecordType()) {
5808 SmallString<128> Name;
5809 llvm::raw_svector_ostream OS(Name);
5810 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5811 /*Qualified=*/true);
5812 SemaRef.Diag(E->getExprLoc(),
5813 diag::err_omp_wrong_dependency_iterator_type)
5814 << OS.str();
5815 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5816 return false;
5817 }
5818 if (Data.first &&
5819 (DepDecl || (PrevDepDecl &&
5820 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5821 if (!DepDecl && PrevDepDecl)
5822 DepDecl = PrevDepDecl;
5823 SmallString<128> Name;
5824 llvm::raw_svector_ostream OS(Name);
5825 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5826 /*Qualified=*/true);
5827 SemaRef.Diag(E->getExprLoc(),
5828 diag::err_omp_invariant_or_linear_dependency)
5829 << OS.str();
5830 return false;
5831 }
5832 if (Data.first) {
5833 DepDecl = VD;
5834 BaseLoopId = Data.first;
5835 }
5836 return Data.first;
5837 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005838
5839public:
5840 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5841 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005842 if (isa<VarDecl>(VD))
5843 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005844 return false;
5845 }
5846 bool VisitMemberExpr(const MemberExpr *E) {
5847 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5848 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005849 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5850 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005851 }
5852 return false;
5853 }
5854 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005855 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005856 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005857 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005858 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005859 }
5860 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005861 const ValueDecl *CurLCDecl, bool IsInitializer,
5862 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005863 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005864 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5865 unsigned getBaseLoopId() const {
5866 assert(CurLCDecl && "Expected loop dependency.");
5867 return BaseLoopId;
5868 }
5869 const ValueDecl *getDepDecl() const {
5870 assert(CurLCDecl && "Expected loop dependency.");
5871 return DepDecl;
5872 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005873};
5874} // namespace
5875
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005876Optional<unsigned>
5877OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5878 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005879 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005880 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5881 DepDecl);
5882 if (LoopStmtChecker.Visit(S)) {
5883 DepDecl = LoopStmtChecker.getDepDecl();
5884 return LoopStmtChecker.getBaseLoopId();
5885 }
5886 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005887}
5888
Alexey Bataeve3727102018-04-18 15:57:46 +00005889bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005890 // Check init-expr for canonical loop form and save loop counter
5891 // variable - #Var and its initialization value - #LB.
5892 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5893 // var = lb
5894 // integer-type var = lb
5895 // random-access-iterator-type var = lb
5896 // pointer-type var = lb
5897 //
5898 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005899 if (EmitDiags) {
5900 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5901 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005902 return true;
5903 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005904 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5905 if (!ExprTemp->cleanupsHaveSideEffects())
5906 S = ExprTemp->getSubExpr();
5907
Alexander Musmana5f070a2014-10-01 06:03:56 +00005908 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005909 if (Expr *E = dyn_cast<Expr>(S))
5910 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005911 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005912 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005913 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005914 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5915 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5916 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005917 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5918 EmitDiags);
5919 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005920 }
5921 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5922 if (ME->isArrow() &&
5923 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005924 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5925 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005926 }
5927 }
David Majnemer9d168222016-08-05 17:44:54 +00005928 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005929 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005930 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005931 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005932 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005933 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005934 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005935 diag::ext_omp_loop_not_canonical_init)
5936 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005937 return setLCDeclAndLB(
5938 Var,
5939 buildDeclRefExpr(SemaRef, Var,
5940 Var->getType().getNonReferenceType(),
5941 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005942 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005943 }
5944 }
5945 }
David Majnemer9d168222016-08-05 17:44:54 +00005946 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005947 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005948 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005949 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005950 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5951 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005952 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5953 EmitDiags);
5954 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005955 }
5956 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5957 if (ME->isArrow() &&
5958 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005959 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5960 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005961 }
5962 }
5963 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005964
Alexey Bataeve3727102018-04-18 15:57:46 +00005965 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005966 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005967 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005968 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005969 << S->getSourceRange();
5970 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005971 return true;
5972}
5973
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005974/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005975/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005976static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005977 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005978 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005979 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005980 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005981 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005982 if ((Ctor->isCopyOrMoveConstructor() ||
5983 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5984 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005985 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005986 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5987 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005988 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005989 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005990 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005991 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5992 return getCanonicalDecl(ME->getMemberDecl());
5993 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005994}
5995
Alexey Bataeve3727102018-04-18 15:57:46 +00005996bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005997 // Check test-expr for canonical form, save upper-bound UB, flags for
5998 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00005999 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006000 // var relational-op b
6001 // b relational-op var
6002 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006003 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006004 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006005 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6006 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006007 return true;
6008 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006009 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006010 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006011 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006012 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006013 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006014 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6015 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006016 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6017 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6018 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006019 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6020 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006021 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6022 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6023 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006024 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6025 return setUB(
6026 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6027 /*LessOp=*/llvm::None,
6028 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006029 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006030 if (CE->getNumArgs() == 2) {
6031 auto Op = CE->getOperator();
6032 switch (Op) {
6033 case OO_Greater:
6034 case OO_GreaterEqual:
6035 case OO_Less:
6036 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006037 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6038 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006039 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6040 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006041 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6042 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006043 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6044 CE->getOperatorLoc());
6045 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006046 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006047 if (IneqCondIsCanonical)
6048 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6049 : CE->getArg(0),
6050 /*LessOp=*/llvm::None,
6051 /*StrictOp=*/true, CE->getSourceRange(),
6052 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006053 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006054 default:
6055 break;
6056 }
6057 }
6058 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006059 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006060 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006061 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006062 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006063 return true;
6064}
6065
Alexey Bataeve3727102018-04-18 15:57:46 +00006066bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006067 // RHS of canonical loop form increment can be:
6068 // var + incr
6069 // incr + var
6070 // var - incr
6071 //
6072 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006073 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006074 if (BO->isAdditiveOp()) {
6075 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006076 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6077 return setStep(BO->getRHS(), !IsAdd);
6078 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6079 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006080 }
David Majnemer9d168222016-08-05 17:44:54 +00006081 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006082 bool IsAdd = CE->getOperator() == OO_Plus;
6083 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006084 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6085 return setStep(CE->getArg(1), !IsAdd);
6086 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6087 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006088 }
6089 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006090 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006091 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006092 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006093 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006094 return true;
6095}
6096
Alexey Bataeve3727102018-04-18 15:57:46 +00006097bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006098 // Check incr-expr for canonical loop form and return true if it
6099 // does not conform.
6100 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6101 // ++var
6102 // var++
6103 // --var
6104 // var--
6105 // var += incr
6106 // var -= incr
6107 // var = var + incr
6108 // var = incr + var
6109 // var = var - incr
6110 //
6111 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006112 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006113 return true;
6114 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006115 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6116 if (!ExprTemp->cleanupsHaveSideEffects())
6117 S = ExprTemp->getSubExpr();
6118
Alexander Musmana5f070a2014-10-01 06:03:56 +00006119 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006120 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006121 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006122 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006123 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6124 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006125 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006126 (UO->isDecrementOp() ? -1 : 1))
6127 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006128 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006129 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006130 switch (BO->getOpcode()) {
6131 case BO_AddAssign:
6132 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006133 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6134 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006135 break;
6136 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006137 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6138 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006139 break;
6140 default:
6141 break;
6142 }
David Majnemer9d168222016-08-05 17:44:54 +00006143 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006144 switch (CE->getOperator()) {
6145 case OO_PlusPlus:
6146 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006147 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6148 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006149 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006150 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006151 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6152 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006153 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006154 break;
6155 case OO_PlusEqual:
6156 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006157 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6158 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006159 break;
6160 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006161 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6162 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006163 break;
6164 default:
6165 break;
6166 }
6167 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006168 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006169 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006170 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006171 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006172 return true;
6173}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006174
Alexey Bataev5a3af132016-03-29 08:58:54 +00006175static ExprResult
6176tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006177 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006178 if (SemaRef.CurContext->isDependentContext())
6179 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006180 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6181 return SemaRef.PerformImplicitConversion(
6182 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6183 /*AllowExplicit=*/true);
6184 auto I = Captures.find(Capture);
6185 if (I != Captures.end())
6186 return buildCapture(SemaRef, Capture, I->second);
6187 DeclRefExpr *Ref = nullptr;
6188 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6189 Captures[Capture] = Ref;
6190 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006191}
6192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006193/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006194Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006195 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006196 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006197 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006198 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006199 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006200 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006201 Expr *LBVal = LB;
6202 Expr *UBVal = UB;
6203 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6204 // max(LB(MinVal), LB(MaxVal))
6205 if (InitDependOnLC) {
6206 const LoopIterationSpace &IS =
6207 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6208 InitDependOnLC.getValueOr(
6209 CondDependOnLC.getValueOr(0))];
6210 if (!IS.MinValue || !IS.MaxValue)
6211 return nullptr;
6212 // OuterVar = Min
6213 ExprResult MinValue =
6214 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6215 if (!MinValue.isUsable())
6216 return nullptr;
6217
6218 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6219 IS.CounterVar, MinValue.get());
6220 if (!LBMinVal.isUsable())
6221 return nullptr;
6222 // OuterVar = Min, LBVal
6223 LBMinVal =
6224 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6225 if (!LBMinVal.isUsable())
6226 return nullptr;
6227 // (OuterVar = Min, LBVal)
6228 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6229 if (!LBMinVal.isUsable())
6230 return nullptr;
6231
6232 // OuterVar = Max
6233 ExprResult MaxValue =
6234 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6235 if (!MaxValue.isUsable())
6236 return nullptr;
6237
6238 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6239 IS.CounterVar, MaxValue.get());
6240 if (!LBMaxVal.isUsable())
6241 return nullptr;
6242 // OuterVar = Max, LBVal
6243 LBMaxVal =
6244 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6245 if (!LBMaxVal.isUsable())
6246 return nullptr;
6247 // (OuterVar = Max, LBVal)
6248 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6249 if (!LBMaxVal.isUsable())
6250 return nullptr;
6251
6252 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6253 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6254 if (!LBMin || !LBMax)
6255 return nullptr;
6256 // LB(MinVal) < LB(MaxVal)
6257 ExprResult MinLessMaxRes =
6258 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6259 if (!MinLessMaxRes.isUsable())
6260 return nullptr;
6261 Expr *MinLessMax =
6262 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6263 if (!MinLessMax)
6264 return nullptr;
6265 if (TestIsLessOp.getValue()) {
6266 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6267 // LB(MaxVal))
6268 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6269 MinLessMax, LBMin, LBMax);
6270 if (!MinLB.isUsable())
6271 return nullptr;
6272 LBVal = MinLB.get();
6273 } else {
6274 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6275 // LB(MaxVal))
6276 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6277 MinLessMax, LBMax, LBMin);
6278 if (!MaxLB.isUsable())
6279 return nullptr;
6280 LBVal = MaxLB.get();
6281 }
6282 }
6283 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6284 // min(UB(MinVal), UB(MaxVal))
6285 if (CondDependOnLC) {
6286 const LoopIterationSpace &IS =
6287 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6288 InitDependOnLC.getValueOr(
6289 CondDependOnLC.getValueOr(0))];
6290 if (!IS.MinValue || !IS.MaxValue)
6291 return nullptr;
6292 // OuterVar = Min
6293 ExprResult MinValue =
6294 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6295 if (!MinValue.isUsable())
6296 return nullptr;
6297
6298 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6299 IS.CounterVar, MinValue.get());
6300 if (!UBMinVal.isUsable())
6301 return nullptr;
6302 // OuterVar = Min, UBVal
6303 UBMinVal =
6304 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6305 if (!UBMinVal.isUsable())
6306 return nullptr;
6307 // (OuterVar = Min, UBVal)
6308 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6309 if (!UBMinVal.isUsable())
6310 return nullptr;
6311
6312 // OuterVar = Max
6313 ExprResult MaxValue =
6314 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6315 if (!MaxValue.isUsable())
6316 return nullptr;
6317
6318 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6319 IS.CounterVar, MaxValue.get());
6320 if (!UBMaxVal.isUsable())
6321 return nullptr;
6322 // OuterVar = Max, UBVal
6323 UBMaxVal =
6324 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6325 if (!UBMaxVal.isUsable())
6326 return nullptr;
6327 // (OuterVar = Max, UBVal)
6328 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6329 if (!UBMaxVal.isUsable())
6330 return nullptr;
6331
6332 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6333 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6334 if (!UBMin || !UBMax)
6335 return nullptr;
6336 // UB(MinVal) > UB(MaxVal)
6337 ExprResult MinGreaterMaxRes =
6338 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6339 if (!MinGreaterMaxRes.isUsable())
6340 return nullptr;
6341 Expr *MinGreaterMax =
6342 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6343 if (!MinGreaterMax)
6344 return nullptr;
6345 if (TestIsLessOp.getValue()) {
6346 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6347 // UB(MaxVal))
6348 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6349 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6350 if (!MaxUB.isUsable())
6351 return nullptr;
6352 UBVal = MaxUB.get();
6353 } else {
6354 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6355 // UB(MaxVal))
6356 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6357 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6358 if (!MinUB.isUsable())
6359 return nullptr;
6360 UBVal = MinUB.get();
6361 }
6362 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006363 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006364 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6365 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006366 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6367 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006368 if (!Upper || !Lower)
6369 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006370
6371 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6372
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006373 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006374 // BuildBinOp already emitted error, this one is to point user to upper
6375 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006376 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006377 << Upper->getSourceRange() << Lower->getSourceRange();
6378 return nullptr;
6379 }
6380 }
6381
6382 if (!Diff.isUsable())
6383 return nullptr;
6384
6385 // Upper - Lower [- 1]
6386 if (TestIsStrictOp)
6387 Diff = SemaRef.BuildBinOp(
6388 S, DefaultLoc, BO_Sub, Diff.get(),
6389 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6390 if (!Diff.isUsable())
6391 return nullptr;
6392
6393 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006394 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006395 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006396 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006397 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006398 if (!Diff.isUsable())
6399 return nullptr;
6400
6401 // Parentheses (for dumping/debugging purposes only).
6402 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6403 if (!Diff.isUsable())
6404 return nullptr;
6405
6406 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006407 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006408 if (!Diff.isUsable())
6409 return nullptr;
6410
Alexander Musman174b3ca2014-10-06 11:16:29 +00006411 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006412 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006413 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006414 bool UseVarType = VarType->hasIntegerRepresentation() &&
6415 C.getTypeSize(Type) > C.getTypeSize(VarType);
6416 if (!Type->isIntegerType() || UseVarType) {
6417 unsigned NewSize =
6418 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6419 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6420 : Type->hasSignedIntegerRepresentation();
6421 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006422 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6423 Diff = SemaRef.PerformImplicitConversion(
6424 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6425 if (!Diff.isUsable())
6426 return nullptr;
6427 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006428 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006429 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006430 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6431 if (NewSize != C.getTypeSize(Type)) {
6432 if (NewSize < C.getTypeSize(Type)) {
6433 assert(NewSize == 64 && "incorrect loop var size");
6434 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6435 << InitSrcRange << ConditionSrcRange;
6436 }
6437 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006438 NewSize, Type->hasSignedIntegerRepresentation() ||
6439 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006440 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6441 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6442 Sema::AA_Converting, true);
6443 if (!Diff.isUsable())
6444 return nullptr;
6445 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006446 }
6447 }
6448
Alexander Musmana5f070a2014-10-01 06:03:56 +00006449 return Diff.get();
6450}
6451
Alexey Bataevf8be4762019-08-14 19:30:06 +00006452std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6453 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6454 // Do not build for iterators, they cannot be used in non-rectangular loop
6455 // nests.
6456 if (LCDecl->getType()->isRecordType())
6457 return std::make_pair(nullptr, nullptr);
6458 // If we subtract, the min is in the condition, otherwise the min is in the
6459 // init value.
6460 Expr *MinExpr = nullptr;
6461 Expr *MaxExpr = nullptr;
6462 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6463 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6464 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6465 : CondDependOnLC.hasValue();
6466 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6467 : InitDependOnLC.hasValue();
6468 Expr *Lower =
6469 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6470 Expr *Upper =
6471 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6472 if (!Upper || !Lower)
6473 return std::make_pair(nullptr, nullptr);
6474
6475 if (TestIsLessOp.getValue())
6476 MinExpr = Lower;
6477 else
6478 MaxExpr = Upper;
6479
6480 // Build minimum/maximum value based on number of iterations.
6481 ExprResult Diff;
6482 QualType VarType = LCDecl->getType().getNonReferenceType();
6483
6484 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6485 if (!Diff.isUsable())
6486 return std::make_pair(nullptr, nullptr);
6487
6488 // Upper - Lower [- 1]
6489 if (TestIsStrictOp)
6490 Diff = SemaRef.BuildBinOp(
6491 S, DefaultLoc, BO_Sub, Diff.get(),
6492 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6493 if (!Diff.isUsable())
6494 return std::make_pair(nullptr, nullptr);
6495
6496 // Upper - Lower [- 1] + Step
6497 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6498 if (!NewStep.isUsable())
6499 return std::make_pair(nullptr, nullptr);
6500
6501 // Parentheses (for dumping/debugging purposes only).
6502 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6503 if (!Diff.isUsable())
6504 return std::make_pair(nullptr, nullptr);
6505
6506 // (Upper - Lower [- 1]) / Step
6507 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6508 if (!Diff.isUsable())
6509 return std::make_pair(nullptr, nullptr);
6510
6511 // ((Upper - Lower [- 1]) / Step) * Step
6512 // Parentheses (for dumping/debugging purposes only).
6513 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6514 if (!Diff.isUsable())
6515 return std::make_pair(nullptr, nullptr);
6516
6517 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6518 if (!Diff.isUsable())
6519 return std::make_pair(nullptr, nullptr);
6520
6521 // Convert to the original type or ptrdiff_t, if original type is pointer.
6522 if (!VarType->isAnyPointerType() &&
6523 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6524 Diff = SemaRef.PerformImplicitConversion(
6525 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6526 } else if (VarType->isAnyPointerType() &&
6527 !SemaRef.Context.hasSameType(
6528 Diff.get()->getType(),
6529 SemaRef.Context.getUnsignedPointerDiffType())) {
6530 Diff = SemaRef.PerformImplicitConversion(
6531 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6532 Sema::AA_Converting, /*AllowExplicit=*/true);
6533 }
6534 if (!Diff.isUsable())
6535 return std::make_pair(nullptr, nullptr);
6536
6537 // Parentheses (for dumping/debugging purposes only).
6538 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6539 if (!Diff.isUsable())
6540 return std::make_pair(nullptr, nullptr);
6541
6542 if (TestIsLessOp.getValue()) {
6543 // MinExpr = Lower;
6544 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6545 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6546 if (!Diff.isUsable())
6547 return std::make_pair(nullptr, nullptr);
6548 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6549 if (!Diff.isUsable())
6550 return std::make_pair(nullptr, nullptr);
6551 MaxExpr = Diff.get();
6552 } else {
6553 // MaxExpr = Upper;
6554 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6555 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6556 if (!Diff.isUsable())
6557 return std::make_pair(nullptr, nullptr);
6558 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6559 if (!Diff.isUsable())
6560 return std::make_pair(nullptr, nullptr);
6561 MinExpr = Diff.get();
6562 }
6563
6564 return std::make_pair(MinExpr, MaxExpr);
6565}
6566
6567Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6568 if (InitDependOnLC || CondDependOnLC)
6569 return Condition;
6570 return nullptr;
6571}
6572
Alexey Bataeve3727102018-04-18 15:57:46 +00006573Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006574 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006575 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006576 // Do not build a precondition when the condition/initialization is dependent
6577 // to prevent pessimistic early loop exit.
6578 // TODO: this can be improved by calculating min/max values but not sure that
6579 // it will be very effective.
6580 if (CondDependOnLC || InitDependOnLC)
6581 return SemaRef.PerformImplicitConversion(
6582 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6583 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6584 /*AllowExplicit=*/true).get();
6585
Alexey Bataev62dbb972015-04-22 11:59:37 +00006586 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006587 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006588
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006589 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6590 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006591 if (!NewLB.isUsable() || !NewUB.isUsable())
6592 return nullptr;
6593
Alexey Bataeve3727102018-04-18 15:57:46 +00006594 ExprResult CondExpr =
6595 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006596 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006597 (TestIsStrictOp ? BO_LT : BO_LE) :
6598 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006599 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006600 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006601 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6602 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006603 CondExpr = SemaRef.PerformImplicitConversion(
6604 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6605 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006606 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006607
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006608 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006609 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6610}
6611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006612/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006613DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006614 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6615 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006616 auto *VD = dyn_cast<VarDecl>(LCDecl);
6617 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006618 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6619 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006620 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006621 const DSAStackTy::DSAVarData Data =
6622 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006623 // If the loop control decl is explicitly marked as private, do not mark it
6624 // as captured again.
6625 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6626 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006627 return Ref;
6628 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006629 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006630}
6631
Alexey Bataeve3727102018-04-18 15:57:46 +00006632Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006633 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006634 QualType Type = LCDecl->getType().getNonReferenceType();
6635 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006636 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6637 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6638 isa<VarDecl>(LCDecl)
6639 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6640 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006641 if (PrivateVar->isInvalidDecl())
6642 return nullptr;
6643 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6644 }
6645 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006646}
6647
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006648/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006649Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006650
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006651/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006652Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006653
Alexey Bataevf138fda2018-08-13 19:04:24 +00006654Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6655 Scope *S, Expr *Counter,
6656 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6657 Expr *Inc, OverloadedOperatorKind OOK) {
6658 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6659 if (!Cnt)
6660 return nullptr;
6661 if (Inc) {
6662 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6663 "Expected only + or - operations for depend clauses.");
6664 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6665 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6666 if (!Cnt)
6667 return nullptr;
6668 }
6669 ExprResult Diff;
6670 QualType VarType = LCDecl->getType().getNonReferenceType();
6671 if (VarType->isIntegerType() || VarType->isPointerType() ||
6672 SemaRef.getLangOpts().CPlusPlus) {
6673 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006674 Expr *Upper = TestIsLessOp.getValue()
6675 ? Cnt
6676 : tryBuildCapture(SemaRef, UB, Captures).get();
6677 Expr *Lower = TestIsLessOp.getValue()
6678 ? tryBuildCapture(SemaRef, LB, Captures).get()
6679 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006680 if (!Upper || !Lower)
6681 return nullptr;
6682
6683 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6684
6685 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6686 // BuildBinOp already emitted error, this one is to point user to upper
6687 // and lower bound, and to tell what is passed to 'operator-'.
6688 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6689 << Upper->getSourceRange() << Lower->getSourceRange();
6690 return nullptr;
6691 }
6692 }
6693
6694 if (!Diff.isUsable())
6695 return nullptr;
6696
6697 // Parentheses (for dumping/debugging purposes only).
6698 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6699 if (!Diff.isUsable())
6700 return nullptr;
6701
6702 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6703 if (!NewStep.isUsable())
6704 return nullptr;
6705 // (Upper - Lower) / Step
6706 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6707 if (!Diff.isUsable())
6708 return nullptr;
6709
6710 return Diff.get();
6711}
Alexey Bataev23b69422014-06-18 07:08:49 +00006712} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006713
Alexey Bataev9c821032015-04-30 04:23:23 +00006714void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6715 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6716 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006717 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6718 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006719 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006720 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006721 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006722 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6723 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006724 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006725 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006726 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006727 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006728 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006729 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006730 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6731 /*WithInit=*/false);
6732 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006733 }
6734 }
6735 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006736 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6737 if (LD != D->getCanonicalDecl()) {
6738 DSAStack->resetPossibleLoopCounter();
6739 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6740 MarkDeclarationsReferencedInExpr(
6741 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6742 Var->getType().getNonLValueExprType(Context),
6743 ForLoc, /*RefersToCapture=*/true));
6744 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006745 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6746 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6747 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6748 // associated for-loop of a simd construct with just one associated
6749 // for-loop may be listed in a linear clause with a constant-linear-step
6750 // that is the increment of the associated for-loop. The loop iteration
6751 // variable(s) in the associated for-loop(s) of a for or parallel for
6752 // construct may be listed in a private or lastprivate clause.
6753 DSAStackTy::DSAVarData DVar =
6754 DSAStack->getTopDSA(D, /*FromParent=*/false);
6755 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6756 // is declared in the loop and it is predetermined as a private.
6757 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6758 OpenMPClauseKind PredeterminedCKind =
6759 isOpenMPSimdDirective(DKind)
6760 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6761 : OMPC_private;
6762 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6763 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6764 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6765 DVar.CKind != OMPC_private))) ||
6766 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006767 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006768 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006769 isOpenMPDistributeDirective(DKind)) &&
6770 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6771 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6772 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6773 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6774 << getOpenMPClauseName(DVar.CKind)
6775 << getOpenMPDirectiveName(DKind)
6776 << getOpenMPClauseName(PredeterminedCKind);
6777 if (DVar.RefExpr == nullptr)
6778 DVar.CKind = PredeterminedCKind;
6779 reportOriginalDsa(*this, DSAStack, D, DVar,
6780 /*IsLoopIterVar=*/true);
6781 } else if (LoopDeclRefExpr) {
6782 // Make the loop iteration variable private (for worksharing
6783 // constructs), linear (for simd directives with the only one
6784 // associated loop) or lastprivate (for simd directives with several
6785 // collapsed or ordered loops).
6786 if (DVar.CKind == OMPC_unknown)
6787 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6788 PrivateRef);
6789 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006790 }
6791 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006792 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006793 }
6794}
6795
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006796/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006797/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006798static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006799 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6800 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006801 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6802 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006803 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006804 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006805 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006806 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006807 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006808 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006809 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006810 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6811 // Ranged for is supported only in OpenMP 5.0.
6812 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006813 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006814 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006815 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006816 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006817 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006818 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6819 SemaRef.Diag(DSA.getConstructLoc(),
6820 diag::note_omp_collapse_ordered_expr)
6821 << 2 << CollapseLoopCountExpr->getSourceRange()
6822 << OrderedLoopCountExpr->getSourceRange();
6823 else if (CollapseLoopCountExpr)
6824 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6825 diag::note_omp_collapse_ordered_expr)
6826 << 0 << CollapseLoopCountExpr->getSourceRange();
6827 else
6828 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6829 diag::note_omp_collapse_ordered_expr)
6830 << 1 << OrderedLoopCountExpr->getSourceRange();
6831 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006832 return true;
6833 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006834 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6835 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006836
Alexey Bataevbef93a92019-10-07 18:54:57 +00006837 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6838 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006839
6840 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006841 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00006842 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006843 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006844
6845 bool HasErrors = false;
6846
6847 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006848 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006849 // OpenMP [2.6, Canonical Loop Form]
6850 // Var is one of the following:
6851 // A variable of signed or unsigned integer type.
6852 // For C++, a variable of a random access iterator type.
6853 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006854 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006855 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6856 !VarType->isPointerType() &&
6857 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006858 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006859 << SemaRef.getLangOpts().CPlusPlus;
6860 HasErrors = true;
6861 }
6862
6863 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6864 // a Construct
6865 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6866 // parallel for construct is (are) private.
6867 // The loop iteration variable in the associated for-loop of a simd
6868 // construct with just one associated for-loop is linear with a
6869 // constant-linear-step that is the increment of the associated for-loop.
6870 // Exclude loop var from the list of variables with implicitly defined data
6871 // sharing attributes.
6872 VarsWithImplicitDSA.erase(LCDecl);
6873
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006874 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
6875
6876 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006877 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006878
6879 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006880 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006881 }
6882
Alexey Bataeve3727102018-04-18 15:57:46 +00006883 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006884 return HasErrors;
6885
Alexander Musmana5f070a2014-10-01 06:03:56 +00006886 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006887 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
6888 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00006889 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6890 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6891 (isOpenMPWorksharingDirective(DKind) ||
6892 isOpenMPTaskLoopDirective(DKind) ||
6893 isOpenMPDistributeDirective(DKind)),
6894 Captures);
6895 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6896 ISC.buildCounterVar(Captures, DSA);
6897 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6898 ISC.buildPrivateCounterVar();
6899 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6900 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6901 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6902 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6903 ISC.getConditionSrcRange();
6904 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6905 ISC.getIncrementSrcRange();
6906 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6907 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6908 ISC.isStrictTestOp();
6909 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6910 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6911 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6912 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6913 ISC.buildFinalCondition(DSA.getCurScope());
6914 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6915 ISC.doesInitDependOnLC();
6916 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6917 ISC.doesCondDependOnLC();
6918 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6919 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006920
Alexey Bataevf8be4762019-08-14 19:30:06 +00006921 HasErrors |=
6922 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6923 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6924 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6925 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6926 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6927 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006928 if (!HasErrors && DSA.isOrderedRegion()) {
6929 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
6930 if (CurrentNestedLoopCount <
6931 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
6932 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006933 CurrentNestedLoopCount,
6934 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006935 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006936 CurrentNestedLoopCount,
6937 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006938 }
6939 }
6940 for (auto &Pair : DSA.getDoacrossDependClauses()) {
6941 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
6942 // Erroneous case - clause has some problems.
6943 continue;
6944 }
6945 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
6946 Pair.second.size() <= CurrentNestedLoopCount) {
6947 // Erroneous case - clause has some problems.
6948 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
6949 continue;
6950 }
6951 Expr *CntValue;
6952 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
6953 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006954 DSA.getCurScope(),
6955 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006956 Pair.first->getDependencyLoc());
6957 else
6958 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006959 DSA.getCurScope(),
6960 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006961 Pair.first->getDependencyLoc(),
6962 Pair.second[CurrentNestedLoopCount].first,
6963 Pair.second[CurrentNestedLoopCount].second);
6964 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
6965 }
6966 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006967
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006968 return HasErrors;
6969}
6970
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006971/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00006972static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00006973buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006974 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006975 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006976 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006977 ExprResult NewStart = IsNonRectangularLB
6978 ? Start.get()
6979 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006980 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006981 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00006982 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00006983 VarRef.get()->getType())) {
6984 NewStart = SemaRef.PerformImplicitConversion(
6985 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
6986 /*AllowExplicit=*/true);
6987 if (!NewStart.isUsable())
6988 return ExprError();
6989 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006990
Alexey Bataeve3727102018-04-18 15:57:46 +00006991 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006992 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6993 return Init;
6994}
6995
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006996/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00006997static ExprResult buildCounterUpdate(
6998 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6999 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007000 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007001 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007002 // Add parentheses (for debugging purposes only).
7003 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7004 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7005 !Step.isUsable())
7006 return ExprError();
7007
Alexey Bataev5a3af132016-03-29 08:58:54 +00007008 ExprResult NewStep = Step;
7009 if (Captures)
7010 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007011 if (NewStep.isInvalid())
7012 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007013 ExprResult Update =
7014 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007015 if (!Update.isUsable())
7016 return ExprError();
7017
Alexey Bataevc0214e02016-02-16 12:13:49 +00007018 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7019 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007020 if (!Start.isUsable())
7021 return ExprError();
7022 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7023 if (!NewStart.isUsable())
7024 return ExprError();
7025 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007026 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007027 if (NewStart.isInvalid())
7028 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007029
Alexey Bataevc0214e02016-02-16 12:13:49 +00007030 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7031 ExprResult SavedUpdate = Update;
7032 ExprResult UpdateVal;
7033 if (VarRef.get()->getType()->isOverloadableType() ||
7034 NewStart.get()->getType()->isOverloadableType() ||
7035 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007036 Sema::TentativeAnalysisScope Trap(SemaRef);
7037
Alexey Bataevc0214e02016-02-16 12:13:49 +00007038 Update =
7039 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7040 if (Update.isUsable()) {
7041 UpdateVal =
7042 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7043 VarRef.get(), SavedUpdate.get());
7044 if (UpdateVal.isUsable()) {
7045 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7046 UpdateVal.get());
7047 }
7048 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007049 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007050
Alexey Bataevc0214e02016-02-16 12:13:49 +00007051 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7052 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7053 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7054 NewStart.get(), SavedUpdate.get());
7055 if (!Update.isUsable())
7056 return ExprError();
7057
Alexey Bataev11481f52016-02-17 10:29:05 +00007058 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7059 VarRef.get()->getType())) {
7060 Update = SemaRef.PerformImplicitConversion(
7061 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7062 if (!Update.isUsable())
7063 return ExprError();
7064 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007065
7066 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7067 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007068 return Update;
7069}
7070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007071/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007072/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007073static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007074 if (E == nullptr)
7075 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007076 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007077 QualType OldType = E->getType();
7078 unsigned HasBits = C.getTypeSize(OldType);
7079 if (HasBits >= Bits)
7080 return ExprResult(E);
7081 // OK to convert to signed, because new type has more bits than old.
7082 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7083 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7084 true);
7085}
7086
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007087/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007088/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007089static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007090 if (E == nullptr)
7091 return false;
7092 llvm::APSInt Result;
7093 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7094 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7095 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007096}
7097
Alexey Bataev5a3af132016-03-29 08:58:54 +00007098/// Build preinits statement for the given declarations.
7099static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007100 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007101 if (!PreInits.empty()) {
7102 return new (Context) DeclStmt(
7103 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7104 SourceLocation(), SourceLocation());
7105 }
7106 return nullptr;
7107}
7108
7109/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007110static Stmt *
7111buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007112 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007113 if (!Captures.empty()) {
7114 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007115 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007116 PreInits.push_back(Pair.second->getDecl());
7117 return buildPreInits(Context, PreInits);
7118 }
7119 return nullptr;
7120}
7121
7122/// Build postupdate expression for the given list of postupdates expressions.
7123static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7124 Expr *PostUpdate = nullptr;
7125 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007126 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007127 Expr *ConvE = S.BuildCStyleCastExpr(
7128 E->getExprLoc(),
7129 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7130 E->getExprLoc(), E)
7131 .get();
7132 PostUpdate = PostUpdate
7133 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7134 PostUpdate, ConvE)
7135 .get()
7136 : ConvE;
7137 }
7138 }
7139 return PostUpdate;
7140}
7141
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007142/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007143/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7144/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007145static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007146checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007147 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7148 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007149 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007150 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007151 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007152 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007153 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007154 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007155 if (!CollapseLoopCountExpr->isValueDependent() &&
7156 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007157 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007158 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007159 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007160 return 1;
7161 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007162 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007163 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007164 if (OrderedLoopCountExpr) {
7165 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007166 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007167 if (!OrderedLoopCountExpr->isValueDependent() &&
7168 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7169 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007170 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007171 if (Result.getLimitedValue() < NestedLoopCount) {
7172 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7173 diag::err_omp_wrong_ordered_loop_count)
7174 << OrderedLoopCountExpr->getSourceRange();
7175 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7176 diag::note_collapse_loop_count)
7177 << CollapseLoopCountExpr->getSourceRange();
7178 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007179 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007180 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007181 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007182 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007183 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007184 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007185 // This is helper routine for loop directives (e.g., 'for', 'simd',
7186 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007187 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007188 SmallVector<LoopIterationSpace, 4> IterSpaces(
7189 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007190 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007191 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007192 if (checkOpenMPIterationSpace(
7193 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7194 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007195 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007196 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007197 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007198 // OpenMP [2.8.1, simd construct, Restrictions]
7199 // All loops associated with the construct must be perfectly nested; that
7200 // is, there must be no intervening code nor any OpenMP directive between
7201 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007202 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7203 CurStmt = For->getBody();
7204 } else {
7205 assert(isa<CXXForRangeStmt>(CurStmt) &&
7206 "Expected canonical for or range-based for loops.");
7207 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7208 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007209 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7210 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007211 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007212 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7213 if (checkOpenMPIterationSpace(
7214 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7215 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007216 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007217 return 0;
7218 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7219 // Handle initialization of captured loop iterator variables.
7220 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7221 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7222 Captures[DRE] = DRE;
7223 }
7224 }
7225 // Move on to the next nested for loop, or to the loop body.
7226 // OpenMP [2.8.1, simd construct, Restrictions]
7227 // All loops associated with the construct must be perfectly nested; that
7228 // is, there must be no intervening code nor any OpenMP directive between
7229 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007230 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7231 CurStmt = For->getBody();
7232 } else {
7233 assert(isa<CXXForRangeStmt>(CurStmt) &&
7234 "Expected canonical for or range-based for loops.");
7235 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7236 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007237 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7238 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007239 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007240
Alexander Musmana5f070a2014-10-01 06:03:56 +00007241 Built.clear(/* size */ NestedLoopCount);
7242
7243 if (SemaRef.CurContext->isDependentContext())
7244 return NestedLoopCount;
7245
7246 // An example of what is generated for the following code:
7247 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007248 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007249 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007250 // for (k = 0; k < NK; ++k)
7251 // for (j = J0; j < NJ; j+=2) {
7252 // <loop body>
7253 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007254 //
7255 // We generate the code below.
7256 // Note: the loop body may be outlined in CodeGen.
7257 // Note: some counters may be C++ classes, operator- is used to find number of
7258 // iterations and operator+= to calculate counter value.
7259 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7260 // or i64 is currently supported).
7261 //
7262 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7263 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7264 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7265 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7266 // // similar updates for vars in clauses (e.g. 'linear')
7267 // <loop body (using local i and j)>
7268 // }
7269 // i = NI; // assign final values of counters
7270 // j = NJ;
7271 //
7272
7273 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7274 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007275 // Precondition tests if there is at least one iteration (all conditions are
7276 // true).
7277 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007278 Expr *N0 = IterSpaces[0].NumIterations;
7279 ExprResult LastIteration32 =
7280 widenIterationCount(/*Bits=*/32,
7281 SemaRef
7282 .PerformImplicitConversion(
7283 N0->IgnoreImpCasts(), N0->getType(),
7284 Sema::AA_Converting, /*AllowExplicit=*/true)
7285 .get(),
7286 SemaRef);
7287 ExprResult LastIteration64 = widenIterationCount(
7288 /*Bits=*/64,
7289 SemaRef
7290 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7291 Sema::AA_Converting,
7292 /*AllowExplicit=*/true)
7293 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007294 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007295
7296 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7297 return NestedLoopCount;
7298
Alexey Bataeve3727102018-04-18 15:57:46 +00007299 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007300 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7301
7302 Scope *CurScope = DSA.getCurScope();
7303 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007304 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007305 PreCond =
7306 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7307 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007308 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007309 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007310 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007311 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7312 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007313 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007314 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007315 SemaRef
7316 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7317 Sema::AA_Converting,
7318 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007319 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007320 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007321 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007322 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007323 SemaRef
7324 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7325 Sema::AA_Converting,
7326 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007327 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007328 }
7329
7330 // Choose either the 32-bit or 64-bit version.
7331 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007332 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7333 (LastIteration32.isUsable() &&
7334 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7335 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7336 fitsInto(
7337 /*Bits=*/32,
7338 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7339 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007340 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007341 QualType VType = LastIteration.get()->getType();
7342 QualType RealVType = VType;
7343 QualType StrideVType = VType;
7344 if (isOpenMPTaskLoopDirective(DKind)) {
7345 VType =
7346 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7347 StrideVType =
7348 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7349 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007350
7351 if (!LastIteration.isUsable())
7352 return 0;
7353
7354 // Save the number of iterations.
7355 ExprResult NumIterations = LastIteration;
7356 {
7357 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007358 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7359 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007360 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7361 if (!LastIteration.isUsable())
7362 return 0;
7363 }
7364
7365 // Calculate the last iteration number beforehand instead of doing this on
7366 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7367 llvm::APSInt Result;
7368 bool IsConstant =
7369 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7370 ExprResult CalcLastIteration;
7371 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007372 ExprResult SaveRef =
7373 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007374 LastIteration = SaveRef;
7375
7376 // Prepare SaveRef + 1.
7377 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007378 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007379 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7380 if (!NumIterations.isUsable())
7381 return 0;
7382 }
7383
7384 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7385
David Majnemer9d168222016-08-05 17:44:54 +00007386 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007387 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007388 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7389 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007390 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007391 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7392 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007393 SemaRef.AddInitializerToDecl(LBDecl,
7394 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7395 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007396
7397 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007398 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7399 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007400 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007401 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007402
7403 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7404 // This will be used to implement clause 'lastprivate'.
7405 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007406 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7407 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007408 SemaRef.AddInitializerToDecl(ILDecl,
7409 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7410 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007411
7412 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007413 VarDecl *STDecl =
7414 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7415 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007416 SemaRef.AddInitializerToDecl(STDecl,
7417 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7418 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007419
7420 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007421 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007422 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7423 UB.get(), LastIteration.get());
7424 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007425 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7426 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007427 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7428 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007429 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007430
7431 // If we have a combined directive that combines 'distribute', 'for' or
7432 // 'simd' we need to be able to access the bounds of the schedule of the
7433 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7434 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7435 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007436 // Lower bound variable, initialized with zero.
7437 VarDecl *CombLBDecl =
7438 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7439 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7440 SemaRef.AddInitializerToDecl(
7441 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7442 /*DirectInit*/ false);
7443
7444 // Upper bound variable, initialized with last iteration number.
7445 VarDecl *CombUBDecl =
7446 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7447 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7448 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7449 /*DirectInit*/ false);
7450
7451 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7452 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7453 ExprResult CombCondOp =
7454 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7455 LastIteration.get(), CombUB.get());
7456 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7457 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007458 CombEUB =
7459 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007460
Alexey Bataeve3727102018-04-18 15:57:46 +00007461 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007462 // We expect to have at least 2 more parameters than the 'parallel'
7463 // directive does - the lower and upper bounds of the previous schedule.
7464 assert(CD->getNumParams() >= 4 &&
7465 "Unexpected number of parameters in loop combined directive");
7466
7467 // Set the proper type for the bounds given what we learned from the
7468 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007469 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7470 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007471
7472 // Previous lower and upper bounds are obtained from the region
7473 // parameters.
7474 PrevLB =
7475 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7476 PrevUB =
7477 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7478 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007479 }
7480
7481 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007482 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007483 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007484 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007485 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7486 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007487 Expr *RHS =
7488 (isOpenMPWorksharingDirective(DKind) ||
7489 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7490 ? LB.get()
7491 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007492 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007493 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007494
7495 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7496 Expr *CombRHS =
7497 (isOpenMPWorksharingDirective(DKind) ||
7498 isOpenMPTaskLoopDirective(DKind) ||
7499 isOpenMPDistributeDirective(DKind))
7500 ? CombLB.get()
7501 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7502 CombInit =
7503 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007504 CombInit =
7505 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007506 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007507 }
7508
Alexey Bataev316ccf62019-01-29 18:51:58 +00007509 bool UseStrictCompare =
7510 RealVType->hasUnsignedIntegerRepresentation() &&
7511 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7512 return LIS.IsStrictCompare;
7513 });
7514 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7515 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007516 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007517 Expr *BoundUB = UB.get();
7518 if (UseStrictCompare) {
7519 BoundUB =
7520 SemaRef
7521 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7522 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7523 .get();
7524 BoundUB =
7525 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7526 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007527 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007528 (isOpenMPWorksharingDirective(DKind) ||
7529 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007530 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7531 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7532 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007533 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7534 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007535 ExprResult CombDistCond;
7536 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007537 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7538 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007539 }
7540
Carlo Bertolliffafe102017-04-20 00:39:39 +00007541 ExprResult CombCond;
7542 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007543 Expr *BoundCombUB = CombUB.get();
7544 if (UseStrictCompare) {
7545 BoundCombUB =
7546 SemaRef
7547 .BuildBinOp(
7548 CurScope, CondLoc, BO_Add, BoundCombUB,
7549 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7550 .get();
7551 BoundCombUB =
7552 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7553 .get();
7554 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007555 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007556 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7557 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007558 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007559 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007560 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007561 ExprResult Inc =
7562 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7563 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7564 if (!Inc.isUsable())
7565 return 0;
7566 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007567 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007568 if (!Inc.isUsable())
7569 return 0;
7570
7571 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7572 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007573 // In combined construct, add combined version that use CombLB and CombUB
7574 // base variables for the update
7575 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007576 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7577 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007578 // LB + ST
7579 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7580 if (!NextLB.isUsable())
7581 return 0;
7582 // LB = LB + ST
7583 NextLB =
7584 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007585 NextLB =
7586 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007587 if (!NextLB.isUsable())
7588 return 0;
7589 // UB + ST
7590 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7591 if (!NextUB.isUsable())
7592 return 0;
7593 // UB = UB + ST
7594 NextUB =
7595 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007596 NextUB =
7597 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007598 if (!NextUB.isUsable())
7599 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007600 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7601 CombNextLB =
7602 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7603 if (!NextLB.isUsable())
7604 return 0;
7605 // LB = LB + ST
7606 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7607 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007608 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7609 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007610 if (!CombNextLB.isUsable())
7611 return 0;
7612 // UB + ST
7613 CombNextUB =
7614 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7615 if (!CombNextUB.isUsable())
7616 return 0;
7617 // UB = UB + ST
7618 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7619 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007620 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7621 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007622 if (!CombNextUB.isUsable())
7623 return 0;
7624 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007625 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007626
Carlo Bertolliffafe102017-04-20 00:39:39 +00007627 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007628 // directive with for as IV = IV + ST; ensure upper bound expression based
7629 // on PrevUB instead of NumIterations - used to implement 'for' when found
7630 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007631 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007632 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007633 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007634 DistCond = SemaRef.BuildBinOp(
7635 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007636 assert(DistCond.isUsable() && "distribute cond expr was not built");
7637
7638 DistInc =
7639 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7640 assert(DistInc.isUsable() && "distribute inc expr was not built");
7641 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7642 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007643 DistInc =
7644 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007645 assert(DistInc.isUsable() && "distribute inc expr was not built");
7646
7647 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7648 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007649 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007650 ExprResult IsUBGreater =
7651 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7652 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7653 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7654 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7655 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007656 PrevEUB =
7657 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007658
Alexey Bataev316ccf62019-01-29 18:51:58 +00007659 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7660 // parallel for is in combination with a distribute directive with
7661 // schedule(static, 1)
7662 Expr *BoundPrevUB = PrevUB.get();
7663 if (UseStrictCompare) {
7664 BoundPrevUB =
7665 SemaRef
7666 .BuildBinOp(
7667 CurScope, CondLoc, BO_Add, BoundPrevUB,
7668 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7669 .get();
7670 BoundPrevUB =
7671 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7672 .get();
7673 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007674 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007675 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7676 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007677 }
7678
Alexander Musmana5f070a2014-10-01 06:03:56 +00007679 // Build updates and final values of the loop counters.
7680 bool HasErrors = false;
7681 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007682 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007683 Built.Updates.resize(NestedLoopCount);
7684 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007685 Built.DependentCounters.resize(NestedLoopCount);
7686 Built.DependentInits.resize(NestedLoopCount);
7687 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007688 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007689 // We implement the following algorithm for obtaining the
7690 // original loop iteration variable values based on the
7691 // value of the collapsed loop iteration variable IV.
7692 //
7693 // Let n+1 be the number of collapsed loops in the nest.
7694 // Iteration variables (I0, I1, .... In)
7695 // Iteration counts (N0, N1, ... Nn)
7696 //
7697 // Acc = IV;
7698 //
7699 // To compute Ik for loop k, 0 <= k <= n, generate:
7700 // Prod = N(k+1) * N(k+2) * ... * Nn;
7701 // Ik = Acc / Prod;
7702 // Acc -= Ik * Prod;
7703 //
7704 ExprResult Acc = IV;
7705 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007706 LoopIterationSpace &IS = IterSpaces[Cnt];
7707 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007708 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007709
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007710 // Compute prod
7711 ExprResult Prod =
7712 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7713 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7714 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7715 IterSpaces[K].NumIterations);
7716
7717 // Iter = Acc / Prod
7718 // If there is at least one more inner loop to avoid
7719 // multiplication by 1.
7720 if (Cnt + 1 < NestedLoopCount)
7721 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7722 Acc.get(), Prod.get());
7723 else
7724 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007725 if (!Iter.isUsable()) {
7726 HasErrors = true;
7727 break;
7728 }
7729
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007730 // Update Acc:
7731 // Acc -= Iter * Prod
7732 // Check if there is at least one more inner loop to avoid
7733 // multiplication by 1.
7734 if (Cnt + 1 < NestedLoopCount)
7735 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7736 Iter.get(), Prod.get());
7737 else
7738 Prod = Iter;
7739 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7740 Acc.get(), Prod.get());
7741
Alexey Bataev39f915b82015-05-08 10:41:21 +00007742 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007743 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007744 DeclRefExpr *CounterVar = buildDeclRefExpr(
7745 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7746 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007747 ExprResult Init =
7748 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7749 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007750 if (!Init.isUsable()) {
7751 HasErrors = true;
7752 break;
7753 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007754 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007755 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007756 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007757 if (!Update.isUsable()) {
7758 HasErrors = true;
7759 break;
7760 }
7761
7762 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007763 ExprResult Final =
7764 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7765 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7766 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007767 if (!Final.isUsable()) {
7768 HasErrors = true;
7769 break;
7770 }
7771
Alexander Musmana5f070a2014-10-01 06:03:56 +00007772 if (!Update.isUsable() || !Final.isUsable()) {
7773 HasErrors = true;
7774 break;
7775 }
7776 // Save results
7777 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007778 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007779 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007780 Built.Updates[Cnt] = Update.get();
7781 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007782 Built.DependentCounters[Cnt] = nullptr;
7783 Built.DependentInits[Cnt] = nullptr;
7784 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007785 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007786 Built.DependentCounters[Cnt] =
7787 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7788 Built.DependentInits[Cnt] =
7789 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7790 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7791 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007792 }
7793 }
7794
7795 if (HasErrors)
7796 return 0;
7797
7798 // Save results
7799 Built.IterationVarRef = IV.get();
7800 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007801 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007802 Built.CalcLastIteration = SemaRef
7803 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007804 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007805 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007806 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007807 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007808 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007809 Built.Init = Init.get();
7810 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007811 Built.LB = LB.get();
7812 Built.UB = UB.get();
7813 Built.IL = IL.get();
7814 Built.ST = ST.get();
7815 Built.EUB = EUB.get();
7816 Built.NLB = NextLB.get();
7817 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007818 Built.PrevLB = PrevLB.get();
7819 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007820 Built.DistInc = DistInc.get();
7821 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007822 Built.DistCombinedFields.LB = CombLB.get();
7823 Built.DistCombinedFields.UB = CombUB.get();
7824 Built.DistCombinedFields.EUB = CombEUB.get();
7825 Built.DistCombinedFields.Init = CombInit.get();
7826 Built.DistCombinedFields.Cond = CombCond.get();
7827 Built.DistCombinedFields.NLB = CombNextLB.get();
7828 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007829 Built.DistCombinedFields.DistCond = CombDistCond.get();
7830 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007831
Alexey Bataevabfc0692014-06-25 06:52:00 +00007832 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007833}
7834
Alexey Bataev10e775f2015-07-30 11:36:16 +00007835static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007836 auto CollapseClauses =
7837 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7838 if (CollapseClauses.begin() != CollapseClauses.end())
7839 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007840 return nullptr;
7841}
7842
Alexey Bataev10e775f2015-07-30 11:36:16 +00007843static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007844 auto OrderedClauses =
7845 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7846 if (OrderedClauses.begin() != OrderedClauses.end())
7847 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007848 return nullptr;
7849}
7850
Kelvin Lic5609492016-07-15 04:39:07 +00007851static bool checkSimdlenSafelenSpecified(Sema &S,
7852 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007853 const OMPSafelenClause *Safelen = nullptr;
7854 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007855
Alexey Bataeve3727102018-04-18 15:57:46 +00007856 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007857 if (Clause->getClauseKind() == OMPC_safelen)
7858 Safelen = cast<OMPSafelenClause>(Clause);
7859 else if (Clause->getClauseKind() == OMPC_simdlen)
7860 Simdlen = cast<OMPSimdlenClause>(Clause);
7861 if (Safelen && Simdlen)
7862 break;
7863 }
7864
7865 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007866 const Expr *SimdlenLength = Simdlen->getSimdlen();
7867 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007868 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7869 SimdlenLength->isInstantiationDependent() ||
7870 SimdlenLength->containsUnexpandedParameterPack())
7871 return false;
7872 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7873 SafelenLength->isInstantiationDependent() ||
7874 SafelenLength->containsUnexpandedParameterPack())
7875 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007876 Expr::EvalResult SimdlenResult, SafelenResult;
7877 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7878 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7879 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7880 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00007881 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7882 // If both simdlen and safelen clauses are specified, the value of the
7883 // simdlen parameter must be less than or equal to the value of the safelen
7884 // parameter.
7885 if (SimdlenRes > SafelenRes) {
7886 S.Diag(SimdlenLength->getExprLoc(),
7887 diag::err_omp_wrong_simdlen_safelen_values)
7888 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7889 return true;
7890 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00007891 }
7892 return false;
7893}
7894
Alexey Bataeve3727102018-04-18 15:57:46 +00007895StmtResult
7896Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7897 SourceLocation StartLoc, SourceLocation EndLoc,
7898 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007899 if (!AStmt)
7900 return StmtError();
7901
7902 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007903 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007904 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7905 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007906 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007907 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7908 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007909 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007910 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007911
Alexander Musmana5f070a2014-10-01 06:03:56 +00007912 assert((CurContext->isDependentContext() || B.builtAll()) &&
7913 "omp simd loop exprs were not built");
7914
Alexander Musman3276a272015-03-21 10:12:56 +00007915 if (!CurContext->isDependentContext()) {
7916 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007917 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007918 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00007919 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007920 B.NumIterations, *this, CurScope,
7921 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00007922 return StmtError();
7923 }
7924 }
7925
Kelvin Lic5609492016-07-15 04:39:07 +00007926 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007927 return StmtError();
7928
Reid Kleckner87a31802018-03-12 21:43:02 +00007929 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007930 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7931 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007932}
7933
Alexey Bataeve3727102018-04-18 15:57:46 +00007934StmtResult
7935Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7936 SourceLocation StartLoc, SourceLocation EndLoc,
7937 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007938 if (!AStmt)
7939 return StmtError();
7940
7941 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007942 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007943 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7944 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007945 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007946 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7947 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007948 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00007949 return StmtError();
7950
Alexander Musmana5f070a2014-10-01 06:03:56 +00007951 assert((CurContext->isDependentContext() || B.builtAll()) &&
7952 "omp for loop exprs were not built");
7953
Alexey Bataev54acd402015-08-04 11:18:19 +00007954 if (!CurContext->isDependentContext()) {
7955 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007956 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007957 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007958 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007959 B.NumIterations, *this, CurScope,
7960 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007961 return StmtError();
7962 }
7963 }
7964
Reid Kleckner87a31802018-03-12 21:43:02 +00007965 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007966 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007967 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00007968}
7969
Alexander Musmanf82886e2014-09-18 05:12:34 +00007970StmtResult Sema::ActOnOpenMPForSimdDirective(
7971 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007972 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007973 if (!AStmt)
7974 return StmtError();
7975
7976 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007977 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007978 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7979 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00007980 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007981 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007982 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7983 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007984 if (NestedLoopCount == 0)
7985 return StmtError();
7986
Alexander Musmanc6388682014-12-15 07:07:06 +00007987 assert((CurContext->isDependentContext() || B.builtAll()) &&
7988 "omp for simd loop exprs were not built");
7989
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007990 if (!CurContext->isDependentContext()) {
7991 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007992 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007993 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007994 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007995 B.NumIterations, *this, CurScope,
7996 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007997 return StmtError();
7998 }
7999 }
8000
Kelvin Lic5609492016-07-15 04:39:07 +00008001 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008002 return StmtError();
8003
Reid Kleckner87a31802018-03-12 21:43:02 +00008004 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008005 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8006 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008007}
8008
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008009StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8010 Stmt *AStmt,
8011 SourceLocation StartLoc,
8012 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008013 if (!AStmt)
8014 return StmtError();
8015
8016 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008017 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008018 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008019 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008020 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008021 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008022 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008023 return StmtError();
8024 // All associated statements must be '#pragma omp section' except for
8025 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008026 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008027 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8028 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008029 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008030 diag::err_omp_sections_substmt_not_section);
8031 return StmtError();
8032 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008033 cast<OMPSectionDirective>(SectionStmt)
8034 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008035 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008036 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008037 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008038 return StmtError();
8039 }
8040
Reid Kleckner87a31802018-03-12 21:43:02 +00008041 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008042
Alexey Bataev25e5b442015-09-15 12:52:43 +00008043 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8044 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008045}
8046
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008047StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8048 SourceLocation StartLoc,
8049 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008050 if (!AStmt)
8051 return StmtError();
8052
8053 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008054
Reid Kleckner87a31802018-03-12 21:43:02 +00008055 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008056 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008057
Alexey Bataev25e5b442015-09-15 12:52:43 +00008058 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8059 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008060}
8061
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008062StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8063 Stmt *AStmt,
8064 SourceLocation StartLoc,
8065 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008066 if (!AStmt)
8067 return StmtError();
8068
8069 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008070
Reid Kleckner87a31802018-03-12 21:43:02 +00008071 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008072
Alexey Bataev3255bf32015-01-19 05:20:46 +00008073 // OpenMP [2.7.3, single Construct, Restrictions]
8074 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008075 const OMPClause *Nowait = nullptr;
8076 const OMPClause *Copyprivate = nullptr;
8077 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008078 if (Clause->getClauseKind() == OMPC_nowait)
8079 Nowait = Clause;
8080 else if (Clause->getClauseKind() == OMPC_copyprivate)
8081 Copyprivate = Clause;
8082 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008083 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008084 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008085 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008086 return StmtError();
8087 }
8088 }
8089
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008090 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8091}
8092
Alexander Musman80c22892014-07-17 08:54:58 +00008093StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8094 SourceLocation StartLoc,
8095 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008096 if (!AStmt)
8097 return StmtError();
8098
8099 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008100
Reid Kleckner87a31802018-03-12 21:43:02 +00008101 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008102
8103 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8104}
8105
Alexey Bataev28c75412015-12-15 08:19:24 +00008106StmtResult Sema::ActOnOpenMPCriticalDirective(
8107 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8108 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008109 if (!AStmt)
8110 return StmtError();
8111
8112 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008113
Alexey Bataev28c75412015-12-15 08:19:24 +00008114 bool ErrorFound = false;
8115 llvm::APSInt Hint;
8116 SourceLocation HintLoc;
8117 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008118 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008119 if (C->getClauseKind() == OMPC_hint) {
8120 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008121 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008122 ErrorFound = true;
8123 }
8124 Expr *E = cast<OMPHintClause>(C)->getHint();
8125 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008126 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008127 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008128 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008129 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008130 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008131 }
8132 }
8133 }
8134 if (ErrorFound)
8135 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008136 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008137 if (Pair.first && DirName.getName() && !DependentHint) {
8138 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8139 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008140 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008141 Diag(HintLoc, diag::note_omp_critical_hint_here)
8142 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008143 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008144 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008145 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008146 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008147 << 1
8148 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8149 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008150 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008151 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008152 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008153 }
8154 }
8155
Reid Kleckner87a31802018-03-12 21:43:02 +00008156 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008157
Alexey Bataev28c75412015-12-15 08:19:24 +00008158 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8159 Clauses, AStmt);
8160 if (!Pair.first && DirName.getName() && !DependentHint)
8161 DSAStack->addCriticalWithHint(Dir, Hint);
8162 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008163}
8164
Alexey Bataev4acb8592014-07-07 13:01:15 +00008165StmtResult Sema::ActOnOpenMPParallelForDirective(
8166 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008167 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008168 if (!AStmt)
8169 return StmtError();
8170
Alexey Bataeve3727102018-04-18 15:57:46 +00008171 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008172 // 1.2.2 OpenMP Language Terminology
8173 // Structured block - An executable statement with a single entry at the
8174 // top and a single exit at the bottom.
8175 // The point of exit cannot be a branch out of the structured block.
8176 // longjmp() and throw() must not violate the entry/exit criteria.
8177 CS->getCapturedDecl()->setNothrow();
8178
Alexander Musmanc6388682014-12-15 07:07:06 +00008179 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008180 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8181 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008182 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008183 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008184 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8185 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008186 if (NestedLoopCount == 0)
8187 return StmtError();
8188
Alexander Musmana5f070a2014-10-01 06:03:56 +00008189 assert((CurContext->isDependentContext() || B.builtAll()) &&
8190 "omp parallel for loop exprs were not built");
8191
Alexey Bataev54acd402015-08-04 11:18:19 +00008192 if (!CurContext->isDependentContext()) {
8193 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008194 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008195 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008196 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008197 B.NumIterations, *this, CurScope,
8198 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008199 return StmtError();
8200 }
8201 }
8202
Reid Kleckner87a31802018-03-12 21:43:02 +00008203 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008204 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008205 NestedLoopCount, Clauses, AStmt, B,
8206 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008207}
8208
Alexander Musmane4e893b2014-09-23 09:33:00 +00008209StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8210 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008211 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008212 if (!AStmt)
8213 return StmtError();
8214
Alexey Bataeve3727102018-04-18 15:57:46 +00008215 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008216 // 1.2.2 OpenMP Language Terminology
8217 // Structured block - An executable statement with a single entry at the
8218 // top and a single exit at the bottom.
8219 // The point of exit cannot be a branch out of the structured block.
8220 // longjmp() and throw() must not violate the entry/exit criteria.
8221 CS->getCapturedDecl()->setNothrow();
8222
Alexander Musmanc6388682014-12-15 07:07:06 +00008223 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008224 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8225 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008226 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008227 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008228 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8229 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008230 if (NestedLoopCount == 0)
8231 return StmtError();
8232
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008233 if (!CurContext->isDependentContext()) {
8234 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008235 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008236 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008237 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008238 B.NumIterations, *this, CurScope,
8239 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008240 return StmtError();
8241 }
8242 }
8243
Kelvin Lic5609492016-07-15 04:39:07 +00008244 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008245 return StmtError();
8246
Reid Kleckner87a31802018-03-12 21:43:02 +00008247 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008248 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008249 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008250}
8251
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008252StmtResult
8253Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8254 Stmt *AStmt, SourceLocation StartLoc,
8255 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008256 if (!AStmt)
8257 return StmtError();
8258
8259 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008260 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008261 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008262 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008263 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008264 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008265 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008266 return StmtError();
8267 // All associated statements must be '#pragma omp section' except for
8268 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008269 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008270 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8271 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008272 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008273 diag::err_omp_parallel_sections_substmt_not_section);
8274 return StmtError();
8275 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008276 cast<OMPSectionDirective>(SectionStmt)
8277 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008278 }
8279 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008280 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008281 diag::err_omp_parallel_sections_not_compound_stmt);
8282 return StmtError();
8283 }
8284
Reid Kleckner87a31802018-03-12 21:43:02 +00008285 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008286
Alexey Bataev25e5b442015-09-15 12:52:43 +00008287 return OMPParallelSectionsDirective::Create(
8288 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008289}
8290
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008291StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8292 Stmt *AStmt, SourceLocation StartLoc,
8293 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008294 if (!AStmt)
8295 return StmtError();
8296
David Majnemer9d168222016-08-05 17:44:54 +00008297 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008298 // 1.2.2 OpenMP Language Terminology
8299 // Structured block - An executable statement with a single entry at the
8300 // top and a single exit at the bottom.
8301 // The point of exit cannot be a branch out of the structured block.
8302 // longjmp() and throw() must not violate the entry/exit criteria.
8303 CS->getCapturedDecl()->setNothrow();
8304
Reid Kleckner87a31802018-03-12 21:43:02 +00008305 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008306
Alexey Bataev25e5b442015-09-15 12:52:43 +00008307 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8308 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008309}
8310
Alexey Bataev68446b72014-07-18 07:47:19 +00008311StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8312 SourceLocation EndLoc) {
8313 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8314}
8315
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008316StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8317 SourceLocation EndLoc) {
8318 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8319}
8320
Alexey Bataev2df347a2014-07-18 10:17:07 +00008321StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8322 SourceLocation EndLoc) {
8323 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8324}
8325
Alexey Bataev169d96a2017-07-18 20:17:46 +00008326StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8327 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008328 SourceLocation StartLoc,
8329 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008330 if (!AStmt)
8331 return StmtError();
8332
8333 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008334
Reid Kleckner87a31802018-03-12 21:43:02 +00008335 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008336
Alexey Bataev169d96a2017-07-18 20:17:46 +00008337 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008338 AStmt,
8339 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008340}
8341
Alexey Bataev6125da92014-07-21 11:26:11 +00008342StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8343 SourceLocation StartLoc,
8344 SourceLocation EndLoc) {
8345 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8346 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8347}
8348
Alexey Bataev346265e2015-09-25 10:37:12 +00008349StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8350 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008351 SourceLocation StartLoc,
8352 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008353 const OMPClause *DependFound = nullptr;
8354 const OMPClause *DependSourceClause = nullptr;
8355 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008356 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008357 const OMPThreadsClause *TC = nullptr;
8358 const OMPSIMDClause *SC = nullptr;
8359 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008360 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8361 DependFound = C;
8362 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8363 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008364 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008365 << getOpenMPDirectiveName(OMPD_ordered)
8366 << getOpenMPClauseName(OMPC_depend) << 2;
8367 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008368 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008369 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008370 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008371 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008372 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008373 << 0;
8374 ErrorFound = true;
8375 }
8376 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8377 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008378 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008379 << 1;
8380 ErrorFound = true;
8381 }
8382 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008383 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008384 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008385 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008386 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008387 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008388 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008389 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008390 if (!ErrorFound && !SC &&
8391 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008392 // OpenMP [2.8.1,simd Construct, Restrictions]
8393 // An ordered construct with the simd clause is the only OpenMP construct
8394 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008395 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8396 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008397 ErrorFound = true;
8398 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008399 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008400 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8401 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008402 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008403 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008404 diag::err_omp_ordered_directive_without_param);
8405 ErrorFound = true;
8406 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008407 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008408 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008409 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8410 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008411 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008412 ErrorFound = true;
8413 }
8414 }
8415 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008416 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008417
8418 if (AStmt) {
8419 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8420
Reid Kleckner87a31802018-03-12 21:43:02 +00008421 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008422 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008423
8424 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008425}
8426
Alexey Bataev1d160b12015-03-13 12:27:31 +00008427namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008428/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008429/// construct.
8430class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008431 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008432 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008433 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008434 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008435 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008436 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008437 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008438 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008439 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008440 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008441 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008442 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008443 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008444 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008445 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008446 /// expression.
8447 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008448 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008449 /// part.
8450 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008451 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008452 NoError
8453 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008454 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008455 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008456 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008457 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008458 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008459 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008460 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008461 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008462 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008463 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8464 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8465 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008466 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008467 /// important for non-associative operations.
8468 bool IsXLHSInRHSPart;
8469 BinaryOperatorKind Op;
8470 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008471 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008472 /// if it is a prefix unary operation.
8473 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008474
8475public:
8476 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008477 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008478 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008479 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008480 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008481 /// expression. If DiagId and NoteId == 0, then only check is performed
8482 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008483 /// \param DiagId Diagnostic which should be emitted if error is found.
8484 /// \param NoteId Diagnostic note for the main error message.
8485 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008486 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008487 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008488 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008489 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008490 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008491 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008492 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8493 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8494 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008495 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008496 /// false otherwise.
8497 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8498
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008499 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008500 /// if it is a prefix unary operation.
8501 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8502
Alexey Bataev1d160b12015-03-13 12:27:31 +00008503private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008504 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8505 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008506};
8507} // namespace
8508
8509bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8510 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8511 ExprAnalysisErrorCode ErrorFound = NoError;
8512 SourceLocation ErrorLoc, NoteLoc;
8513 SourceRange ErrorRange, NoteRange;
8514 // Allowed constructs are:
8515 // x = x binop expr;
8516 // x = expr binop x;
8517 if (AtomicBinOp->getOpcode() == BO_Assign) {
8518 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008519 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008520 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8521 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8522 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8523 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008524 Op = AtomicInnerBinOp->getOpcode();
8525 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008526 Expr *LHS = AtomicInnerBinOp->getLHS();
8527 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008528 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8529 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8530 /*Canonical=*/true);
8531 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8532 /*Canonical=*/true);
8533 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8534 /*Canonical=*/true);
8535 if (XId == LHSId) {
8536 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008537 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008538 } else if (XId == RHSId) {
8539 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008540 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008541 } else {
8542 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8543 ErrorRange = AtomicInnerBinOp->getSourceRange();
8544 NoteLoc = X->getExprLoc();
8545 NoteRange = X->getSourceRange();
8546 ErrorFound = NotAnUpdateExpression;
8547 }
8548 } else {
8549 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8550 ErrorRange = AtomicInnerBinOp->getSourceRange();
8551 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8552 NoteRange = SourceRange(NoteLoc, NoteLoc);
8553 ErrorFound = NotABinaryOperator;
8554 }
8555 } else {
8556 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8557 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8558 ErrorFound = NotABinaryExpression;
8559 }
8560 } else {
8561 ErrorLoc = AtomicBinOp->getExprLoc();
8562 ErrorRange = AtomicBinOp->getSourceRange();
8563 NoteLoc = AtomicBinOp->getOperatorLoc();
8564 NoteRange = SourceRange(NoteLoc, NoteLoc);
8565 ErrorFound = NotAnAssignmentOp;
8566 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008567 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008568 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8569 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8570 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008571 }
8572 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008573 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008574 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008575}
8576
8577bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8578 unsigned NoteId) {
8579 ExprAnalysisErrorCode ErrorFound = NoError;
8580 SourceLocation ErrorLoc, NoteLoc;
8581 SourceRange ErrorRange, NoteRange;
8582 // Allowed constructs are:
8583 // x++;
8584 // x--;
8585 // ++x;
8586 // --x;
8587 // x binop= expr;
8588 // x = x binop expr;
8589 // x = expr binop x;
8590 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8591 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8592 if (AtomicBody->getType()->isScalarType() ||
8593 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008594 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008595 AtomicBody->IgnoreParenImpCasts())) {
8596 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008597 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008598 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008599 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008600 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008601 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008602 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008603 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8604 AtomicBody->IgnoreParenImpCasts())) {
8605 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008606 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008607 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008608 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008609 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008610 // Check for Unary Operation
8611 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008612 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008613 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8614 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008615 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008616 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8617 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008618 } else {
8619 ErrorFound = NotAnUnaryIncDecExpression;
8620 ErrorLoc = AtomicUnaryOp->getExprLoc();
8621 ErrorRange = AtomicUnaryOp->getSourceRange();
8622 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8623 NoteRange = SourceRange(NoteLoc, NoteLoc);
8624 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008625 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008626 ErrorFound = NotABinaryOrUnaryExpression;
8627 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8628 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8629 }
8630 } else {
8631 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008632 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008633 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8634 }
8635 } else {
8636 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008637 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008638 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8639 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008640 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008641 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8642 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8643 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008644 }
8645 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008646 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008647 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008648 // Build an update expression of form 'OpaqueValueExpr(x) binop
8649 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8650 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8651 auto *OVEX = new (SemaRef.getASTContext())
8652 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8653 auto *OVEExpr = new (SemaRef.getASTContext())
8654 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008655 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008656 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8657 IsXLHSInRHSPart ? OVEExpr : OVEX);
8658 if (Update.isInvalid())
8659 return true;
8660 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8661 Sema::AA_Casting);
8662 if (Update.isInvalid())
8663 return true;
8664 UpdateExpr = Update.get();
8665 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008666 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008667}
8668
Alexey Bataev0162e452014-07-22 10:10:35 +00008669StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8670 Stmt *AStmt,
8671 SourceLocation StartLoc,
8672 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008673 if (!AStmt)
8674 return StmtError();
8675
David Majnemer9d168222016-08-05 17:44:54 +00008676 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008677 // 1.2.2 OpenMP Language Terminology
8678 // Structured block - An executable statement with a single entry at the
8679 // top and a single exit at the bottom.
8680 // The point of exit cannot be a branch out of the structured block.
8681 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008682 OpenMPClauseKind AtomicKind = OMPC_unknown;
8683 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008684 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008685 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008686 C->getClauseKind() == OMPC_update ||
8687 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008688 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008689 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008690 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008691 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8692 << getOpenMPClauseName(AtomicKind);
8693 } else {
8694 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008695 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008696 }
8697 }
8698 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008699
Alexey Bataeve3727102018-04-18 15:57:46 +00008700 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008701 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8702 Body = EWC->getSubExpr();
8703
Alexey Bataev62cec442014-11-18 10:14:22 +00008704 Expr *X = nullptr;
8705 Expr *V = nullptr;
8706 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008707 Expr *UE = nullptr;
8708 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008709 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008710 // OpenMP [2.12.6, atomic Construct]
8711 // In the next expressions:
8712 // * x and v (as applicable) are both l-value expressions with scalar type.
8713 // * During the execution of an atomic region, multiple syntactic
8714 // occurrences of x must designate the same storage location.
8715 // * Neither of v and expr (as applicable) may access the storage location
8716 // designated by x.
8717 // * Neither of x and expr (as applicable) may access the storage location
8718 // designated by v.
8719 // * expr is an expression with scalar type.
8720 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8721 // * binop, binop=, ++, and -- are not overloaded operators.
8722 // * The expression x binop expr must be numerically equivalent to x binop
8723 // (expr). This requirement is satisfied if the operators in expr have
8724 // precedence greater than binop, or by using parentheses around expr or
8725 // subexpressions of expr.
8726 // * The expression expr binop x must be numerically equivalent to (expr)
8727 // binop x. This requirement is satisfied if the operators in expr have
8728 // precedence equal to or greater than binop, or by using parentheses around
8729 // expr or subexpressions of expr.
8730 // * For forms that allow multiple occurrences of x, the number of times
8731 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008732 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008733 enum {
8734 NotAnExpression,
8735 NotAnAssignmentOp,
8736 NotAScalarType,
8737 NotAnLValue,
8738 NoError
8739 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008740 SourceLocation ErrorLoc, NoteLoc;
8741 SourceRange ErrorRange, NoteRange;
8742 // If clause is read:
8743 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008744 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8745 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008746 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8747 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8748 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8749 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8750 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8751 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8752 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008753 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008754 ErrorFound = NotAnLValue;
8755 ErrorLoc = AtomicBinOp->getExprLoc();
8756 ErrorRange = AtomicBinOp->getSourceRange();
8757 NoteLoc = NotLValueExpr->getExprLoc();
8758 NoteRange = NotLValueExpr->getSourceRange();
8759 }
8760 } else if (!X->isInstantiationDependent() ||
8761 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008762 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008763 (X->isInstantiationDependent() || X->getType()->isScalarType())
8764 ? V
8765 : X;
8766 ErrorFound = NotAScalarType;
8767 ErrorLoc = AtomicBinOp->getExprLoc();
8768 ErrorRange = AtomicBinOp->getSourceRange();
8769 NoteLoc = NotScalarExpr->getExprLoc();
8770 NoteRange = NotScalarExpr->getSourceRange();
8771 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008772 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008773 ErrorFound = NotAnAssignmentOp;
8774 ErrorLoc = AtomicBody->getExprLoc();
8775 ErrorRange = AtomicBody->getSourceRange();
8776 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8777 : AtomicBody->getExprLoc();
8778 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8779 : AtomicBody->getSourceRange();
8780 }
8781 } else {
8782 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008783 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008784 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008785 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008786 if (ErrorFound != NoError) {
8787 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8788 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008789 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8790 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008791 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008792 }
8793 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008794 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008795 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008796 enum {
8797 NotAnExpression,
8798 NotAnAssignmentOp,
8799 NotAScalarType,
8800 NotAnLValue,
8801 NoError
8802 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008803 SourceLocation ErrorLoc, NoteLoc;
8804 SourceRange ErrorRange, NoteRange;
8805 // If clause is write:
8806 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008807 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8808 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008809 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8810 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008811 X = AtomicBinOp->getLHS();
8812 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008813 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8814 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8815 if (!X->isLValue()) {
8816 ErrorFound = NotAnLValue;
8817 ErrorLoc = AtomicBinOp->getExprLoc();
8818 ErrorRange = AtomicBinOp->getSourceRange();
8819 NoteLoc = X->getExprLoc();
8820 NoteRange = X->getSourceRange();
8821 }
8822 } else if (!X->isInstantiationDependent() ||
8823 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008824 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008825 (X->isInstantiationDependent() || X->getType()->isScalarType())
8826 ? E
8827 : X;
8828 ErrorFound = NotAScalarType;
8829 ErrorLoc = AtomicBinOp->getExprLoc();
8830 ErrorRange = AtomicBinOp->getSourceRange();
8831 NoteLoc = NotScalarExpr->getExprLoc();
8832 NoteRange = NotScalarExpr->getSourceRange();
8833 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008834 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008835 ErrorFound = NotAnAssignmentOp;
8836 ErrorLoc = AtomicBody->getExprLoc();
8837 ErrorRange = AtomicBody->getSourceRange();
8838 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8839 : AtomicBody->getExprLoc();
8840 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8841 : AtomicBody->getSourceRange();
8842 }
8843 } else {
8844 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008845 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008846 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008847 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008848 if (ErrorFound != NoError) {
8849 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8850 << ErrorRange;
8851 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8852 << NoteRange;
8853 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008854 }
8855 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00008856 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008857 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008858 // If clause is update:
8859 // x++;
8860 // x--;
8861 // ++x;
8862 // --x;
8863 // x binop= expr;
8864 // x = x binop expr;
8865 // x = expr binop x;
8866 OpenMPAtomicUpdateChecker Checker(*this);
8867 if (Checker.checkStatement(
8868 Body, (AtomicKind == OMPC_update)
8869 ? diag::err_omp_atomic_update_not_expression_statement
8870 : diag::err_omp_atomic_not_expression_statement,
8871 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00008872 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008873 if (!CurContext->isDependentContext()) {
8874 E = Checker.getExpr();
8875 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008876 UE = Checker.getUpdateExpr();
8877 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00008878 }
Alexey Bataev459dec02014-07-24 06:46:57 +00008879 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008880 enum {
8881 NotAnAssignmentOp,
8882 NotACompoundStatement,
8883 NotTwoSubstatements,
8884 NotASpecificExpression,
8885 NoError
8886 } ErrorFound = NoError;
8887 SourceLocation ErrorLoc, NoteLoc;
8888 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00008889 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008890 // If clause is a capture:
8891 // v = x++;
8892 // v = x--;
8893 // v = ++x;
8894 // v = --x;
8895 // v = x binop= expr;
8896 // v = x = x binop expr;
8897 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008898 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00008899 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8900 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8901 V = AtomicBinOp->getLHS();
8902 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8903 OpenMPAtomicUpdateChecker Checker(*this);
8904 if (Checker.checkStatement(
8905 Body, diag::err_omp_atomic_capture_not_expression_statement,
8906 diag::note_omp_atomic_update))
8907 return StmtError();
8908 E = Checker.getExpr();
8909 X = Checker.getX();
8910 UE = Checker.getUpdateExpr();
8911 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8912 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00008913 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008914 ErrorLoc = AtomicBody->getExprLoc();
8915 ErrorRange = AtomicBody->getSourceRange();
8916 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8917 : AtomicBody->getExprLoc();
8918 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8919 : AtomicBody->getSourceRange();
8920 ErrorFound = NotAnAssignmentOp;
8921 }
8922 if (ErrorFound != NoError) {
8923 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
8924 << ErrorRange;
8925 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8926 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008927 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008928 if (CurContext->isDependentContext())
8929 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008930 } else {
8931 // If clause is a capture:
8932 // { v = x; x = expr; }
8933 // { v = x; x++; }
8934 // { v = x; x--; }
8935 // { v = x; ++x; }
8936 // { v = x; --x; }
8937 // { v = x; x binop= expr; }
8938 // { v = x; x = x binop expr; }
8939 // { v = x; x = expr binop x; }
8940 // { x++; v = x; }
8941 // { x--; v = x; }
8942 // { ++x; v = x; }
8943 // { --x; v = x; }
8944 // { x binop= expr; v = x; }
8945 // { x = x binop expr; v = x; }
8946 // { x = expr binop x; v = x; }
8947 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
8948 // Check that this is { expr1; expr2; }
8949 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008950 Stmt *First = CS->body_front();
8951 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008952 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
8953 First = EWC->getSubExpr()->IgnoreParenImpCasts();
8954 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
8955 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
8956 // Need to find what subexpression is 'v' and what is 'x'.
8957 OpenMPAtomicUpdateChecker Checker(*this);
8958 bool IsUpdateExprFound = !Checker.checkStatement(Second);
8959 BinaryOperator *BinOp = nullptr;
8960 if (IsUpdateExprFound) {
8961 BinOp = dyn_cast<BinaryOperator>(First);
8962 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8963 }
8964 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8965 // { v = x; x++; }
8966 // { v = x; x--; }
8967 // { v = x; ++x; }
8968 // { v = x; --x; }
8969 // { v = x; x binop= expr; }
8970 // { v = x; x = x binop expr; }
8971 // { v = x; x = expr binop x; }
8972 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008973 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008974 llvm::FoldingSetNodeID XId, PossibleXId;
8975 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8976 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8977 IsUpdateExprFound = XId == PossibleXId;
8978 if (IsUpdateExprFound) {
8979 V = BinOp->getLHS();
8980 X = Checker.getX();
8981 E = Checker.getExpr();
8982 UE = Checker.getUpdateExpr();
8983 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008984 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008985 }
8986 }
8987 if (!IsUpdateExprFound) {
8988 IsUpdateExprFound = !Checker.checkStatement(First);
8989 BinOp = nullptr;
8990 if (IsUpdateExprFound) {
8991 BinOp = dyn_cast<BinaryOperator>(Second);
8992 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8993 }
8994 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8995 // { x++; v = x; }
8996 // { x--; v = x; }
8997 // { ++x; v = x; }
8998 // { --x; v = x; }
8999 // { x binop= expr; v = x; }
9000 // { x = x binop expr; v = x; }
9001 // { x = expr binop x; v = x; }
9002 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009003 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009004 llvm::FoldingSetNodeID XId, PossibleXId;
9005 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9006 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9007 IsUpdateExprFound = XId == PossibleXId;
9008 if (IsUpdateExprFound) {
9009 V = BinOp->getLHS();
9010 X = Checker.getX();
9011 E = Checker.getExpr();
9012 UE = Checker.getUpdateExpr();
9013 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009014 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009015 }
9016 }
9017 }
9018 if (!IsUpdateExprFound) {
9019 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009020 auto *FirstExpr = dyn_cast<Expr>(First);
9021 auto *SecondExpr = dyn_cast<Expr>(Second);
9022 if (!FirstExpr || !SecondExpr ||
9023 !(FirstExpr->isInstantiationDependent() ||
9024 SecondExpr->isInstantiationDependent())) {
9025 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9026 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009027 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009028 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009029 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009030 NoteRange = ErrorRange = FirstBinOp
9031 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009032 : SourceRange(ErrorLoc, ErrorLoc);
9033 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009034 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9035 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9036 ErrorFound = NotAnAssignmentOp;
9037 NoteLoc = ErrorLoc = SecondBinOp
9038 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009039 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009040 NoteRange = ErrorRange =
9041 SecondBinOp ? SecondBinOp->getSourceRange()
9042 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009043 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009044 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009045 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009046 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009047 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9048 llvm::FoldingSetNodeID X1Id, X2Id;
9049 PossibleXRHSInFirst->Profile(X1Id, Context,
9050 /*Canonical=*/true);
9051 PossibleXLHSInSecond->Profile(X2Id, Context,
9052 /*Canonical=*/true);
9053 IsUpdateExprFound = X1Id == X2Id;
9054 if (IsUpdateExprFound) {
9055 V = FirstBinOp->getLHS();
9056 X = SecondBinOp->getLHS();
9057 E = SecondBinOp->getRHS();
9058 UE = nullptr;
9059 IsXLHSInRHSPart = false;
9060 IsPostfixUpdate = true;
9061 } else {
9062 ErrorFound = NotASpecificExpression;
9063 ErrorLoc = FirstBinOp->getExprLoc();
9064 ErrorRange = FirstBinOp->getSourceRange();
9065 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9066 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9067 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009068 }
9069 }
9070 }
9071 }
9072 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009073 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009074 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009075 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009076 ErrorFound = NotTwoSubstatements;
9077 }
9078 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009079 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009080 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009081 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009082 ErrorFound = NotACompoundStatement;
9083 }
9084 if (ErrorFound != NoError) {
9085 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9086 << ErrorRange;
9087 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9088 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009089 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009090 if (CurContext->isDependentContext())
9091 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009092 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009093 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009094
Reid Kleckner87a31802018-03-12 21:43:02 +00009095 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009096
Alexey Bataev62cec442014-11-18 10:14:22 +00009097 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009098 X, V, E, UE, IsXLHSInRHSPart,
9099 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009100}
9101
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009102StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9103 Stmt *AStmt,
9104 SourceLocation StartLoc,
9105 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009106 if (!AStmt)
9107 return StmtError();
9108
Alexey Bataeve3727102018-04-18 15:57:46 +00009109 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009110 // 1.2.2 OpenMP Language Terminology
9111 // Structured block - An executable statement with a single entry at the
9112 // top and a single exit at the bottom.
9113 // The point of exit cannot be a branch out of the structured block.
9114 // longjmp() and throw() must not violate the entry/exit criteria.
9115 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009116 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9117 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9118 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9119 // 1.2.2 OpenMP Language Terminology
9120 // Structured block - An executable statement with a single entry at the
9121 // top and a single exit at the bottom.
9122 // The point of exit cannot be a branch out of the structured block.
9123 // longjmp() and throw() must not violate the entry/exit criteria.
9124 CS->getCapturedDecl()->setNothrow();
9125 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009126
Alexey Bataev13314bf2014-10-09 04:18:56 +00009127 // OpenMP [2.16, Nesting of Regions]
9128 // If specified, a teams construct must be contained within a target
9129 // construct. That target construct must contain no statements or directives
9130 // outside of the teams construct.
9131 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009132 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009133 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009134 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009135 auto I = CS->body_begin();
9136 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009137 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009138 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9139 OMPTeamsFound) {
9140
Alexey Bataev13314bf2014-10-09 04:18:56 +00009141 OMPTeamsFound = false;
9142 break;
9143 }
9144 ++I;
9145 }
9146 assert(I != CS->body_end() && "Not found statement");
9147 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009148 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009149 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009150 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009151 }
9152 if (!OMPTeamsFound) {
9153 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9154 Diag(DSAStack->getInnerTeamsRegionLoc(),
9155 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009156 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009157 << isa<OMPExecutableDirective>(S);
9158 return StmtError();
9159 }
9160 }
9161
Reid Kleckner87a31802018-03-12 21:43:02 +00009162 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009163
9164 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9165}
9166
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009167StmtResult
9168Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9169 Stmt *AStmt, SourceLocation StartLoc,
9170 SourceLocation EndLoc) {
9171 if (!AStmt)
9172 return StmtError();
9173
Alexey Bataeve3727102018-04-18 15:57:46 +00009174 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009175 // 1.2.2 OpenMP Language Terminology
9176 // Structured block - An executable statement with a single entry at the
9177 // top and a single exit at the bottom.
9178 // The point of exit cannot be a branch out of the structured block.
9179 // longjmp() and throw() must not violate the entry/exit criteria.
9180 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009181 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9182 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9183 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9184 // 1.2.2 OpenMP Language Terminology
9185 // Structured block - An executable statement with a single entry at the
9186 // top and a single exit at the bottom.
9187 // The point of exit cannot be a branch out of the structured block.
9188 // longjmp() and throw() must not violate the entry/exit criteria.
9189 CS->getCapturedDecl()->setNothrow();
9190 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009191
Reid Kleckner87a31802018-03-12 21:43:02 +00009192 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009193
9194 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9195 AStmt);
9196}
9197
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009198StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9199 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009200 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009201 if (!AStmt)
9202 return StmtError();
9203
Alexey Bataeve3727102018-04-18 15:57:46 +00009204 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009205 // 1.2.2 OpenMP Language Terminology
9206 // Structured block - An executable statement with a single entry at the
9207 // top and a single exit at the bottom.
9208 // The point of exit cannot be a branch out of the structured block.
9209 // longjmp() and throw() must not violate the entry/exit criteria.
9210 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009211 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9212 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9213 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9214 // 1.2.2 OpenMP Language Terminology
9215 // Structured block - An executable statement with a single entry at the
9216 // top and a single exit at the bottom.
9217 // The point of exit cannot be a branch out of the structured block.
9218 // longjmp() and throw() must not violate the entry/exit criteria.
9219 CS->getCapturedDecl()->setNothrow();
9220 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009221
9222 OMPLoopDirective::HelperExprs B;
9223 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9224 // define the nested loops number.
9225 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009226 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009227 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009228 VarsWithImplicitDSA, B);
9229 if (NestedLoopCount == 0)
9230 return StmtError();
9231
9232 assert((CurContext->isDependentContext() || B.builtAll()) &&
9233 "omp target parallel for loop exprs were not built");
9234
9235 if (!CurContext->isDependentContext()) {
9236 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009237 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009238 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009239 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009240 B.NumIterations, *this, CurScope,
9241 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009242 return StmtError();
9243 }
9244 }
9245
Reid Kleckner87a31802018-03-12 21:43:02 +00009246 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009247 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9248 NestedLoopCount, Clauses, AStmt,
9249 B, DSAStack->isCancelRegion());
9250}
9251
Alexey Bataev95b64a92017-05-30 16:00:04 +00009252/// Check for existence of a map clause in the list of clauses.
9253static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9254 const OpenMPClauseKind K) {
9255 return llvm::any_of(
9256 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9257}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009258
Alexey Bataev95b64a92017-05-30 16:00:04 +00009259template <typename... Params>
9260static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9261 const Params... ClauseTypes) {
9262 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009263}
9264
Michael Wong65f367f2015-07-21 13:44:28 +00009265StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9266 Stmt *AStmt,
9267 SourceLocation StartLoc,
9268 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009269 if (!AStmt)
9270 return StmtError();
9271
9272 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9273
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009274 // OpenMP [2.10.1, Restrictions, p. 97]
9275 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009276 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9277 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9278 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009279 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009280 return StmtError();
9281 }
9282
Reid Kleckner87a31802018-03-12 21:43:02 +00009283 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009284
9285 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9286 AStmt);
9287}
9288
Samuel Antaodf67fc42016-01-19 19:15:56 +00009289StmtResult
9290Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9291 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009292 SourceLocation EndLoc, Stmt *AStmt) {
9293 if (!AStmt)
9294 return StmtError();
9295
Alexey Bataeve3727102018-04-18 15:57:46 +00009296 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009297 // 1.2.2 OpenMP Language Terminology
9298 // Structured block - An executable statement with a single entry at the
9299 // top and a single exit at the bottom.
9300 // The point of exit cannot be a branch out of the structured block.
9301 // longjmp() and throw() must not violate the entry/exit criteria.
9302 CS->getCapturedDecl()->setNothrow();
9303 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9304 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9305 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9306 // 1.2.2 OpenMP Language Terminology
9307 // Structured block - An executable statement with a single entry at the
9308 // top and a single exit at the bottom.
9309 // The point of exit cannot be a branch out of the structured block.
9310 // longjmp() and throw() must not violate the entry/exit criteria.
9311 CS->getCapturedDecl()->setNothrow();
9312 }
9313
Samuel Antaodf67fc42016-01-19 19:15:56 +00009314 // OpenMP [2.10.2, Restrictions, p. 99]
9315 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009316 if (!hasClauses(Clauses, OMPC_map)) {
9317 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9318 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009319 return StmtError();
9320 }
9321
Alexey Bataev7828b252017-11-21 17:08:48 +00009322 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9323 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009324}
9325
Samuel Antao72590762016-01-19 20:04:50 +00009326StmtResult
9327Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9328 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009329 SourceLocation EndLoc, Stmt *AStmt) {
9330 if (!AStmt)
9331 return StmtError();
9332
Alexey Bataeve3727102018-04-18 15:57:46 +00009333 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009334 // 1.2.2 OpenMP Language Terminology
9335 // Structured block - An executable statement with a single entry at the
9336 // top and a single exit at the bottom.
9337 // The point of exit cannot be a branch out of the structured block.
9338 // longjmp() and throw() must not violate the entry/exit criteria.
9339 CS->getCapturedDecl()->setNothrow();
9340 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9341 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9342 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9343 // 1.2.2 OpenMP Language Terminology
9344 // Structured block - An executable statement with a single entry at the
9345 // top and a single exit at the bottom.
9346 // The point of exit cannot be a branch out of the structured block.
9347 // longjmp() and throw() must not violate the entry/exit criteria.
9348 CS->getCapturedDecl()->setNothrow();
9349 }
9350
Samuel Antao72590762016-01-19 20:04:50 +00009351 // OpenMP [2.10.3, Restrictions, p. 102]
9352 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009353 if (!hasClauses(Clauses, OMPC_map)) {
9354 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9355 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009356 return StmtError();
9357 }
9358
Alexey Bataev7828b252017-11-21 17:08:48 +00009359 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9360 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009361}
9362
Samuel Antao686c70c2016-05-26 17:30:50 +00009363StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9364 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009365 SourceLocation EndLoc,
9366 Stmt *AStmt) {
9367 if (!AStmt)
9368 return StmtError();
9369
Alexey Bataeve3727102018-04-18 15:57:46 +00009370 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009371 // 1.2.2 OpenMP Language Terminology
9372 // Structured block - An executable statement with a single entry at the
9373 // top and a single exit at the bottom.
9374 // The point of exit cannot be a branch out of the structured block.
9375 // longjmp() and throw() must not violate the entry/exit criteria.
9376 CS->getCapturedDecl()->setNothrow();
9377 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9378 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9379 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9380 // 1.2.2 OpenMP Language Terminology
9381 // Structured block - An executable statement with a single entry at the
9382 // top and a single exit at the bottom.
9383 // The point of exit cannot be a branch out of the structured block.
9384 // longjmp() and throw() must not violate the entry/exit criteria.
9385 CS->getCapturedDecl()->setNothrow();
9386 }
9387
Alexey Bataev95b64a92017-05-30 16:00:04 +00009388 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009389 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9390 return StmtError();
9391 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009392 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9393 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009394}
9395
Alexey Bataev13314bf2014-10-09 04:18:56 +00009396StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9397 Stmt *AStmt, SourceLocation StartLoc,
9398 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009399 if (!AStmt)
9400 return StmtError();
9401
Alexey Bataeve3727102018-04-18 15:57:46 +00009402 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009403 // 1.2.2 OpenMP Language Terminology
9404 // Structured block - An executable statement with a single entry at the
9405 // top and a single exit at the bottom.
9406 // The point of exit cannot be a branch out of the structured block.
9407 // longjmp() and throw() must not violate the entry/exit criteria.
9408 CS->getCapturedDecl()->setNothrow();
9409
Reid Kleckner87a31802018-03-12 21:43:02 +00009410 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009411
Alexey Bataevceabd412017-11-30 18:01:54 +00009412 DSAStack->setParentTeamsRegionLoc(StartLoc);
9413
Alexey Bataev13314bf2014-10-09 04:18:56 +00009414 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9415}
9416
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009417StmtResult
9418Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9419 SourceLocation EndLoc,
9420 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009421 if (DSAStack->isParentNowaitRegion()) {
9422 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9423 return StmtError();
9424 }
9425 if (DSAStack->isParentOrderedRegion()) {
9426 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9427 return StmtError();
9428 }
9429 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9430 CancelRegion);
9431}
9432
Alexey Bataev87933c72015-09-18 08:07:34 +00009433StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9434 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009435 SourceLocation EndLoc,
9436 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009437 if (DSAStack->isParentNowaitRegion()) {
9438 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9439 return StmtError();
9440 }
9441 if (DSAStack->isParentOrderedRegion()) {
9442 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9443 return StmtError();
9444 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009445 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009446 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9447 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009448}
9449
Alexey Bataev382967a2015-12-08 12:06:20 +00009450static bool checkGrainsizeNumTasksClauses(Sema &S,
9451 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009452 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009453 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009454 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009455 if (C->getClauseKind() == OMPC_grainsize ||
9456 C->getClauseKind() == OMPC_num_tasks) {
9457 if (!PrevClause)
9458 PrevClause = C;
9459 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009460 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009461 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9462 << getOpenMPClauseName(C->getClauseKind())
9463 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009464 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009465 diag::note_omp_previous_grainsize_num_tasks)
9466 << getOpenMPClauseName(PrevClause->getClauseKind());
9467 ErrorFound = true;
9468 }
9469 }
9470 }
9471 return ErrorFound;
9472}
9473
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009474static bool checkReductionClauseWithNogroup(Sema &S,
9475 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009476 const OMPClause *ReductionClause = nullptr;
9477 const OMPClause *NogroupClause = nullptr;
9478 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009479 if (C->getClauseKind() == OMPC_reduction) {
9480 ReductionClause = C;
9481 if (NogroupClause)
9482 break;
9483 continue;
9484 }
9485 if (C->getClauseKind() == OMPC_nogroup) {
9486 NogroupClause = C;
9487 if (ReductionClause)
9488 break;
9489 continue;
9490 }
9491 }
9492 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009493 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9494 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009495 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009496 return true;
9497 }
9498 return false;
9499}
9500
Alexey Bataev49f6e782015-12-01 04:18:41 +00009501StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9502 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009503 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009504 if (!AStmt)
9505 return StmtError();
9506
9507 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9508 OMPLoopDirective::HelperExprs B;
9509 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9510 // define the nested loops number.
9511 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009512 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009513 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009514 VarsWithImplicitDSA, B);
9515 if (NestedLoopCount == 0)
9516 return StmtError();
9517
9518 assert((CurContext->isDependentContext() || B.builtAll()) &&
9519 "omp for loop exprs were not built");
9520
Alexey Bataev382967a2015-12-08 12:06:20 +00009521 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9522 // The grainsize clause and num_tasks clause are mutually exclusive and may
9523 // not appear on the same taskloop directive.
9524 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9525 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009526 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9527 // If a reduction clause is present on the taskloop directive, the nogroup
9528 // clause must not be specified.
9529 if (checkReductionClauseWithNogroup(*this, Clauses))
9530 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009531
Reid Kleckner87a31802018-03-12 21:43:02 +00009532 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009533 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9534 NestedLoopCount, Clauses, AStmt, B);
9535}
9536
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009537StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9538 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009539 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009540 if (!AStmt)
9541 return StmtError();
9542
9543 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9544 OMPLoopDirective::HelperExprs B;
9545 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9546 // define the nested loops number.
9547 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009548 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009549 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9550 VarsWithImplicitDSA, B);
9551 if (NestedLoopCount == 0)
9552 return StmtError();
9553
9554 assert((CurContext->isDependentContext() || B.builtAll()) &&
9555 "omp for loop exprs were not built");
9556
Alexey Bataev5a3af132016-03-29 08:58:54 +00009557 if (!CurContext->isDependentContext()) {
9558 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009559 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009560 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009561 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009562 B.NumIterations, *this, CurScope,
9563 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009564 return StmtError();
9565 }
9566 }
9567
Alexey Bataev382967a2015-12-08 12:06:20 +00009568 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9569 // The grainsize clause and num_tasks clause are mutually exclusive and may
9570 // not appear on the same taskloop directive.
9571 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9572 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009573 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9574 // If a reduction clause is present on the taskloop directive, the nogroup
9575 // clause must not be specified.
9576 if (checkReductionClauseWithNogroup(*this, Clauses))
9577 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009578 if (checkSimdlenSafelenSpecified(*this, Clauses))
9579 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009580
Reid Kleckner87a31802018-03-12 21:43:02 +00009581 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009582 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9583 NestedLoopCount, Clauses, AStmt, B);
9584}
9585
Alexey Bataev60e51c42019-10-10 20:13:02 +00009586StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9587 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9588 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9589 if (!AStmt)
9590 return StmtError();
9591
9592 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9593 OMPLoopDirective::HelperExprs B;
9594 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9595 // define the nested loops number.
9596 unsigned NestedLoopCount =
9597 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9598 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9599 VarsWithImplicitDSA, B);
9600 if (NestedLoopCount == 0)
9601 return StmtError();
9602
9603 assert((CurContext->isDependentContext() || B.builtAll()) &&
9604 "omp for loop exprs were not built");
9605
9606 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9607 // The grainsize clause and num_tasks clause are mutually exclusive and may
9608 // not appear on the same taskloop directive.
9609 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9610 return StmtError();
9611 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9612 // If a reduction clause is present on the taskloop directive, the nogroup
9613 // clause must not be specified.
9614 if (checkReductionClauseWithNogroup(*this, Clauses))
9615 return StmtError();
9616
9617 setFunctionHasBranchProtectedScope();
9618 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9619 NestedLoopCount, Clauses, AStmt, B);
9620}
9621
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009622StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9623 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9624 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9625 if (!AStmt)
9626 return StmtError();
9627
9628 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9629 OMPLoopDirective::HelperExprs B;
9630 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9631 // define the nested loops number.
9632 unsigned NestedLoopCount =
9633 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9634 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9635 VarsWithImplicitDSA, B);
9636 if (NestedLoopCount == 0)
9637 return StmtError();
9638
9639 assert((CurContext->isDependentContext() || B.builtAll()) &&
9640 "omp for loop exprs were not built");
9641
9642 if (!CurContext->isDependentContext()) {
9643 // Finalize the clauses that need pre-built expressions for CodeGen.
9644 for (OMPClause *C : Clauses) {
9645 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9646 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9647 B.NumIterations, *this, CurScope,
9648 DSAStack))
9649 return StmtError();
9650 }
9651 }
9652
9653 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9654 // The grainsize clause and num_tasks clause are mutually exclusive and may
9655 // not appear on the same taskloop directive.
9656 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9657 return StmtError();
9658 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9659 // If a reduction clause is present on the taskloop directive, the nogroup
9660 // clause must not be specified.
9661 if (checkReductionClauseWithNogroup(*this, Clauses))
9662 return StmtError();
9663 if (checkSimdlenSafelenSpecified(*this, Clauses))
9664 return StmtError();
9665
9666 setFunctionHasBranchProtectedScope();
9667 return OMPMasterTaskLoopSimdDirective::Create(
9668 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9669}
9670
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009671StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9672 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9673 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9674 if (!AStmt)
9675 return StmtError();
9676
9677 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9678 auto *CS = cast<CapturedStmt>(AStmt);
9679 // 1.2.2 OpenMP Language Terminology
9680 // Structured block - An executable statement with a single entry at the
9681 // top and a single exit at the bottom.
9682 // The point of exit cannot be a branch out of the structured block.
9683 // longjmp() and throw() must not violate the entry/exit criteria.
9684 CS->getCapturedDecl()->setNothrow();
9685 for (int ThisCaptureLevel =
9686 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9687 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9688 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9689 // 1.2.2 OpenMP Language Terminology
9690 // Structured block - An executable statement with a single entry at the
9691 // top and a single exit at the bottom.
9692 // The point of exit cannot be a branch out of the structured block.
9693 // longjmp() and throw() must not violate the entry/exit criteria.
9694 CS->getCapturedDecl()->setNothrow();
9695 }
9696
9697 OMPLoopDirective::HelperExprs B;
9698 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9699 // define the nested loops number.
9700 unsigned NestedLoopCount = checkOpenMPLoop(
9701 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9702 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9703 VarsWithImplicitDSA, B);
9704 if (NestedLoopCount == 0)
9705 return StmtError();
9706
9707 assert((CurContext->isDependentContext() || B.builtAll()) &&
9708 "omp for loop exprs were not built");
9709
9710 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9711 // The grainsize clause and num_tasks clause are mutually exclusive and may
9712 // not appear on the same taskloop directive.
9713 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9714 return StmtError();
9715 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9716 // If a reduction clause is present on the taskloop directive, the nogroup
9717 // clause must not be specified.
9718 if (checkReductionClauseWithNogroup(*this, Clauses))
9719 return StmtError();
9720
9721 setFunctionHasBranchProtectedScope();
9722 return OMPParallelMasterTaskLoopDirective::Create(
9723 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9724}
9725
Alexey Bataev14a388f2019-10-25 10:27:13 -04009726StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9727 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9728 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9729 if (!AStmt)
9730 return StmtError();
9731
9732 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9733 auto *CS = cast<CapturedStmt>(AStmt);
9734 // 1.2.2 OpenMP Language Terminology
9735 // Structured block - An executable statement with a single entry at the
9736 // top and a single exit at the bottom.
9737 // The point of exit cannot be a branch out of the structured block.
9738 // longjmp() and throw() must not violate the entry/exit criteria.
9739 CS->getCapturedDecl()->setNothrow();
9740 for (int ThisCaptureLevel =
9741 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
9742 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9743 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9744 // 1.2.2 OpenMP Language Terminology
9745 // Structured block - An executable statement with a single entry at the
9746 // top and a single exit at the bottom.
9747 // The point of exit cannot be a branch out of the structured block.
9748 // longjmp() and throw() must not violate the entry/exit criteria.
9749 CS->getCapturedDecl()->setNothrow();
9750 }
9751
9752 OMPLoopDirective::HelperExprs B;
9753 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9754 // define the nested loops number.
9755 unsigned NestedLoopCount = checkOpenMPLoop(
9756 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9757 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9758 VarsWithImplicitDSA, B);
9759 if (NestedLoopCount == 0)
9760 return StmtError();
9761
9762 assert((CurContext->isDependentContext() || B.builtAll()) &&
9763 "omp for loop exprs were not built");
9764
9765 if (!CurContext->isDependentContext()) {
9766 // Finalize the clauses that need pre-built expressions for CodeGen.
9767 for (OMPClause *C : Clauses) {
9768 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9769 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9770 B.NumIterations, *this, CurScope,
9771 DSAStack))
9772 return StmtError();
9773 }
9774 }
9775
9776 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9777 // The grainsize clause and num_tasks clause are mutually exclusive and may
9778 // not appear on the same taskloop directive.
9779 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9780 return StmtError();
9781 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9782 // If a reduction clause is present on the taskloop directive, the nogroup
9783 // clause must not be specified.
9784 if (checkReductionClauseWithNogroup(*this, Clauses))
9785 return StmtError();
9786 if (checkSimdlenSafelenSpecified(*this, Clauses))
9787 return StmtError();
9788
9789 setFunctionHasBranchProtectedScope();
9790 return OMPParallelMasterTaskLoopSimdDirective::Create(
9791 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9792}
9793
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009794StmtResult Sema::ActOnOpenMPDistributeDirective(
9795 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009796 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009797 if (!AStmt)
9798 return StmtError();
9799
9800 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9801 OMPLoopDirective::HelperExprs B;
9802 // In presence of clause 'collapse' with number of loops, it will
9803 // define the nested loops number.
9804 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009805 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009806 nullptr /*ordered not a clause on distribute*/, AStmt,
9807 *this, *DSAStack, VarsWithImplicitDSA, B);
9808 if (NestedLoopCount == 0)
9809 return StmtError();
9810
9811 assert((CurContext->isDependentContext() || B.builtAll()) &&
9812 "omp for loop exprs were not built");
9813
Reid Kleckner87a31802018-03-12 21:43:02 +00009814 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009815 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9816 NestedLoopCount, Clauses, AStmt, B);
9817}
9818
Carlo Bertolli9925f152016-06-27 14:55:37 +00009819StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9820 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009821 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009822 if (!AStmt)
9823 return StmtError();
9824
Alexey Bataeve3727102018-04-18 15:57:46 +00009825 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009826 // 1.2.2 OpenMP Language Terminology
9827 // Structured block - An executable statement with a single entry at the
9828 // top and a single exit at the bottom.
9829 // The point of exit cannot be a branch out of the structured block.
9830 // longjmp() and throw() must not violate the entry/exit criteria.
9831 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009832 for (int ThisCaptureLevel =
9833 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9834 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9835 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9836 // 1.2.2 OpenMP Language Terminology
9837 // Structured block - An executable statement with a single entry at the
9838 // top and a single exit at the bottom.
9839 // The point of exit cannot be a branch out of the structured block.
9840 // longjmp() and throw() must not violate the entry/exit criteria.
9841 CS->getCapturedDecl()->setNothrow();
9842 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009843
9844 OMPLoopDirective::HelperExprs B;
9845 // In presence of clause 'collapse' with number of loops, it will
9846 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009847 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009848 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009849 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009850 VarsWithImplicitDSA, B);
9851 if (NestedLoopCount == 0)
9852 return StmtError();
9853
9854 assert((CurContext->isDependentContext() || B.builtAll()) &&
9855 "omp for loop exprs were not built");
9856
Reid Kleckner87a31802018-03-12 21:43:02 +00009857 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00009858 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009859 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9860 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00009861}
9862
Kelvin Li4a39add2016-07-05 05:00:15 +00009863StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9864 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009865 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00009866 if (!AStmt)
9867 return StmtError();
9868
Alexey Bataeve3727102018-04-18 15:57:46 +00009869 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00009870 // 1.2.2 OpenMP Language Terminology
9871 // Structured block - An executable statement with a single entry at the
9872 // top and a single exit at the bottom.
9873 // The point of exit cannot be a branch out of the structured block.
9874 // longjmp() and throw() must not violate the entry/exit criteria.
9875 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00009876 for (int ThisCaptureLevel =
9877 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
9878 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9879 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9880 // 1.2.2 OpenMP Language Terminology
9881 // Structured block - An executable statement with a single entry at the
9882 // top and a single exit at the bottom.
9883 // The point of exit cannot be a branch out of the structured block.
9884 // longjmp() and throw() must not violate the entry/exit criteria.
9885 CS->getCapturedDecl()->setNothrow();
9886 }
Kelvin Li4a39add2016-07-05 05:00:15 +00009887
9888 OMPLoopDirective::HelperExprs B;
9889 // In presence of clause 'collapse' with number of loops, it will
9890 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009891 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00009892 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00009893 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00009894 VarsWithImplicitDSA, B);
9895 if (NestedLoopCount == 0)
9896 return StmtError();
9897
9898 assert((CurContext->isDependentContext() || B.builtAll()) &&
9899 "omp for loop exprs were not built");
9900
Alexey Bataev438388c2017-11-22 18:34:02 +00009901 if (!CurContext->isDependentContext()) {
9902 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009903 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009904 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9905 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9906 B.NumIterations, *this, CurScope,
9907 DSAStack))
9908 return StmtError();
9909 }
9910 }
9911
Kelvin Lic5609492016-07-15 04:39:07 +00009912 if (checkSimdlenSafelenSpecified(*this, Clauses))
9913 return StmtError();
9914
Reid Kleckner87a31802018-03-12 21:43:02 +00009915 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00009916 return OMPDistributeParallelForSimdDirective::Create(
9917 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9918}
9919
Kelvin Li787f3fc2016-07-06 04:45:38 +00009920StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
9921 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009922 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00009923 if (!AStmt)
9924 return StmtError();
9925
Alexey Bataeve3727102018-04-18 15:57:46 +00009926 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009927 // 1.2.2 OpenMP Language Terminology
9928 // Structured block - An executable statement with a single entry at the
9929 // top and a single exit at the bottom.
9930 // The point of exit cannot be a branch out of the structured block.
9931 // longjmp() and throw() must not violate the entry/exit criteria.
9932 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00009933 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
9934 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9935 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9936 // 1.2.2 OpenMP Language Terminology
9937 // Structured block - An executable statement with a single entry at the
9938 // top and a single exit at the bottom.
9939 // The point of exit cannot be a branch out of the structured block.
9940 // longjmp() and throw() must not violate the entry/exit criteria.
9941 CS->getCapturedDecl()->setNothrow();
9942 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00009943
9944 OMPLoopDirective::HelperExprs B;
9945 // In presence of clause 'collapse' with number of loops, it will
9946 // define the nested loops number.
9947 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009948 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00009949 nullptr /*ordered not a clause on distribute*/, CS, *this,
9950 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009951 if (NestedLoopCount == 0)
9952 return StmtError();
9953
9954 assert((CurContext->isDependentContext() || B.builtAll()) &&
9955 "omp for loop exprs were not built");
9956
Alexey Bataev438388c2017-11-22 18:34:02 +00009957 if (!CurContext->isDependentContext()) {
9958 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009959 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009960 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9961 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9962 B.NumIterations, *this, CurScope,
9963 DSAStack))
9964 return StmtError();
9965 }
9966 }
9967
Kelvin Lic5609492016-07-15 04:39:07 +00009968 if (checkSimdlenSafelenSpecified(*this, Clauses))
9969 return StmtError();
9970
Reid Kleckner87a31802018-03-12 21:43:02 +00009971 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00009972 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
9973 NestedLoopCount, Clauses, AStmt, B);
9974}
9975
Kelvin Lia579b912016-07-14 02:54:56 +00009976StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
9977 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009978 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00009979 if (!AStmt)
9980 return StmtError();
9981
Alexey Bataeve3727102018-04-18 15:57:46 +00009982 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00009983 // 1.2.2 OpenMP Language Terminology
9984 // Structured block - An executable statement with a single entry at the
9985 // top and a single exit at the bottom.
9986 // The point of exit cannot be a branch out of the structured block.
9987 // longjmp() and throw() must not violate the entry/exit criteria.
9988 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009989 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9990 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9991 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9992 // 1.2.2 OpenMP Language Terminology
9993 // Structured block - An executable statement with a single entry at the
9994 // top and a single exit at the bottom.
9995 // The point of exit cannot be a branch out of the structured block.
9996 // longjmp() and throw() must not violate the entry/exit criteria.
9997 CS->getCapturedDecl()->setNothrow();
9998 }
Kelvin Lia579b912016-07-14 02:54:56 +00009999
10000 OMPLoopDirective::HelperExprs B;
10001 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10002 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010003 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010004 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010005 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010006 VarsWithImplicitDSA, B);
10007 if (NestedLoopCount == 0)
10008 return StmtError();
10009
10010 assert((CurContext->isDependentContext() || B.builtAll()) &&
10011 "omp target parallel for simd loop exprs were not built");
10012
10013 if (!CurContext->isDependentContext()) {
10014 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010015 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010016 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010017 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10018 B.NumIterations, *this, CurScope,
10019 DSAStack))
10020 return StmtError();
10021 }
10022 }
Kelvin Lic5609492016-07-15 04:39:07 +000010023 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010024 return StmtError();
10025
Reid Kleckner87a31802018-03-12 21:43:02 +000010026 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010027 return OMPTargetParallelForSimdDirective::Create(
10028 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10029}
10030
Kelvin Li986330c2016-07-20 22:57:10 +000010031StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10032 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010033 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010034 if (!AStmt)
10035 return StmtError();
10036
Alexey Bataeve3727102018-04-18 15:57:46 +000010037 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010038 // 1.2.2 OpenMP Language Terminology
10039 // Structured block - An executable statement with a single entry at the
10040 // top and a single exit at the bottom.
10041 // The point of exit cannot be a branch out of the structured block.
10042 // longjmp() and throw() must not violate the entry/exit criteria.
10043 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010044 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_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 }
10054
Kelvin Li986330c2016-07-20 22:57:10 +000010055 OMPLoopDirective::HelperExprs B;
10056 // In presence of clause 'collapse' with number of loops, it will define the
10057 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010058 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010059 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010060 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010061 VarsWithImplicitDSA, B);
10062 if (NestedLoopCount == 0)
10063 return StmtError();
10064
10065 assert((CurContext->isDependentContext() || B.builtAll()) &&
10066 "omp target simd loop exprs were not built");
10067
10068 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) {
David Majnemer9d168222016-08-05 17:44:54 +000010071 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010072 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10073 B.NumIterations, *this, CurScope,
10074 DSAStack))
10075 return StmtError();
10076 }
10077 }
10078
10079 if (checkSimdlenSafelenSpecified(*this, Clauses))
10080 return StmtError();
10081
Reid Kleckner87a31802018-03-12 21:43:02 +000010082 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010083 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10084 NestedLoopCount, Clauses, AStmt, B);
10085}
10086
Kelvin Li02532872016-08-05 14:37:37 +000010087StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10088 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010089 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010090 if (!AStmt)
10091 return StmtError();
10092
Alexey Bataeve3727102018-04-18 15:57:46 +000010093 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +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 Bataev95c6dd42017-11-29 15:14:16 +000010100 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
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 Li02532872016-08-05 14:37:37 +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_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010116 nullptr /*ordered not a clause on distribute*/, CS, *this,
10117 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010118 if (NestedLoopCount == 0)
10119 return StmtError();
10120
10121 assert((CurContext->isDependentContext() || B.builtAll()) &&
10122 "omp teams distribute loop exprs were not built");
10123
Reid Kleckner87a31802018-03-12 21:43:02 +000010124 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010125
10126 DSAStack->setParentTeamsRegionLoc(StartLoc);
10127
David Majnemer9d168222016-08-05 17:44:54 +000010128 return OMPTeamsDistributeDirective::Create(
10129 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010130}
10131
Kelvin Li4e325f72016-10-25 12:50:55 +000010132StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10133 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010134 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010135 if (!AStmt)
10136 return StmtError();
10137
Alexey Bataeve3727102018-04-18 15:57:46 +000010138 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010139 // 1.2.2 OpenMP Language Terminology
10140 // Structured block - An executable statement with a single entry at the
10141 // top and a single exit at the bottom.
10142 // The point of exit cannot be a branch out of the structured block.
10143 // longjmp() and throw() must not violate the entry/exit criteria.
10144 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010145 for (int ThisCaptureLevel =
10146 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10147 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10148 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10149 // 1.2.2 OpenMP Language Terminology
10150 // Structured block - An executable statement with a single entry at the
10151 // top and a single exit at the bottom.
10152 // The point of exit cannot be a branch out of the structured block.
10153 // longjmp() and throw() must not violate the entry/exit criteria.
10154 CS->getCapturedDecl()->setNothrow();
10155 }
10156
Kelvin Li4e325f72016-10-25 12:50:55 +000010157
10158 OMPLoopDirective::HelperExprs B;
10159 // In presence of clause 'collapse' with number of loops, it will
10160 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010161 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010162 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010163 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010164 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010165
10166 if (NestedLoopCount == 0)
10167 return StmtError();
10168
10169 assert((CurContext->isDependentContext() || B.builtAll()) &&
10170 "omp teams distribute simd loop exprs were not built");
10171
10172 if (!CurContext->isDependentContext()) {
10173 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010174 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010175 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10176 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10177 B.NumIterations, *this, CurScope,
10178 DSAStack))
10179 return StmtError();
10180 }
10181 }
10182
10183 if (checkSimdlenSafelenSpecified(*this, Clauses))
10184 return StmtError();
10185
Reid Kleckner87a31802018-03-12 21:43:02 +000010186 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010187
10188 DSAStack->setParentTeamsRegionLoc(StartLoc);
10189
Kelvin Li4e325f72016-10-25 12:50:55 +000010190 return OMPTeamsDistributeSimdDirective::Create(
10191 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10192}
10193
Kelvin Li579e41c2016-11-30 23:51:03 +000010194StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10195 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010196 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010197 if (!AStmt)
10198 return StmtError();
10199
Alexey Bataeve3727102018-04-18 15:57:46 +000010200 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010201 // 1.2.2 OpenMP Language Terminology
10202 // Structured block - An executable statement with a single entry at the
10203 // top and a single exit at the bottom.
10204 // The point of exit cannot be a branch out of the structured block.
10205 // longjmp() and throw() must not violate the entry/exit criteria.
10206 CS->getCapturedDecl()->setNothrow();
10207
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010208 for (int ThisCaptureLevel =
10209 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10210 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10211 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10212 // 1.2.2 OpenMP Language Terminology
10213 // Structured block - An executable statement with a single entry at the
10214 // top and a single exit at the bottom.
10215 // The point of exit cannot be a branch out of the structured block.
10216 // longjmp() and throw() must not violate the entry/exit criteria.
10217 CS->getCapturedDecl()->setNothrow();
10218 }
10219
Kelvin Li579e41c2016-11-30 23:51:03 +000010220 OMPLoopDirective::HelperExprs B;
10221 // In presence of clause 'collapse' with number of loops, it will
10222 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010223 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010224 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010225 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010226 VarsWithImplicitDSA, B);
10227
10228 if (NestedLoopCount == 0)
10229 return StmtError();
10230
10231 assert((CurContext->isDependentContext() || B.builtAll()) &&
10232 "omp for loop exprs were not built");
10233
10234 if (!CurContext->isDependentContext()) {
10235 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010236 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010237 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10238 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10239 B.NumIterations, *this, CurScope,
10240 DSAStack))
10241 return StmtError();
10242 }
10243 }
10244
10245 if (checkSimdlenSafelenSpecified(*this, Clauses))
10246 return StmtError();
10247
Reid Kleckner87a31802018-03-12 21:43:02 +000010248 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010249
10250 DSAStack->setParentTeamsRegionLoc(StartLoc);
10251
Kelvin Li579e41c2016-11-30 23:51:03 +000010252 return OMPTeamsDistributeParallelForSimdDirective::Create(
10253 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10254}
10255
Kelvin Li7ade93f2016-12-09 03:24:30 +000010256StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10257 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010258 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010259 if (!AStmt)
10260 return StmtError();
10261
Alexey Bataeve3727102018-04-18 15:57:46 +000010262 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010263 // 1.2.2 OpenMP Language Terminology
10264 // Structured block - An executable statement with a single entry at the
10265 // top and a single exit at the bottom.
10266 // The point of exit cannot be a branch out of the structured block.
10267 // longjmp() and throw() must not violate the entry/exit criteria.
10268 CS->getCapturedDecl()->setNothrow();
10269
Carlo Bertolli62fae152017-11-20 20:46:39 +000010270 for (int ThisCaptureLevel =
10271 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10272 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10273 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10274 // 1.2.2 OpenMP Language Terminology
10275 // Structured block - An executable statement with a single entry at the
10276 // top and a single exit at the bottom.
10277 // The point of exit cannot be a branch out of the structured block.
10278 // longjmp() and throw() must not violate the entry/exit criteria.
10279 CS->getCapturedDecl()->setNothrow();
10280 }
10281
Kelvin Li7ade93f2016-12-09 03:24:30 +000010282 OMPLoopDirective::HelperExprs B;
10283 // In presence of clause 'collapse' with number of loops, it will
10284 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010285 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010286 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010287 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010288 VarsWithImplicitDSA, B);
10289
10290 if (NestedLoopCount == 0)
10291 return StmtError();
10292
10293 assert((CurContext->isDependentContext() || B.builtAll()) &&
10294 "omp for loop exprs were not built");
10295
Reid Kleckner87a31802018-03-12 21:43:02 +000010296 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010297
10298 DSAStack->setParentTeamsRegionLoc(StartLoc);
10299
Kelvin Li7ade93f2016-12-09 03:24:30 +000010300 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010301 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10302 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010303}
10304
Kelvin Libf594a52016-12-17 05:48:59 +000010305StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10306 Stmt *AStmt,
10307 SourceLocation StartLoc,
10308 SourceLocation EndLoc) {
10309 if (!AStmt)
10310 return StmtError();
10311
Alexey Bataeve3727102018-04-18 15:57:46 +000010312 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010313 // 1.2.2 OpenMP Language Terminology
10314 // Structured block - An executable statement with a single entry at the
10315 // top and a single exit at the bottom.
10316 // The point of exit cannot be a branch out of the structured block.
10317 // longjmp() and throw() must not violate the entry/exit criteria.
10318 CS->getCapturedDecl()->setNothrow();
10319
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010320 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10321 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10322 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10323 // 1.2.2 OpenMP Language Terminology
10324 // Structured block - An executable statement with a single entry at the
10325 // top and a single exit at the bottom.
10326 // The point of exit cannot be a branch out of the structured block.
10327 // longjmp() and throw() must not violate the entry/exit criteria.
10328 CS->getCapturedDecl()->setNothrow();
10329 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010330 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010331
10332 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10333 AStmt);
10334}
10335
Kelvin Li83c451e2016-12-25 04:52:54 +000010336StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10337 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010338 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010339 if (!AStmt)
10340 return StmtError();
10341
Alexey Bataeve3727102018-04-18 15:57:46 +000010342 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010343 // 1.2.2 OpenMP Language Terminology
10344 // Structured block - An executable statement with a single entry at the
10345 // top and a single exit at the bottom.
10346 // The point of exit cannot be a branch out of the structured block.
10347 // longjmp() and throw() must not violate the entry/exit criteria.
10348 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010349 for (int ThisCaptureLevel =
10350 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10351 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10352 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10353 // 1.2.2 OpenMP Language Terminology
10354 // Structured block - An executable statement with a single entry at the
10355 // top and a single exit at the bottom.
10356 // The point of exit cannot be a branch out of the structured block.
10357 // longjmp() and throw() must not violate the entry/exit criteria.
10358 CS->getCapturedDecl()->setNothrow();
10359 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010360
10361 OMPLoopDirective::HelperExprs B;
10362 // In presence of clause 'collapse' with number of loops, it will
10363 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010364 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010365 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10366 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010367 VarsWithImplicitDSA, B);
10368 if (NestedLoopCount == 0)
10369 return StmtError();
10370
10371 assert((CurContext->isDependentContext() || B.builtAll()) &&
10372 "omp target teams distribute loop exprs were not built");
10373
Reid Kleckner87a31802018-03-12 21:43:02 +000010374 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010375 return OMPTargetTeamsDistributeDirective::Create(
10376 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10377}
10378
Kelvin Li80e8f562016-12-29 22:16:30 +000010379StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10380 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010381 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010382 if (!AStmt)
10383 return StmtError();
10384
Alexey Bataeve3727102018-04-18 15:57:46 +000010385 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010386 // 1.2.2 OpenMP Language Terminology
10387 // Structured block - An executable statement with a single entry at the
10388 // top and a single exit at the bottom.
10389 // The point of exit cannot be a branch out of the structured block.
10390 // longjmp() and throw() must not violate the entry/exit criteria.
10391 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010392 for (int ThisCaptureLevel =
10393 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10394 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10395 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10396 // 1.2.2 OpenMP Language Terminology
10397 // Structured block - An executable statement with a single entry at the
10398 // top and a single exit at the bottom.
10399 // The point of exit cannot be a branch out of the structured block.
10400 // longjmp() and throw() must not violate the entry/exit criteria.
10401 CS->getCapturedDecl()->setNothrow();
10402 }
10403
Kelvin Li80e8f562016-12-29 22:16:30 +000010404 OMPLoopDirective::HelperExprs B;
10405 // In presence of clause 'collapse' with number of loops, it will
10406 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010407 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010408 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10409 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010410 VarsWithImplicitDSA, B);
10411 if (NestedLoopCount == 0)
10412 return StmtError();
10413
10414 assert((CurContext->isDependentContext() || B.builtAll()) &&
10415 "omp target teams distribute parallel for loop exprs were not built");
10416
Alexey Bataev647dd842018-01-15 20:59:40 +000010417 if (!CurContext->isDependentContext()) {
10418 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010419 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010420 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10421 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10422 B.NumIterations, *this, CurScope,
10423 DSAStack))
10424 return StmtError();
10425 }
10426 }
10427
Reid Kleckner87a31802018-03-12 21:43:02 +000010428 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010429 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010430 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10431 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010432}
10433
Kelvin Li1851df52017-01-03 05:23:48 +000010434StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10435 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010436 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010437 if (!AStmt)
10438 return StmtError();
10439
Alexey Bataeve3727102018-04-18 15:57:46 +000010440 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010441 // 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();
Alexey Bataev647dd842018-01-15 20:59:40 +000010447 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10448 OMPD_target_teams_distribute_parallel_for_simd);
10449 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10450 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10451 // 1.2.2 OpenMP Language Terminology
10452 // Structured block - An executable statement with a single entry at the
10453 // top and a single exit at the bottom.
10454 // The point of exit cannot be a branch out of the structured block.
10455 // longjmp() and throw() must not violate the entry/exit criteria.
10456 CS->getCapturedDecl()->setNothrow();
10457 }
Kelvin Li1851df52017-01-03 05:23:48 +000010458
10459 OMPLoopDirective::HelperExprs B;
10460 // In presence of clause 'collapse' with number of loops, it will
10461 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010462 unsigned NestedLoopCount =
10463 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010464 getCollapseNumberExpr(Clauses),
10465 nullptr /*ordered not a clause on distribute*/, CS, *this,
10466 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010467 if (NestedLoopCount == 0)
10468 return StmtError();
10469
10470 assert((CurContext->isDependentContext() || B.builtAll()) &&
10471 "omp target teams distribute parallel for simd loop exprs were not "
10472 "built");
10473
10474 if (!CurContext->isDependentContext()) {
10475 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010476 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010477 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10478 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10479 B.NumIterations, *this, CurScope,
10480 DSAStack))
10481 return StmtError();
10482 }
10483 }
10484
Alexey Bataev438388c2017-11-22 18:34:02 +000010485 if (checkSimdlenSafelenSpecified(*this, Clauses))
10486 return StmtError();
10487
Reid Kleckner87a31802018-03-12 21:43:02 +000010488 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010489 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10490 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10491}
10492
Kelvin Lida681182017-01-10 18:08:18 +000010493StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10494 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010495 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010496 if (!AStmt)
10497 return StmtError();
10498
10499 auto *CS = cast<CapturedStmt>(AStmt);
10500 // 1.2.2 OpenMP Language Terminology
10501 // Structured block - An executable statement with a single entry at the
10502 // top and a single exit at the bottom.
10503 // The point of exit cannot be a branch out of the structured block.
10504 // longjmp() and throw() must not violate the entry/exit criteria.
10505 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010506 for (int ThisCaptureLevel =
10507 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10508 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10509 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10510 // 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();
10516 }
Kelvin Lida681182017-01-10 18:08:18 +000010517
10518 OMPLoopDirective::HelperExprs B;
10519 // In presence of clause 'collapse' with number of loops, it will
10520 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010521 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010522 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010523 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010524 VarsWithImplicitDSA, B);
10525 if (NestedLoopCount == 0)
10526 return StmtError();
10527
10528 assert((CurContext->isDependentContext() || B.builtAll()) &&
10529 "omp target teams distribute simd loop exprs were not built");
10530
Alexey Bataev438388c2017-11-22 18:34:02 +000010531 if (!CurContext->isDependentContext()) {
10532 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010533 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010534 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10535 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10536 B.NumIterations, *this, CurScope,
10537 DSAStack))
10538 return StmtError();
10539 }
10540 }
10541
10542 if (checkSimdlenSafelenSpecified(*this, Clauses))
10543 return StmtError();
10544
Reid Kleckner87a31802018-03-12 21:43:02 +000010545 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010546 return OMPTargetTeamsDistributeSimdDirective::Create(
10547 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10548}
10549
Alexey Bataeved09d242014-05-28 05:53:51 +000010550OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010551 SourceLocation StartLoc,
10552 SourceLocation LParenLoc,
10553 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010554 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010555 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010556 case OMPC_final:
10557 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10558 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010559 case OMPC_num_threads:
10560 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10561 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010562 case OMPC_safelen:
10563 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10564 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010565 case OMPC_simdlen:
10566 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10567 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010568 case OMPC_allocator:
10569 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10570 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010571 case OMPC_collapse:
10572 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10573 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010574 case OMPC_ordered:
10575 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10576 break;
Michael Wonge710d542015-08-07 16:16:36 +000010577 case OMPC_device:
10578 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10579 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010580 case OMPC_num_teams:
10581 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10582 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010583 case OMPC_thread_limit:
10584 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10585 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010586 case OMPC_priority:
10587 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10588 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010589 case OMPC_grainsize:
10590 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10591 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010592 case OMPC_num_tasks:
10593 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10594 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010595 case OMPC_hint:
10596 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10597 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010598 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010599 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010600 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010601 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010602 case OMPC_private:
10603 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010604 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010605 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010606 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010607 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010608 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010609 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010610 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010611 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010612 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010613 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010614 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010615 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010616 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010617 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010618 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010619 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010620 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010621 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010622 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010623 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010624 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010625 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010626 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010627 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010628 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010629 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010630 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010631 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010632 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010633 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010634 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010635 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010636 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010637 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010638 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010639 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010640 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010641 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010642 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010643 case OMPC_match:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010644 llvm_unreachable("Clause is not allowed.");
10645 }
10646 return Res;
10647}
10648
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010649// An OpenMP directive such as 'target parallel' has two captured regions:
10650// for the 'target' and 'parallel' respectively. This function returns
10651// the region in which to capture expressions associated with a clause.
10652// A return value of OMPD_unknown signifies that the expression should not
10653// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010654static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
10655 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
10656 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010657 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010658 switch (CKind) {
10659 case OMPC_if:
10660 switch (DKind) {
10661 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010662 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010663 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010664 // If this clause applies to the nested 'parallel' region, capture within
10665 // the 'target' region, otherwise do not capture.
10666 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10667 CaptureRegion = OMPD_target;
10668 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010669 case OMPD_target_teams_distribute_parallel_for:
10670 case OMPD_target_teams_distribute_parallel_for_simd:
10671 // If this clause applies to the nested 'parallel' region, capture within
10672 // the 'teams' region, otherwise do not capture.
10673 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10674 CaptureRegion = OMPD_teams;
10675 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010676 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010677 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010678 CaptureRegion = OMPD_teams;
10679 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010680 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010681 case OMPD_target_enter_data:
10682 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010683 CaptureRegion = OMPD_task;
10684 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010685 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010686 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010687 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10688 CaptureRegion = OMPD_parallel;
10689 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010690 case OMPD_cancel:
10691 case OMPD_parallel:
10692 case OMPD_parallel_sections:
10693 case OMPD_parallel_for:
10694 case OMPD_parallel_for_simd:
10695 case OMPD_target:
10696 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010697 case OMPD_target_teams:
10698 case OMPD_target_teams_distribute:
10699 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010700 case OMPD_distribute_parallel_for:
10701 case OMPD_distribute_parallel_for_simd:
10702 case OMPD_task:
10703 case OMPD_taskloop:
10704 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010705 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010706 case OMPD_master_taskloop_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010707 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050010708 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050010709 case OMPD_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010710 // Do not capture if-clause expressions.
10711 break;
10712 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010713 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010714 case OMPD_taskyield:
10715 case OMPD_barrier:
10716 case OMPD_taskwait:
10717 case OMPD_cancellation_point:
10718 case OMPD_flush:
10719 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010720 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010721 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010722 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010723 case OMPD_declare_target:
10724 case OMPD_end_declare_target:
10725 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010726 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010727 case OMPD_sections:
10728 case OMPD_section:
10729 case OMPD_single:
10730 case OMPD_master:
10731 case OMPD_critical:
10732 case OMPD_taskgroup:
10733 case OMPD_distribute:
10734 case OMPD_ordered:
10735 case OMPD_atomic:
10736 case OMPD_distribute_simd:
10737 case OMPD_teams_distribute:
10738 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010739 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010740 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10741 case OMPD_unknown:
10742 llvm_unreachable("Unknown OpenMP directive");
10743 }
10744 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010745 case OMPC_num_threads:
10746 switch (DKind) {
10747 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010748 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010749 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010750 CaptureRegion = OMPD_target;
10751 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010752 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010753 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010754 case OMPD_target_teams_distribute_parallel_for:
10755 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010756 CaptureRegion = OMPD_teams;
10757 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010758 case OMPD_parallel:
10759 case OMPD_parallel_sections:
10760 case OMPD_parallel_for:
10761 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010762 case OMPD_distribute_parallel_for:
10763 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010764 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010765 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010766 // Do not capture num_threads-clause expressions.
10767 break;
10768 case OMPD_target_data:
10769 case OMPD_target_enter_data:
10770 case OMPD_target_exit_data:
10771 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010772 case OMPD_target:
10773 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010774 case OMPD_target_teams:
10775 case OMPD_target_teams_distribute:
10776 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010777 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010778 case OMPD_task:
10779 case OMPD_taskloop:
10780 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010781 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010782 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010783 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010784 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010785 case OMPD_taskyield:
10786 case OMPD_barrier:
10787 case OMPD_taskwait:
10788 case OMPD_cancellation_point:
10789 case OMPD_flush:
10790 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010791 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010792 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010793 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010794 case OMPD_declare_target:
10795 case OMPD_end_declare_target:
10796 case OMPD_teams:
10797 case OMPD_simd:
10798 case OMPD_for:
10799 case OMPD_for_simd:
10800 case OMPD_sections:
10801 case OMPD_section:
10802 case OMPD_single:
10803 case OMPD_master:
10804 case OMPD_critical:
10805 case OMPD_taskgroup:
10806 case OMPD_distribute:
10807 case OMPD_ordered:
10808 case OMPD_atomic:
10809 case OMPD_distribute_simd:
10810 case OMPD_teams_distribute:
10811 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010812 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010813 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
10814 case OMPD_unknown:
10815 llvm_unreachable("Unknown OpenMP directive");
10816 }
10817 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010818 case OMPC_num_teams:
10819 switch (DKind) {
10820 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010821 case OMPD_target_teams_distribute:
10822 case OMPD_target_teams_distribute_simd:
10823 case OMPD_target_teams_distribute_parallel_for:
10824 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010825 CaptureRegion = OMPD_target;
10826 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010827 case OMPD_teams_distribute_parallel_for:
10828 case OMPD_teams_distribute_parallel_for_simd:
10829 case OMPD_teams:
10830 case OMPD_teams_distribute:
10831 case OMPD_teams_distribute_simd:
10832 // Do not capture num_teams-clause expressions.
10833 break;
10834 case OMPD_distribute_parallel_for:
10835 case OMPD_distribute_parallel_for_simd:
10836 case OMPD_task:
10837 case OMPD_taskloop:
10838 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010839 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010840 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010841 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010842 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010843 case OMPD_target_data:
10844 case OMPD_target_enter_data:
10845 case OMPD_target_exit_data:
10846 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010847 case OMPD_cancel:
10848 case OMPD_parallel:
10849 case OMPD_parallel_sections:
10850 case OMPD_parallel_for:
10851 case OMPD_parallel_for_simd:
10852 case OMPD_target:
10853 case OMPD_target_simd:
10854 case OMPD_target_parallel:
10855 case OMPD_target_parallel_for:
10856 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010857 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010858 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010859 case OMPD_taskyield:
10860 case OMPD_barrier:
10861 case OMPD_taskwait:
10862 case OMPD_cancellation_point:
10863 case OMPD_flush:
10864 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010865 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010866 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010867 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010868 case OMPD_declare_target:
10869 case OMPD_end_declare_target:
10870 case OMPD_simd:
10871 case OMPD_for:
10872 case OMPD_for_simd:
10873 case OMPD_sections:
10874 case OMPD_section:
10875 case OMPD_single:
10876 case OMPD_master:
10877 case OMPD_critical:
10878 case OMPD_taskgroup:
10879 case OMPD_distribute:
10880 case OMPD_ordered:
10881 case OMPD_atomic:
10882 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010883 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010884 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10885 case OMPD_unknown:
10886 llvm_unreachable("Unknown OpenMP directive");
10887 }
10888 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010889 case OMPC_thread_limit:
10890 switch (DKind) {
10891 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010892 case OMPD_target_teams_distribute:
10893 case OMPD_target_teams_distribute_simd:
10894 case OMPD_target_teams_distribute_parallel_for:
10895 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010896 CaptureRegion = OMPD_target;
10897 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010898 case OMPD_teams_distribute_parallel_for:
10899 case OMPD_teams_distribute_parallel_for_simd:
10900 case OMPD_teams:
10901 case OMPD_teams_distribute:
10902 case OMPD_teams_distribute_simd:
10903 // Do not capture thread_limit-clause expressions.
10904 break;
10905 case OMPD_distribute_parallel_for:
10906 case OMPD_distribute_parallel_for_simd:
10907 case OMPD_task:
10908 case OMPD_taskloop:
10909 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010910 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010911 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010912 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010913 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010914 case OMPD_target_data:
10915 case OMPD_target_enter_data:
10916 case OMPD_target_exit_data:
10917 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010918 case OMPD_cancel:
10919 case OMPD_parallel:
10920 case OMPD_parallel_sections:
10921 case OMPD_parallel_for:
10922 case OMPD_parallel_for_simd:
10923 case OMPD_target:
10924 case OMPD_target_simd:
10925 case OMPD_target_parallel:
10926 case OMPD_target_parallel_for:
10927 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010928 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010929 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010930 case OMPD_taskyield:
10931 case OMPD_barrier:
10932 case OMPD_taskwait:
10933 case OMPD_cancellation_point:
10934 case OMPD_flush:
10935 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010936 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010937 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010938 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010939 case OMPD_declare_target:
10940 case OMPD_end_declare_target:
10941 case OMPD_simd:
10942 case OMPD_for:
10943 case OMPD_for_simd:
10944 case OMPD_sections:
10945 case OMPD_section:
10946 case OMPD_single:
10947 case OMPD_master:
10948 case OMPD_critical:
10949 case OMPD_taskgroup:
10950 case OMPD_distribute:
10951 case OMPD_ordered:
10952 case OMPD_atomic:
10953 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010954 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010955 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
10956 case OMPD_unknown:
10957 llvm_unreachable("Unknown OpenMP directive");
10958 }
10959 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010960 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010961 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000010962 case OMPD_parallel_for:
10963 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010964 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000010965 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010966 case OMPD_teams_distribute_parallel_for:
10967 case OMPD_teams_distribute_parallel_for_simd:
10968 case OMPD_target_parallel_for:
10969 case OMPD_target_parallel_for_simd:
10970 case OMPD_target_teams_distribute_parallel_for:
10971 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010972 CaptureRegion = OMPD_parallel;
10973 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010974 case OMPD_for:
10975 case OMPD_for_simd:
10976 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010977 break;
10978 case OMPD_task:
10979 case OMPD_taskloop:
10980 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010981 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010982 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010983 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010984 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010985 case OMPD_target_data:
10986 case OMPD_target_enter_data:
10987 case OMPD_target_exit_data:
10988 case OMPD_target_update:
10989 case OMPD_teams:
10990 case OMPD_teams_distribute:
10991 case OMPD_teams_distribute_simd:
10992 case OMPD_target_teams_distribute:
10993 case OMPD_target_teams_distribute_simd:
10994 case OMPD_target:
10995 case OMPD_target_simd:
10996 case OMPD_target_parallel:
10997 case OMPD_cancel:
10998 case OMPD_parallel:
10999 case OMPD_parallel_sections:
11000 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011001 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011002 case OMPD_taskyield:
11003 case OMPD_barrier:
11004 case OMPD_taskwait:
11005 case OMPD_cancellation_point:
11006 case OMPD_flush:
11007 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011008 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011009 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011010 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011011 case OMPD_declare_target:
11012 case OMPD_end_declare_target:
11013 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011014 case OMPD_sections:
11015 case OMPD_section:
11016 case OMPD_single:
11017 case OMPD_master:
11018 case OMPD_critical:
11019 case OMPD_taskgroup:
11020 case OMPD_distribute:
11021 case OMPD_ordered:
11022 case OMPD_atomic:
11023 case OMPD_distribute_simd:
11024 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011025 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011026 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11027 case OMPD_unknown:
11028 llvm_unreachable("Unknown OpenMP directive");
11029 }
11030 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011031 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011032 switch (DKind) {
11033 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011034 case OMPD_teams_distribute_parallel_for_simd:
11035 case OMPD_teams_distribute:
11036 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011037 case OMPD_target_teams_distribute_parallel_for:
11038 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011039 case OMPD_target_teams_distribute:
11040 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011041 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011042 break;
11043 case OMPD_distribute_parallel_for:
11044 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011045 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011046 case OMPD_distribute_simd:
11047 // Do not capture thread_limit-clause expressions.
11048 break;
11049 case OMPD_parallel_for:
11050 case OMPD_parallel_for_simd:
11051 case OMPD_target_parallel_for_simd:
11052 case OMPD_target_parallel_for:
11053 case OMPD_task:
11054 case OMPD_taskloop:
11055 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011056 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011057 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011058 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011059 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011060 case OMPD_target_data:
11061 case OMPD_target_enter_data:
11062 case OMPD_target_exit_data:
11063 case OMPD_target_update:
11064 case OMPD_teams:
11065 case OMPD_target:
11066 case OMPD_target_simd:
11067 case OMPD_target_parallel:
11068 case OMPD_cancel:
11069 case OMPD_parallel:
11070 case OMPD_parallel_sections:
11071 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011072 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011073 case OMPD_taskyield:
11074 case OMPD_barrier:
11075 case OMPD_taskwait:
11076 case OMPD_cancellation_point:
11077 case OMPD_flush:
11078 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011079 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011080 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011081 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011082 case OMPD_declare_target:
11083 case OMPD_end_declare_target:
11084 case OMPD_simd:
11085 case OMPD_for:
11086 case OMPD_for_simd:
11087 case OMPD_sections:
11088 case OMPD_section:
11089 case OMPD_single:
11090 case OMPD_master:
11091 case OMPD_critical:
11092 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011093 case OMPD_ordered:
11094 case OMPD_atomic:
11095 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011096 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011097 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11098 case OMPD_unknown:
11099 llvm_unreachable("Unknown OpenMP directive");
11100 }
11101 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011102 case OMPC_device:
11103 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011104 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011105 case OMPD_target_enter_data:
11106 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011107 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011108 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011109 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011110 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011111 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011112 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011113 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011114 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011115 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011116 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011117 CaptureRegion = OMPD_task;
11118 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011119 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011120 // Do not capture device-clause expressions.
11121 break;
11122 case OMPD_teams_distribute_parallel_for:
11123 case OMPD_teams_distribute_parallel_for_simd:
11124 case OMPD_teams:
11125 case OMPD_teams_distribute:
11126 case OMPD_teams_distribute_simd:
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_cancel:
11137 case OMPD_parallel:
11138 case OMPD_parallel_sections:
11139 case OMPD_parallel_for:
11140 case OMPD_parallel_for_simd:
11141 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011142 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011143 case OMPD_taskyield:
11144 case OMPD_barrier:
11145 case OMPD_taskwait:
11146 case OMPD_cancellation_point:
11147 case OMPD_flush:
11148 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011149 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011150 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011151 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011152 case OMPD_declare_target:
11153 case OMPD_end_declare_target:
11154 case OMPD_simd:
11155 case OMPD_for:
11156 case OMPD_for_simd:
11157 case OMPD_sections:
11158 case OMPD_section:
11159 case OMPD_single:
11160 case OMPD_master:
11161 case OMPD_critical:
11162 case OMPD_taskgroup:
11163 case OMPD_distribute:
11164 case OMPD_ordered:
11165 case OMPD_atomic:
11166 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011167 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011168 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11169 case OMPD_unknown:
11170 llvm_unreachable("Unknown OpenMP directive");
11171 }
11172 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011173 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011174 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011175 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011176 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011177 switch (DKind) {
11178 case OMPD_task:
11179 case OMPD_taskloop:
11180 case OMPD_taskloop_simd:
11181 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011182 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011183 break;
11184 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011185 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011186 CaptureRegion = OMPD_parallel;
11187 break;
11188 case OMPD_target_update:
11189 case OMPD_target_enter_data:
11190 case OMPD_target_exit_data:
11191 case OMPD_target:
11192 case OMPD_target_simd:
11193 case OMPD_target_teams:
11194 case OMPD_target_parallel:
11195 case OMPD_target_teams_distribute:
11196 case OMPD_target_teams_distribute_simd:
11197 case OMPD_target_parallel_for:
11198 case OMPD_target_parallel_for_simd:
11199 case OMPD_target_teams_distribute_parallel_for:
11200 case OMPD_target_teams_distribute_parallel_for_simd:
11201 case OMPD_target_data:
11202 case OMPD_teams_distribute_parallel_for:
11203 case OMPD_teams_distribute_parallel_for_simd:
11204 case OMPD_teams:
11205 case OMPD_teams_distribute:
11206 case OMPD_teams_distribute_simd:
11207 case OMPD_distribute_parallel_for:
11208 case OMPD_distribute_parallel_for_simd:
11209 case OMPD_cancel:
11210 case OMPD_parallel:
11211 case OMPD_parallel_sections:
11212 case OMPD_parallel_for:
11213 case OMPD_parallel_for_simd:
11214 case OMPD_threadprivate:
11215 case OMPD_allocate:
11216 case OMPD_taskyield:
11217 case OMPD_barrier:
11218 case OMPD_taskwait:
11219 case OMPD_cancellation_point:
11220 case OMPD_flush:
11221 case OMPD_declare_reduction:
11222 case OMPD_declare_mapper:
11223 case OMPD_declare_simd:
11224 case OMPD_declare_variant:
11225 case OMPD_declare_target:
11226 case OMPD_end_declare_target:
11227 case OMPD_simd:
11228 case OMPD_for:
11229 case OMPD_for_simd:
11230 case OMPD_sections:
11231 case OMPD_section:
11232 case OMPD_single:
11233 case OMPD_master:
11234 case OMPD_critical:
11235 case OMPD_taskgroup:
11236 case OMPD_distribute:
11237 case OMPD_ordered:
11238 case OMPD_atomic:
11239 case OMPD_distribute_simd:
11240 case OMPD_requires:
11241 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11242 case OMPD_unknown:
11243 llvm_unreachable("Unknown OpenMP directive");
11244 }
11245 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011246 case OMPC_firstprivate:
11247 case OMPC_lastprivate:
11248 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011249 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011250 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011251 case OMPC_linear:
11252 case OMPC_default:
11253 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011254 case OMPC_safelen:
11255 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011256 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011257 case OMPC_collapse:
11258 case OMPC_private:
11259 case OMPC_shared:
11260 case OMPC_aligned:
11261 case OMPC_copyin:
11262 case OMPC_copyprivate:
11263 case OMPC_ordered:
11264 case OMPC_nowait:
11265 case OMPC_untied:
11266 case OMPC_mergeable:
11267 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011268 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011269 case OMPC_flush:
11270 case OMPC_read:
11271 case OMPC_write:
11272 case OMPC_update:
11273 case OMPC_capture:
11274 case OMPC_seq_cst:
11275 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011276 case OMPC_threads:
11277 case OMPC_simd:
11278 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011279 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011280 case OMPC_hint:
11281 case OMPC_defaultmap:
11282 case OMPC_unknown:
11283 case OMPC_uniform:
11284 case OMPC_to:
11285 case OMPC_from:
11286 case OMPC_use_device_ptr:
11287 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011288 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011289 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011290 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011291 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011292 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011293 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011294 case OMPC_match:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011295 llvm_unreachable("Unexpected OpenMP clause.");
11296 }
11297 return CaptureRegion;
11298}
11299
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011300OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11301 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011302 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011303 SourceLocation NameModifierLoc,
11304 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011305 SourceLocation EndLoc) {
11306 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011307 Stmt *HelperValStmt = nullptr;
11308 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011309 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11310 !Condition->isInstantiationDependent() &&
11311 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011312 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011313 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011314 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011315
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011316 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011317
11318 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11319 CaptureRegion =
11320 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011321 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011322 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011323 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011324 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11325 HelperValStmt = buildPreInits(Context, Captures);
11326 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011327 }
11328
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011329 return new (Context)
11330 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11331 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011332}
11333
Alexey Bataev3778b602014-07-17 07:32:53 +000011334OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11335 SourceLocation StartLoc,
11336 SourceLocation LParenLoc,
11337 SourceLocation EndLoc) {
11338 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011339 Stmt *HelperValStmt = nullptr;
11340 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011341 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11342 !Condition->isInstantiationDependent() &&
11343 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011344 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011345 if (Val.isInvalid())
11346 return nullptr;
11347
Richard Smith03a4aa32016-06-23 19:02:52 +000011348 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011349
11350 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11351 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_final);
11352 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11353 ValExpr = MakeFullExpr(ValExpr).get();
11354 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11355 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11356 HelperValStmt = buildPreInits(Context, Captures);
11357 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011358 }
11359
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011360 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11361 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011362}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011363
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011364ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11365 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011366 if (!Op)
11367 return ExprError();
11368
11369 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11370 public:
11371 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011372 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011373 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11374 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011375 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11376 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011377 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11378 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011379 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11380 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011381 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11382 QualType T,
11383 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011384 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11385 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011386 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11387 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011388 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011389 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011390 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011391 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11392 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011393 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11394 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011395 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11396 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011397 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011398 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011399 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011400 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11401 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011402 llvm_unreachable("conversion functions are permitted");
11403 }
11404 } ConvertDiagnoser;
11405 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11406}
11407
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011408static bool
11409isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11410 bool StrictlyPositive, bool BuildCapture = false,
11411 OpenMPDirectiveKind DKind = OMPD_unknown,
11412 OpenMPDirectiveKind *CaptureRegion = nullptr,
11413 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011414 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11415 !ValExpr->isInstantiationDependent()) {
11416 SourceLocation Loc = ValExpr->getExprLoc();
11417 ExprResult Value =
11418 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11419 if (Value.isInvalid())
11420 return false;
11421
11422 ValExpr = Value.get();
11423 // The expression must evaluate to a non-negative integer value.
11424 llvm::APSInt Result;
11425 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011426 Result.isSigned() &&
11427 !((!StrictlyPositive && Result.isNonNegative()) ||
11428 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011429 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011430 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11431 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011432 return false;
11433 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011434 if (!BuildCapture)
11435 return true;
11436 *CaptureRegion = getOpenMPCaptureRegionForClause(DKind, CKind);
11437 if (*CaptureRegion != OMPD_unknown &&
11438 !SemaRef.CurContext->isDependentContext()) {
11439 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11440 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11441 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11442 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11443 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011444 }
11445 return true;
11446}
11447
Alexey Bataev568a8332014-03-06 06:15:19 +000011448OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11449 SourceLocation StartLoc,
11450 SourceLocation LParenLoc,
11451 SourceLocation EndLoc) {
11452 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011453 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011454
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011455 // OpenMP [2.5, Restrictions]
11456 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011457 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011458 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011459 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011460
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011461 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011462 OpenMPDirectiveKind CaptureRegion =
11463 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
11464 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011465 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011466 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011467 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11468 HelperValStmt = buildPreInits(Context, Captures);
11469 }
11470
11471 return new (Context) OMPNumThreadsClause(
11472 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011473}
11474
Alexey Bataev62c87d22014-03-21 04:51:18 +000011475ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011476 OpenMPClauseKind CKind,
11477 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011478 if (!E)
11479 return ExprError();
11480 if (E->isValueDependent() || E->isTypeDependent() ||
11481 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011482 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011483 llvm::APSInt Result;
11484 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11485 if (ICE.isInvalid())
11486 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011487 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11488 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011489 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011490 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11491 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011492 return ExprError();
11493 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011494 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11495 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11496 << E->getSourceRange();
11497 return ExprError();
11498 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011499 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11500 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011501 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011502 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011503 return ICE;
11504}
11505
11506OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11507 SourceLocation LParenLoc,
11508 SourceLocation EndLoc) {
11509 // OpenMP [2.8.1, simd construct, Description]
11510 // The parameter of the safelen clause must be a constant
11511 // positive integer expression.
11512 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11513 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011514 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011515 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011516 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011517}
11518
Alexey Bataev66b15b52015-08-21 11:14:16 +000011519OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11520 SourceLocation LParenLoc,
11521 SourceLocation EndLoc) {
11522 // OpenMP [2.8.1, simd construct, Description]
11523 // The parameter of the simdlen clause must be a constant
11524 // positive integer expression.
11525 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11526 if (Simdlen.isInvalid())
11527 return nullptr;
11528 return new (Context)
11529 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11530}
11531
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011532/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011533static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11534 DSAStackTy *Stack) {
11535 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011536 if (!OMPAllocatorHandleT.isNull())
11537 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011538 // Build the predefined allocator expressions.
11539 bool ErrorFound = false;
11540 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11541 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11542 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11543 StringRef Allocator =
11544 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11545 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11546 auto *VD = dyn_cast_or_null<ValueDecl>(
11547 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11548 if (!VD) {
11549 ErrorFound = true;
11550 break;
11551 }
11552 QualType AllocatorType =
11553 VD->getType().getNonLValueExprType(S.getASTContext());
11554 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11555 if (!Res.isUsable()) {
11556 ErrorFound = true;
11557 break;
11558 }
11559 if (OMPAllocatorHandleT.isNull())
11560 OMPAllocatorHandleT = AllocatorType;
11561 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11562 ErrorFound = true;
11563 break;
11564 }
11565 Stack->setAllocator(AllocatorKind, Res.get());
11566 }
11567 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011568 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11569 return false;
11570 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011571 OMPAllocatorHandleT.addConst();
11572 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011573 return true;
11574}
11575
11576OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11577 SourceLocation LParenLoc,
11578 SourceLocation EndLoc) {
11579 // OpenMP [2.11.3, allocate Directive, Description]
11580 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011581 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011582 return nullptr;
11583
11584 ExprResult Allocator = DefaultLvalueConversion(A);
11585 if (Allocator.isInvalid())
11586 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011587 Allocator = PerformImplicitConversion(Allocator.get(),
11588 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011589 Sema::AA_Initializing,
11590 /*AllowExplicit=*/true);
11591 if (Allocator.isInvalid())
11592 return nullptr;
11593 return new (Context)
11594 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11595}
11596
Alexander Musman64d33f12014-06-04 07:53:32 +000011597OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11598 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011599 SourceLocation LParenLoc,
11600 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011601 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011602 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011603 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011604 // The parameter of the collapse clause must be a constant
11605 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011606 ExprResult NumForLoopsResult =
11607 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11608 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011609 return nullptr;
11610 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011611 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011612}
11613
Alexey Bataev10e775f2015-07-30 11:36:16 +000011614OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11615 SourceLocation EndLoc,
11616 SourceLocation LParenLoc,
11617 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011618 // OpenMP [2.7.1, loop construct, Description]
11619 // OpenMP [2.8.1, simd construct, Description]
11620 // OpenMP [2.9.6, distribute construct, Description]
11621 // The parameter of the ordered clause must be a constant
11622 // positive integer expression if any.
11623 if (NumForLoops && LParenLoc.isValid()) {
11624 ExprResult NumForLoopsResult =
11625 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11626 if (NumForLoopsResult.isInvalid())
11627 return nullptr;
11628 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011629 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011630 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011631 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011632 auto *Clause = OMPOrderedClause::Create(
11633 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11634 StartLoc, LParenLoc, EndLoc);
11635 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11636 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011637}
11638
Alexey Bataeved09d242014-05-28 05:53:51 +000011639OMPClause *Sema::ActOnOpenMPSimpleClause(
11640 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11641 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011642 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011643 switch (Kind) {
11644 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011645 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011646 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11647 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011648 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011649 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000011650 Res = ActOnOpenMPProcBindClause(
11651 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
11652 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011653 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011654 case OMPC_atomic_default_mem_order:
11655 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11656 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11657 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11658 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011659 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011660 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011661 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011662 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011663 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011664 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011665 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011666 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011667 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011668 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011669 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011670 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011671 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011672 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011673 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011674 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011675 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011676 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011677 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011678 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011679 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011680 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011681 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011682 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011683 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011684 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011685 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011686 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011687 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011688 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011689 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011690 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011691 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011692 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011693 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011694 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011695 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011696 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011697 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011698 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011699 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011700 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011701 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011702 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011703 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011704 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011705 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011706 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011707 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011708 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011709 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011710 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011711 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011712 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011713 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011714 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011715 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011716 llvm_unreachable("Clause is not allowed.");
11717 }
11718 return Res;
11719}
11720
Alexey Bataev6402bca2015-12-28 07:25:51 +000011721static std::string
11722getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11723 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011724 SmallString<256> Buffer;
11725 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011726 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11727 unsigned Skipped = Exclude.size();
11728 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011729 for (unsigned I = First; I < Last; ++I) {
11730 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011731 --Skipped;
11732 continue;
11733 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011734 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11735 if (I == Bound - Skipped)
11736 Out << " or ";
11737 else if (I != Bound + 1 - Skipped)
11738 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011739 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011740 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011741}
11742
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011743OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11744 SourceLocation KindKwLoc,
11745 SourceLocation StartLoc,
11746 SourceLocation LParenLoc,
11747 SourceLocation EndLoc) {
11748 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011749 static_assert(OMPC_DEFAULT_unknown > 0,
11750 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011751 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011752 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11753 /*Last=*/OMPC_DEFAULT_unknown)
11754 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011755 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011756 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011757 switch (Kind) {
11758 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011759 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011760 break;
11761 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011762 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011763 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011764 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011765 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011766 break;
11767 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011768 return new (Context)
11769 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011770}
11771
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011772OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11773 SourceLocation KindKwLoc,
11774 SourceLocation StartLoc,
11775 SourceLocation LParenLoc,
11776 SourceLocation EndLoc) {
11777 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011778 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011779 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11780 /*Last=*/OMPC_PROC_BIND_unknown)
11781 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011782 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011783 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011784 return new (Context)
11785 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011786}
11787
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011788OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11789 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11790 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11791 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11792 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11793 << getListOfPossibleValues(
11794 OMPC_atomic_default_mem_order, /*First=*/0,
11795 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11796 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11797 return nullptr;
11798 }
11799 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11800 LParenLoc, EndLoc);
11801}
11802
Alexey Bataev56dafe82014-06-20 07:16:17 +000011803OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011804 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011805 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011806 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011807 SourceLocation EndLoc) {
11808 OMPClause *Res = nullptr;
11809 switch (Kind) {
11810 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011811 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11812 assert(Argument.size() == NumberOfElements &&
11813 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011814 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011815 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11816 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11817 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11818 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11819 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011820 break;
11821 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011822 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
11823 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11824 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11825 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011826 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011827 case OMPC_dist_schedule:
11828 Res = ActOnOpenMPDistScheduleClause(
11829 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11830 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11831 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011832 case OMPC_defaultmap:
11833 enum { Modifier, DefaultmapKind };
11834 Res = ActOnOpenMPDefaultmapClause(
11835 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11836 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000011837 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11838 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011839 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000011840 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011841 case OMPC_num_threads:
11842 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011843 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011844 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011845 case OMPC_collapse:
11846 case OMPC_default:
11847 case OMPC_proc_bind:
11848 case OMPC_private:
11849 case OMPC_firstprivate:
11850 case OMPC_lastprivate:
11851 case OMPC_shared:
11852 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011853 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011854 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011855 case OMPC_linear:
11856 case OMPC_aligned:
11857 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011858 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011859 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011860 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011861 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011862 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011863 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011864 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011865 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011866 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011867 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011868 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011869 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011870 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011871 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011872 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011873 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011874 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011875 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011876 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011877 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011878 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011879 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011880 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011881 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011882 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011883 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011884 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011885 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011886 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011887 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011888 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011889 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011890 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011891 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011892 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011893 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011894 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011895 case OMPC_match:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011896 llvm_unreachable("Clause is not allowed.");
11897 }
11898 return Res;
11899}
11900
Alexey Bataev6402bca2015-12-28 07:25:51 +000011901static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
11902 OpenMPScheduleClauseModifier M2,
11903 SourceLocation M1Loc, SourceLocation M2Loc) {
11904 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
11905 SmallVector<unsigned, 2> Excluded;
11906 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
11907 Excluded.push_back(M2);
11908 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
11909 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
11910 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
11911 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
11912 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
11913 << getListOfPossibleValues(OMPC_schedule,
11914 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
11915 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11916 Excluded)
11917 << getOpenMPClauseName(OMPC_schedule);
11918 return true;
11919 }
11920 return false;
11921}
11922
Alexey Bataev56dafe82014-06-20 07:16:17 +000011923OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011924 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011925 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011926 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11927 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
11928 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
11929 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
11930 return nullptr;
11931 // OpenMP, 2.7.1, Loop Construct, Restrictions
11932 // Either the monotonic modifier or the nonmonotonic modifier can be specified
11933 // but not both.
11934 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
11935 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
11936 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
11937 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
11938 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
11939 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
11940 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
11941 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
11942 return nullptr;
11943 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011944 if (Kind == OMPC_SCHEDULE_unknown) {
11945 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000011946 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
11947 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
11948 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11949 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11950 Exclude);
11951 } else {
11952 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11953 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011954 }
11955 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11956 << Values << getOpenMPClauseName(OMPC_schedule);
11957 return nullptr;
11958 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000011959 // OpenMP, 2.7.1, Loop Construct, Restrictions
11960 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
11961 // schedule(guided).
11962 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
11963 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
11964 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
11965 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
11966 diag::err_omp_schedule_nonmonotonic_static);
11967 return nullptr;
11968 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011969 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011970 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000011971 if (ChunkSize) {
11972 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11973 !ChunkSize->isInstantiationDependent() &&
11974 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011975 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000011976 ExprResult Val =
11977 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11978 if (Val.isInvalid())
11979 return nullptr;
11980
11981 ValExpr = Val.get();
11982
11983 // OpenMP [2.7.1, Restrictions]
11984 // chunk_size must be a loop invariant integer expression with a positive
11985 // value.
11986 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000011987 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11988 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11989 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011990 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000011991 return nullptr;
11992 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000011993 } else if (getOpenMPCaptureRegionForClause(
11994 DSAStack->getCurrentDirective(), OMPC_schedule) !=
11995 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011996 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011997 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011998 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000011999 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12000 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012001 }
12002 }
12003 }
12004
Alexey Bataev6402bca2015-12-28 07:25:51 +000012005 return new (Context)
12006 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012007 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012008}
12009
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012010OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12011 SourceLocation StartLoc,
12012 SourceLocation EndLoc) {
12013 OMPClause *Res = nullptr;
12014 switch (Kind) {
12015 case OMPC_ordered:
12016 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12017 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012018 case OMPC_nowait:
12019 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12020 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012021 case OMPC_untied:
12022 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12023 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012024 case OMPC_mergeable:
12025 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12026 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012027 case OMPC_read:
12028 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12029 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012030 case OMPC_write:
12031 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12032 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012033 case OMPC_update:
12034 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12035 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012036 case OMPC_capture:
12037 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12038 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012039 case OMPC_seq_cst:
12040 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12041 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012042 case OMPC_threads:
12043 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12044 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012045 case OMPC_simd:
12046 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12047 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012048 case OMPC_nogroup:
12049 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12050 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012051 case OMPC_unified_address:
12052 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12053 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012054 case OMPC_unified_shared_memory:
12055 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12056 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012057 case OMPC_reverse_offload:
12058 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12059 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012060 case OMPC_dynamic_allocators:
12061 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12062 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012063 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012064 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012065 case OMPC_num_threads:
12066 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012067 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012068 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012069 case OMPC_collapse:
12070 case OMPC_schedule:
12071 case OMPC_private:
12072 case OMPC_firstprivate:
12073 case OMPC_lastprivate:
12074 case OMPC_shared:
12075 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012076 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012077 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012078 case OMPC_linear:
12079 case OMPC_aligned:
12080 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012081 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012082 case OMPC_default:
12083 case OMPC_proc_bind:
12084 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012085 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012086 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012087 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012088 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012089 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012090 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012091 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012092 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012093 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012094 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012095 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012096 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012097 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012098 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012099 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012100 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012101 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012102 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012103 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012104 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012105 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012106 case OMPC_match:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012107 llvm_unreachable("Clause is not allowed.");
12108 }
12109 return Res;
12110}
12111
Alexey Bataev236070f2014-06-20 11:19:47 +000012112OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12113 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012114 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012115 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12116}
12117
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012118OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12119 SourceLocation EndLoc) {
12120 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12121}
12122
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012123OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12124 SourceLocation EndLoc) {
12125 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12126}
12127
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012128OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12129 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012130 return new (Context) OMPReadClause(StartLoc, EndLoc);
12131}
12132
Alexey Bataevdea47612014-07-23 07:46:59 +000012133OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12134 SourceLocation EndLoc) {
12135 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12136}
12137
Alexey Bataev67a4f222014-07-23 10:25:33 +000012138OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12139 SourceLocation EndLoc) {
12140 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12141}
12142
Alexey Bataev459dec02014-07-24 06:46:57 +000012143OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12144 SourceLocation EndLoc) {
12145 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12146}
12147
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012148OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12149 SourceLocation EndLoc) {
12150 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12151}
12152
Alexey Bataev346265e2015-09-25 10:37:12 +000012153OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12154 SourceLocation EndLoc) {
12155 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12156}
12157
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012158OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12159 SourceLocation EndLoc) {
12160 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12161}
12162
Alexey Bataevb825de12015-12-07 10:51:44 +000012163OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12164 SourceLocation EndLoc) {
12165 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12166}
12167
Kelvin Li1408f912018-09-26 04:28:39 +000012168OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12169 SourceLocation EndLoc) {
12170 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12171}
12172
Patrick Lyster4a370b92018-10-01 13:47:43 +000012173OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12174 SourceLocation EndLoc) {
12175 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12176}
12177
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012178OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12179 SourceLocation EndLoc) {
12180 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12181}
12182
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012183OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12184 SourceLocation EndLoc) {
12185 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12186}
12187
Alexey Bataevc5e02582014-06-16 07:08:35 +000012188OMPClause *Sema::ActOnOpenMPVarListClause(
12189 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012190 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12191 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
12192 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000012193 OpenMPLinearClauseKind LinKind,
12194 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012195 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
12196 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
12197 SourceLocation StartLoc = Locs.StartLoc;
12198 SourceLocation LParenLoc = Locs.LParenLoc;
12199 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012200 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012201 switch (Kind) {
12202 case OMPC_private:
12203 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12204 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012205 case OMPC_firstprivate:
12206 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12207 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012208 case OMPC_lastprivate:
12209 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12210 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012211 case OMPC_shared:
12212 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12213 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012214 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012215 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012216 EndLoc, ReductionOrMapperIdScopeSpec,
12217 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012218 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012219 case OMPC_task_reduction:
12220 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012221 EndLoc, ReductionOrMapperIdScopeSpec,
12222 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012223 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012224 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012225 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12226 EndLoc, ReductionOrMapperIdScopeSpec,
12227 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012228 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012229 case OMPC_linear:
12230 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012231 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012232 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012233 case OMPC_aligned:
12234 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12235 ColonLoc, EndLoc);
12236 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012237 case OMPC_copyin:
12238 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12239 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012240 case OMPC_copyprivate:
12241 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12242 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012243 case OMPC_flush:
12244 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12245 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012246 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000012247 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012248 StartLoc, LParenLoc, EndLoc);
12249 break;
12250 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012251 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
12252 ReductionOrMapperIdScopeSpec,
12253 ReductionOrMapperId, MapType, IsMapTypeImplicit,
12254 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012255 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012256 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012257 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12258 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012259 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012260 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012261 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12262 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012263 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012264 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012265 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012266 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012267 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012268 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012269 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012270 case OMPC_allocate:
12271 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12272 ColonLoc, EndLoc);
12273 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012274 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012275 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012276 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012277 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012278 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012279 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012280 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012281 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012282 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012283 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012284 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012285 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012286 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012287 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012288 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012289 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012290 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012291 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012292 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012293 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012294 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012295 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012296 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012297 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012298 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012299 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012300 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012301 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012302 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012303 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012304 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012305 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012306 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012307 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012308 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012309 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012310 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012311 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012312 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012313 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012314 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012315 llvm_unreachable("Clause is not allowed.");
12316 }
12317 return Res;
12318}
12319
Alexey Bataev90c228f2016-02-08 09:29:13 +000012320ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012321 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012322 ExprResult Res = BuildDeclRefExpr(
12323 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12324 if (!Res.isUsable())
12325 return ExprError();
12326 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12327 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12328 if (!Res.isUsable())
12329 return ExprError();
12330 }
12331 if (VK != VK_LValue && Res.get()->isGLValue()) {
12332 Res = DefaultLvalueConversion(Res.get());
12333 if (!Res.isUsable())
12334 return ExprError();
12335 }
12336 return Res;
12337}
12338
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012339OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12340 SourceLocation StartLoc,
12341 SourceLocation LParenLoc,
12342 SourceLocation EndLoc) {
12343 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012344 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012345 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012346 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012347 SourceLocation ELoc;
12348 SourceRange ERange;
12349 Expr *SimpleRefExpr = RefExpr;
12350 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012351 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012352 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012353 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012354 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012355 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012356 ValueDecl *D = Res.first;
12357 if (!D)
12358 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012359
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012360 QualType Type = D->getType();
12361 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012362
12363 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12364 // A variable that appears in a private clause must not have an incomplete
12365 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012366 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012367 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012368 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012369
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012370 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12371 // A variable that is privatized must not have a const-qualified type
12372 // unless it is of class type with a mutable member. This restriction does
12373 // not apply to the firstprivate clause.
12374 //
12375 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12376 // A variable that appears in a private clause must not have a
12377 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012378 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012379 continue;
12380
Alexey Bataev758e55e2013-09-06 18:03:48 +000012381 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12382 // in a Construct]
12383 // Variables with the predetermined data-sharing attributes may not be
12384 // listed in data-sharing attributes clauses, except for the cases
12385 // listed below. For these exceptions only, listing a predetermined
12386 // variable in a data-sharing attribute clause is allowed and overrides
12387 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012388 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012389 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012390 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12391 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012392 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012393 continue;
12394 }
12395
Alexey Bataeve3727102018-04-18 15:57:46 +000012396 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012397 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012398 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012399 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012400 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12401 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012402 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012403 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012404 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012405 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012406 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012407 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012408 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012409 continue;
12410 }
12411
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012412 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12413 // A list item cannot appear in both a map clause and a data-sharing
12414 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012415 //
12416 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12417 // A list item cannot appear in both a map clause and a data-sharing
12418 // attribute clause on the same construct unless the construct is a
12419 // combined construct.
12420 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12421 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012422 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012423 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012424 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012425 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12426 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12427 ConflictKind = WhereFoundClauseKind;
12428 return true;
12429 })) {
12430 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012431 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012432 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012433 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012434 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012435 continue;
12436 }
12437 }
12438
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012439 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12440 // A variable of class type (or array thereof) that appears in a private
12441 // clause requires an accessible, unambiguous default constructor for the
12442 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012443 // Generate helper private variable and initialize it with the default
12444 // value. The address of the original variable is replaced by the address of
12445 // the new private variable in CodeGen. This new variable is not added to
12446 // IdResolver, so the code in the OpenMP region uses original variable for
12447 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012448 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012449 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012450 buildVarDecl(*this, ELoc, Type, D->getName(),
12451 D->hasAttrs() ? &D->getAttrs() : nullptr,
12452 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012453 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012454 if (VDPrivate->isInvalidDecl())
12455 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012456 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012457 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012458
Alexey Bataev90c228f2016-02-08 09:29:13 +000012459 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012460 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012461 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012462 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012463 Vars.push_back((VD || CurContext->isDependentContext())
12464 ? RefExpr->IgnoreParens()
12465 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012466 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012467 }
12468
Alexey Bataeved09d242014-05-28 05:53:51 +000012469 if (Vars.empty())
12470 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012471
Alexey Bataev03b340a2014-10-21 03:16:40 +000012472 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12473 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012474}
12475
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012476namespace {
12477class DiagsUninitializedSeveretyRAII {
12478private:
12479 DiagnosticsEngine &Diags;
12480 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012481 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012482
12483public:
12484 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12485 bool IsIgnored)
12486 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12487 if (!IsIgnored) {
12488 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12489 /*Map*/ diag::Severity::Ignored, Loc);
12490 }
12491 }
12492 ~DiagsUninitializedSeveretyRAII() {
12493 if (!IsIgnored)
12494 Diags.popMappings(SavedLoc);
12495 }
12496};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012497}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012498
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012499OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12500 SourceLocation StartLoc,
12501 SourceLocation LParenLoc,
12502 SourceLocation EndLoc) {
12503 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012504 SmallVector<Expr *, 8> PrivateCopies;
12505 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012506 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012507 bool IsImplicitClause =
12508 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012509 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012510
Alexey Bataeve3727102018-04-18 15:57:46 +000012511 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012512 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012513 SourceLocation ELoc;
12514 SourceRange ERange;
12515 Expr *SimpleRefExpr = RefExpr;
12516 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012517 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012518 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012519 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012520 PrivateCopies.push_back(nullptr);
12521 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012522 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012523 ValueDecl *D = Res.first;
12524 if (!D)
12525 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012526
Alexey Bataev60da77e2016-02-29 05:54:20 +000012527 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012528 QualType Type = D->getType();
12529 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012530
12531 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12532 // A variable that appears in a private clause must not have an incomplete
12533 // type or a reference type.
12534 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012535 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012536 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012537 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012538
12539 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12540 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012541 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012542 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012543 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012544
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012545 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012546 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012547 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012548 DSAStackTy::DSAVarData DVar =
12549 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012550 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012551 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012552 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012553 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12554 // A list item that specifies a given variable may not appear in more
12555 // than one clause on the same directive, except that a variable may be
12556 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012557 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12558 // A list item may appear in a firstprivate or lastprivate clause but not
12559 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012560 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012561 (isOpenMPDistributeDirective(CurrDir) ||
12562 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012563 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012564 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012565 << getOpenMPClauseName(DVar.CKind)
12566 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012567 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012568 continue;
12569 }
12570
12571 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12572 // in a Construct]
12573 // Variables with the predetermined data-sharing attributes may not be
12574 // listed in data-sharing attributes clauses, except for the cases
12575 // listed below. For these exceptions only, listing a predetermined
12576 // variable in a data-sharing attribute clause is allowed and overrides
12577 // the variable's predetermined data-sharing attributes.
12578 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12579 // in a Construct, C/C++, p.2]
12580 // Variables with const-qualified type having no mutable member may be
12581 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012582 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012583 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12584 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012585 << getOpenMPClauseName(DVar.CKind)
12586 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012587 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012588 continue;
12589 }
12590
12591 // OpenMP [2.9.3.4, Restrictions, p.2]
12592 // A list item that is private within a parallel region must not appear
12593 // in a firstprivate clause on a worksharing construct if any of the
12594 // worksharing regions arising from the worksharing construct ever bind
12595 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012596 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12597 // A list item that is private within a teams region must not appear in a
12598 // firstprivate clause on a distribute construct if any of the distribute
12599 // regions arising from the distribute construct ever bind to any of the
12600 // teams regions arising from the teams construct.
12601 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12602 // A list item that appears in a reduction clause of a teams construct
12603 // must not appear in a firstprivate clause on a distribute construct if
12604 // any of the distribute regions arising from the distribute construct
12605 // ever bind to any of the teams regions arising from the teams construct.
12606 if ((isOpenMPWorksharingDirective(CurrDir) ||
12607 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012608 !isOpenMPParallelDirective(CurrDir) &&
12609 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012610 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012611 if (DVar.CKind != OMPC_shared &&
12612 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012613 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012614 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012615 Diag(ELoc, diag::err_omp_required_access)
12616 << getOpenMPClauseName(OMPC_firstprivate)
12617 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012618 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012619 continue;
12620 }
12621 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012622 // OpenMP [2.9.3.4, Restrictions, p.3]
12623 // A list item that appears in a reduction clause of a parallel construct
12624 // must not appear in a firstprivate clause on a worksharing or task
12625 // construct if any of the worksharing or task regions arising from the
12626 // worksharing or task construct ever bind to any of the parallel regions
12627 // arising from the parallel construct.
12628 // OpenMP [2.9.3.4, Restrictions, p.4]
12629 // A list item that appears in a reduction clause in worksharing
12630 // construct must not appear in a firstprivate clause in a task construct
12631 // encountered during execution of any of the worksharing regions arising
12632 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012633 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012634 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012635 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12636 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012637 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012638 isOpenMPWorksharingDirective(K) ||
12639 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012640 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012641 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012642 if (DVar.CKind == OMPC_reduction &&
12643 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012644 isOpenMPWorksharingDirective(DVar.DKind) ||
12645 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012646 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12647 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012648 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012649 continue;
12650 }
12651 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012652
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012653 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12654 // A list item cannot appear in both a map clause and a data-sharing
12655 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012656 //
12657 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12658 // A list item cannot appear in both a map clause and a data-sharing
12659 // attribute clause on the same construct unless the construct is a
12660 // combined construct.
12661 if ((LangOpts.OpenMP <= 45 &&
12662 isOpenMPTargetExecutionDirective(CurrDir)) ||
12663 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012664 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012665 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012666 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012667 [&ConflictKind](
12668 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12669 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012670 ConflictKind = WhereFoundClauseKind;
12671 return true;
12672 })) {
12673 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012674 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012675 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012676 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012677 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012678 continue;
12679 }
12680 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012681 }
12682
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012683 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012684 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012685 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012686 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12687 << getOpenMPClauseName(OMPC_firstprivate) << Type
12688 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12689 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012690 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012691 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012692 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012693 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012694 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012695 continue;
12696 }
12697
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012698 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012699 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012700 buildVarDecl(*this, ELoc, Type, D->getName(),
12701 D->hasAttrs() ? &D->getAttrs() : nullptr,
12702 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012703 // Generate helper private variable and initialize it with the value of the
12704 // original variable. The address of the original variable is replaced by
12705 // the address of the new private variable in the CodeGen. This new variable
12706 // is not added to IdResolver, so the code in the OpenMP region uses
12707 // original variable for proper diagnostics and variable capturing.
12708 Expr *VDInitRefExpr = nullptr;
12709 // For arrays generate initializer for single element and replace it by the
12710 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012711 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012712 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012713 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012714 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012715 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012716 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012717 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12718 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012719 InitializedEntity Entity =
12720 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012721 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12722
12723 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12724 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12725 if (Result.isInvalid())
12726 VDPrivate->setInvalidDecl();
12727 else
12728 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012729 // Remove temp variable declaration.
12730 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012731 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012732 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12733 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012734 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12735 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012736 AddInitializerToDecl(VDPrivate,
12737 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012738 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012739 }
12740 if (VDPrivate->isInvalidDecl()) {
12741 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012742 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012743 diag::note_omp_task_predetermined_firstprivate_here);
12744 }
12745 continue;
12746 }
12747 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012748 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012749 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12750 RefExpr->getExprLoc());
12751 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012752 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012753 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012754 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012755 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012756 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012757 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012758 ExprCaptures.push_back(Ref->getDecl());
12759 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012760 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012761 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012762 Vars.push_back((VD || CurContext->isDependentContext())
12763 ? RefExpr->IgnoreParens()
12764 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012765 PrivateCopies.push_back(VDPrivateRefExpr);
12766 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012767 }
12768
Alexey Bataeved09d242014-05-28 05:53:51 +000012769 if (Vars.empty())
12770 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012771
12772 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012773 Vars, PrivateCopies, Inits,
12774 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012775}
12776
Alexander Musman1bb328c2014-06-04 13:06:39 +000012777OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12778 SourceLocation StartLoc,
12779 SourceLocation LParenLoc,
12780 SourceLocation EndLoc) {
12781 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012782 SmallVector<Expr *, 8> SrcExprs;
12783 SmallVector<Expr *, 8> DstExprs;
12784 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000012785 SmallVector<Decl *, 4> ExprCaptures;
12786 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000012787 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012788 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012789 SourceLocation ELoc;
12790 SourceRange ERange;
12791 Expr *SimpleRefExpr = RefExpr;
12792 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000012793 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012794 // It will be analyzed later.
12795 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012796 SrcExprs.push_back(nullptr);
12797 DstExprs.push_back(nullptr);
12798 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012799 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012800 ValueDecl *D = Res.first;
12801 if (!D)
12802 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012803
Alexey Bataev74caaf22016-02-20 04:09:36 +000012804 QualType Type = D->getType();
12805 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012806
12807 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12808 // A variable that appears in a lastprivate clause must not have an
12809 // incomplete type or a reference type.
12810 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000012811 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000012812 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012813 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012814
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012815 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12816 // A variable that is privatized must not have a const-qualified type
12817 // unless it is of class type with a mutable member. This restriction does
12818 // not apply to the firstprivate clause.
12819 //
12820 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12821 // A variable that appears in a lastprivate clause must not have a
12822 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012823 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012824 continue;
12825
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012826 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012827 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12828 // in a Construct]
12829 // Variables with the predetermined data-sharing attributes may not be
12830 // listed in data-sharing attributes clauses, except for the cases
12831 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012832 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12833 // A list item may appear in a firstprivate or lastprivate clause but not
12834 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000012835 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012836 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012837 (isOpenMPDistributeDirective(CurrDir) ||
12838 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000012839 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12840 Diag(ELoc, diag::err_omp_wrong_dsa)
12841 << getOpenMPClauseName(DVar.CKind)
12842 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012843 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012844 continue;
12845 }
12846
Alexey Bataevf29276e2014-06-18 04:14:57 +000012847 // OpenMP [2.14.3.5, Restrictions, p.2]
12848 // A list item that is private within a parallel region, or that appears in
12849 // the reduction clause of a parallel construct, must not appear in a
12850 // lastprivate clause on a worksharing construct if any of the corresponding
12851 // worksharing regions ever binds to any of the corresponding parallel
12852 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000012853 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000012854 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012855 !isOpenMPParallelDirective(CurrDir) &&
12856 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000012857 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012858 if (DVar.CKind != OMPC_shared) {
12859 Diag(ELoc, diag::err_omp_required_access)
12860 << getOpenMPClauseName(OMPC_lastprivate)
12861 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012862 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012863 continue;
12864 }
12865 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012866
Alexander Musman1bb328c2014-06-04 13:06:39 +000012867 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000012868 // A variable of class type (or array thereof) that appears in a
12869 // lastprivate clause requires an accessible, unambiguous default
12870 // constructor for the class type, unless the list item is also specified
12871 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000012872 // A variable of class type (or array thereof) that appears in a
12873 // lastprivate clause requires an accessible, unambiguous copy assignment
12874 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000012875 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012876 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
12877 Type.getUnqualifiedType(), ".lastprivate.src",
12878 D->hasAttrs() ? &D->getAttrs() : nullptr);
12879 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000012880 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012881 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012882 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000012883 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012884 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000012885 // For arrays generate assignment operation for single element and replace
12886 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012887 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
12888 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012889 if (AssignmentOp.isInvalid())
12890 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012891 AssignmentOp =
12892 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000012893 if (AssignmentOp.isInvalid())
12894 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012895
Alexey Bataev74caaf22016-02-20 04:09:36 +000012896 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012897 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012898 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012899 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012900 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012901 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012902 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012903 ExprCaptures.push_back(Ref->getDecl());
12904 }
12905 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012906 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012907 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012908 ExprResult RefRes = DefaultLvalueConversion(Ref);
12909 if (!RefRes.isUsable())
12910 continue;
12911 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012912 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12913 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012914 if (!PostUpdateRes.isUsable())
12915 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012916 ExprPostUpdates.push_back(
12917 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012918 }
12919 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012920 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012921 Vars.push_back((VD || CurContext->isDependentContext())
12922 ? RefExpr->IgnoreParens()
12923 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000012924 SrcExprs.push_back(PseudoSrcExpr);
12925 DstExprs.push_back(PseudoDstExpr);
12926 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000012927 }
12928
12929 if (Vars.empty())
12930 return nullptr;
12931
12932 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000012933 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012934 buildPreInits(Context, ExprCaptures),
12935 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000012936}
12937
Alexey Bataev758e55e2013-09-06 18:03:48 +000012938OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12939 SourceLocation StartLoc,
12940 SourceLocation LParenLoc,
12941 SourceLocation EndLoc) {
12942 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012943 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012944 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012945 SourceLocation ELoc;
12946 SourceRange ERange;
12947 Expr *SimpleRefExpr = RefExpr;
12948 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012949 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000012950 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012951 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012952 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012953 ValueDecl *D = Res.first;
12954 if (!D)
12955 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012956
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012957 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012958 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12959 // in a Construct]
12960 // Variables with the predetermined data-sharing attributes may not be
12961 // listed in data-sharing attributes clauses, except for the cases
12962 // listed below. For these exceptions only, listing a predetermined
12963 // variable in a data-sharing attribute clause is allowed and overrides
12964 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012965 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000012966 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
12967 DVar.RefExpr) {
12968 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12969 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012970 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012971 continue;
12972 }
12973
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012974 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012975 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012976 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012977 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012978 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
12979 ? RefExpr->IgnoreParens()
12980 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012981 }
12982
Alexey Bataeved09d242014-05-28 05:53:51 +000012983 if (Vars.empty())
12984 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012985
12986 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
12987}
12988
Alexey Bataevc5e02582014-06-16 07:08:35 +000012989namespace {
12990class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
12991 DSAStackTy *Stack;
12992
12993public:
12994 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012995 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
12996 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012997 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
12998 return false;
12999 if (DVar.CKind != OMPC_unknown)
13000 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013001 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013002 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013003 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013004 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013005 }
13006 return false;
13007 }
13008 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013009 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013010 if (Child && Visit(Child))
13011 return true;
13012 }
13013 return false;
13014 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013015 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013016};
Alexey Bataev23b69422014-06-18 07:08:49 +000013017} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013018
Alexey Bataev60da77e2016-02-29 05:54:20 +000013019namespace {
13020// Transform MemberExpression for specified FieldDecl of current class to
13021// DeclRefExpr to specified OMPCapturedExprDecl.
13022class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13023 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013024 ValueDecl *Field = nullptr;
13025 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013026
13027public:
13028 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13029 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13030
13031 ExprResult TransformMemberExpr(MemberExpr *E) {
13032 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13033 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013034 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013035 return CapturedExpr;
13036 }
13037 return BaseTransform::TransformMemberExpr(E);
13038 }
13039 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13040};
13041} // namespace
13042
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013043template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013044static T filterLookupForUDReductionAndMapper(
13045 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013046 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013047 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013048 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013049 return Res;
13050 }
13051 }
13052 return T();
13053}
13054
Alexey Bataev43b90b72018-09-12 16:31:59 +000013055static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13056 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13057
13058 for (auto RD : D->redecls()) {
13059 // Don't bother with extra checks if we already know this one isn't visible.
13060 if (RD == D)
13061 continue;
13062
13063 auto ND = cast<NamedDecl>(RD);
13064 if (LookupResult::isVisible(SemaRef, ND))
13065 return ND;
13066 }
13067
13068 return nullptr;
13069}
13070
13071static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013072argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013073 SourceLocation Loc, QualType Ty,
13074 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13075 // Find all of the associated namespaces and classes based on the
13076 // arguments we have.
13077 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13078 Sema::AssociatedClassSet AssociatedClasses;
13079 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13080 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13081 AssociatedClasses);
13082
13083 // C++ [basic.lookup.argdep]p3:
13084 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13085 // and let Y be the lookup set produced by argument dependent
13086 // lookup (defined as follows). If X contains [...] then Y is
13087 // empty. Otherwise Y is the set of declarations found in the
13088 // namespaces associated with the argument types as described
13089 // below. The set of declarations found by the lookup of the name
13090 // is the union of X and Y.
13091 //
13092 // Here, we compute Y and add its members to the overloaded
13093 // candidate set.
13094 for (auto *NS : AssociatedNamespaces) {
13095 // When considering an associated namespace, the lookup is the
13096 // same as the lookup performed when the associated namespace is
13097 // used as a qualifier (3.4.3.2) except that:
13098 //
13099 // -- Any using-directives in the associated namespace are
13100 // ignored.
13101 //
13102 // -- Any namespace-scope friend functions declared in
13103 // associated classes are visible within their respective
13104 // namespaces even if they are not visible during an ordinary
13105 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013106 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013107 for (auto *D : R) {
13108 auto *Underlying = D;
13109 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13110 Underlying = USD->getTargetDecl();
13111
Michael Kruse4304e9d2019-02-19 16:38:20 +000013112 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13113 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013114 continue;
13115
13116 if (!SemaRef.isVisible(D)) {
13117 D = findAcceptableDecl(SemaRef, D);
13118 if (!D)
13119 continue;
13120 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13121 Underlying = USD->getTargetDecl();
13122 }
13123 Lookups.emplace_back();
13124 Lookups.back().addDecl(Underlying);
13125 }
13126 }
13127}
13128
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013129static ExprResult
13130buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13131 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13132 const DeclarationNameInfo &ReductionId, QualType Ty,
13133 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13134 if (ReductionIdScopeSpec.isInvalid())
13135 return ExprError();
13136 SmallVector<UnresolvedSet<8>, 4> Lookups;
13137 if (S) {
13138 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13139 Lookup.suppressDiagnostics();
13140 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013141 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013142 do {
13143 S = S->getParent();
13144 } while (S && !S->isDeclScope(D));
13145 if (S)
13146 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013147 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013148 Lookups.back().append(Lookup.begin(), Lookup.end());
13149 Lookup.clear();
13150 }
13151 } else if (auto *ULE =
13152 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13153 Lookups.push_back(UnresolvedSet<8>());
13154 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013155 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013156 if (D == PrevD)
13157 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013158 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013159 Lookups.back().addDecl(DRD);
13160 PrevD = D;
13161 }
13162 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013163 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13164 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013165 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013166 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013167 return !D->isInvalidDecl() &&
13168 (D->getType()->isDependentType() ||
13169 D->getType()->isInstantiationDependentType() ||
13170 D->getType()->containsUnexpandedParameterPack());
13171 })) {
13172 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013173 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013174 if (Set.empty())
13175 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013176 ResSet.append(Set.begin(), Set.end());
13177 // The last item marks the end of all declarations at the specified scope.
13178 ResSet.addDecl(Set[Set.size() - 1]);
13179 }
13180 return UnresolvedLookupExpr::Create(
13181 SemaRef.Context, /*NamingClass=*/nullptr,
13182 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13183 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13184 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013185 // Lookup inside the classes.
13186 // C++ [over.match.oper]p3:
13187 // For a unary operator @ with an operand of a type whose
13188 // cv-unqualified version is T1, and for a binary operator @ with
13189 // a left operand of a type whose cv-unqualified version is T1 and
13190 // a right operand of a type whose cv-unqualified version is T2,
13191 // three sets of candidate functions, designated member
13192 // candidates, non-member candidates and built-in candidates, are
13193 // constructed as follows:
13194 // -- If T1 is a complete class type or a class currently being
13195 // defined, the set of member candidates is the result of the
13196 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13197 // the set of member candidates is empty.
13198 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13199 Lookup.suppressDiagnostics();
13200 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13201 // Complete the type if it can be completed.
13202 // If the type is neither complete nor being defined, bail out now.
13203 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13204 TyRec->getDecl()->getDefinition()) {
13205 Lookup.clear();
13206 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13207 if (Lookup.empty()) {
13208 Lookups.emplace_back();
13209 Lookups.back().append(Lookup.begin(), Lookup.end());
13210 }
13211 }
13212 }
13213 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013214 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013215 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013216 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13217 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13218 if (!D->isInvalidDecl() &&
13219 SemaRef.Context.hasSameType(D->getType(), Ty))
13220 return D;
13221 return nullptr;
13222 }))
13223 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13224 VK_LValue, Loc);
13225 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013226 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13227 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13228 if (!D->isInvalidDecl() &&
13229 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13230 !Ty.isMoreQualifiedThan(D->getType()))
13231 return D;
13232 return nullptr;
13233 })) {
13234 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13235 /*DetectVirtual=*/false);
13236 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13237 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13238 VD->getType().getUnqualifiedType()))) {
13239 if (SemaRef.CheckBaseClassAccess(
13240 Loc, VD->getType(), Ty, Paths.front(),
13241 /*DiagID=*/0) != Sema::AR_inaccessible) {
13242 SemaRef.BuildBasePathArray(Paths, BasePath);
13243 return SemaRef.BuildDeclRefExpr(
13244 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13245 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013246 }
13247 }
13248 }
13249 }
13250 if (ReductionIdScopeSpec.isSet()) {
13251 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
13252 return ExprError();
13253 }
13254 return ExprEmpty();
13255}
13256
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013257namespace {
13258/// Data for the reduction-based clauses.
13259struct ReductionData {
13260 /// List of original reduction items.
13261 SmallVector<Expr *, 8> Vars;
13262 /// List of private copies of the reduction items.
13263 SmallVector<Expr *, 8> Privates;
13264 /// LHS expressions for the reduction_op expressions.
13265 SmallVector<Expr *, 8> LHSs;
13266 /// RHS expressions for the reduction_op expressions.
13267 SmallVector<Expr *, 8> RHSs;
13268 /// Reduction operation expression.
13269 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013270 /// Taskgroup descriptors for the corresponding reduction items in
13271 /// in_reduction clauses.
13272 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013273 /// List of captures for clause.
13274 SmallVector<Decl *, 4> ExprCaptures;
13275 /// List of postupdate expressions.
13276 SmallVector<Expr *, 4> ExprPostUpdates;
13277 ReductionData() = delete;
13278 /// Reserves required memory for the reduction data.
13279 ReductionData(unsigned Size) {
13280 Vars.reserve(Size);
13281 Privates.reserve(Size);
13282 LHSs.reserve(Size);
13283 RHSs.reserve(Size);
13284 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013285 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013286 ExprCaptures.reserve(Size);
13287 ExprPostUpdates.reserve(Size);
13288 }
13289 /// Stores reduction item and reduction operation only (required for dependent
13290 /// reduction item).
13291 void push(Expr *Item, Expr *ReductionOp) {
13292 Vars.emplace_back(Item);
13293 Privates.emplace_back(nullptr);
13294 LHSs.emplace_back(nullptr);
13295 RHSs.emplace_back(nullptr);
13296 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013297 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013298 }
13299 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013300 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13301 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013302 Vars.emplace_back(Item);
13303 Privates.emplace_back(Private);
13304 LHSs.emplace_back(LHS);
13305 RHSs.emplace_back(RHS);
13306 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013307 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013308 }
13309};
13310} // namespace
13311
Alexey Bataeve3727102018-04-18 15:57:46 +000013312static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013313 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13314 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13315 const Expr *Length = OASE->getLength();
13316 if (Length == nullptr) {
13317 // For array sections of the form [1:] or [:], we would need to analyze
13318 // the lower bound...
13319 if (OASE->getColonLoc().isValid())
13320 return false;
13321
13322 // This is an array subscript which has implicit length 1!
13323 SingleElement = true;
13324 ArraySizes.push_back(llvm::APSInt::get(1));
13325 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013326 Expr::EvalResult Result;
13327 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013328 return false;
13329
Fangrui Song407659a2018-11-30 23:41:18 +000013330 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013331 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13332 ArraySizes.push_back(ConstantLengthValue);
13333 }
13334
13335 // Get the base of this array section and walk up from there.
13336 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13337
13338 // We require length = 1 for all array sections except the right-most to
13339 // guarantee that the memory region is contiguous and has no holes in it.
13340 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13341 Length = TempOASE->getLength();
13342 if (Length == nullptr) {
13343 // For array sections of the form [1:] or [:], we would need to analyze
13344 // the lower bound...
13345 if (OASE->getColonLoc().isValid())
13346 return false;
13347
13348 // This is an array subscript which has implicit length 1!
13349 ArraySizes.push_back(llvm::APSInt::get(1));
13350 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013351 Expr::EvalResult Result;
13352 if (!Length->EvaluateAsInt(Result, Context))
13353 return false;
13354
13355 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13356 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013357 return false;
13358
13359 ArraySizes.push_back(ConstantLengthValue);
13360 }
13361 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13362 }
13363
13364 // If we have a single element, we don't need to add the implicit lengths.
13365 if (!SingleElement) {
13366 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13367 // Has implicit length 1!
13368 ArraySizes.push_back(llvm::APSInt::get(1));
13369 Base = TempASE->getBase()->IgnoreParenImpCasts();
13370 }
13371 }
13372
13373 // This array section can be privatized as a single value or as a constant
13374 // sized array.
13375 return true;
13376}
13377
Alexey Bataeve3727102018-04-18 15:57:46 +000013378static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013379 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13380 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13381 SourceLocation ColonLoc, SourceLocation EndLoc,
13382 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013383 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013384 DeclarationName DN = ReductionId.getName();
13385 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013386 BinaryOperatorKind BOK = BO_Comma;
13387
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013388 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013389 // OpenMP [2.14.3.6, reduction clause]
13390 // C
13391 // reduction-identifier is either an identifier or one of the following
13392 // operators: +, -, *, &, |, ^, && and ||
13393 // C++
13394 // reduction-identifier is either an id-expression or one of the following
13395 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013396 switch (OOK) {
13397 case OO_Plus:
13398 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013399 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013400 break;
13401 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013402 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013403 break;
13404 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013405 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013406 break;
13407 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013408 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013409 break;
13410 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013411 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013412 break;
13413 case OO_AmpAmp:
13414 BOK = BO_LAnd;
13415 break;
13416 case OO_PipePipe:
13417 BOK = BO_LOr;
13418 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013419 case OO_New:
13420 case OO_Delete:
13421 case OO_Array_New:
13422 case OO_Array_Delete:
13423 case OO_Slash:
13424 case OO_Percent:
13425 case OO_Tilde:
13426 case OO_Exclaim:
13427 case OO_Equal:
13428 case OO_Less:
13429 case OO_Greater:
13430 case OO_LessEqual:
13431 case OO_GreaterEqual:
13432 case OO_PlusEqual:
13433 case OO_MinusEqual:
13434 case OO_StarEqual:
13435 case OO_SlashEqual:
13436 case OO_PercentEqual:
13437 case OO_CaretEqual:
13438 case OO_AmpEqual:
13439 case OO_PipeEqual:
13440 case OO_LessLess:
13441 case OO_GreaterGreater:
13442 case OO_LessLessEqual:
13443 case OO_GreaterGreaterEqual:
13444 case OO_EqualEqual:
13445 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013446 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013447 case OO_PlusPlus:
13448 case OO_MinusMinus:
13449 case OO_Comma:
13450 case OO_ArrowStar:
13451 case OO_Arrow:
13452 case OO_Call:
13453 case OO_Subscript:
13454 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013455 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013456 case NUM_OVERLOADED_OPERATORS:
13457 llvm_unreachable("Unexpected reduction identifier");
13458 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013459 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013460 if (II->isStr("max"))
13461 BOK = BO_GT;
13462 else if (II->isStr("min"))
13463 BOK = BO_LT;
13464 }
13465 break;
13466 }
13467 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013468 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013469 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013470 else
13471 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013472 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013473
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013474 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13475 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013476 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013477 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013478 // OpenMP [2.1, C/C++]
13479 // A list item is a variable or array section, subject to the restrictions
13480 // specified in Section 2.4 on page 42 and in each of the sections
13481 // describing clauses and directives for which a list appears.
13482 // OpenMP [2.14.3.3, Restrictions, p.1]
13483 // A variable that is part of another variable (as an array or
13484 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013485 if (!FirstIter && IR != ER)
13486 ++IR;
13487 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013488 SourceLocation ELoc;
13489 SourceRange ERange;
13490 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013491 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013492 /*AllowArraySection=*/true);
13493 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013494 // Try to find 'declare reduction' corresponding construct before using
13495 // builtin/overloaded operators.
13496 QualType Type = Context.DependentTy;
13497 CXXCastPath BasePath;
13498 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013499 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013500 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013501 Expr *ReductionOp = nullptr;
13502 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013503 (DeclareReductionRef.isUnset() ||
13504 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013505 ReductionOp = DeclareReductionRef.get();
13506 // It will be analyzed later.
13507 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013508 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013509 ValueDecl *D = Res.first;
13510 if (!D)
13511 continue;
13512
Alexey Bataev88202be2017-07-27 13:20:36 +000013513 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013514 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013515 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13516 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013517 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013518 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013519 } else if (OASE) {
13520 QualType BaseType =
13521 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13522 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013523 Type = ATy->getElementType();
13524 else
13525 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013526 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013527 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013528 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013529 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013530 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013531
Alexey Bataevc5e02582014-06-16 07:08:35 +000013532 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13533 // A variable that appears in a private clause must not have an incomplete
13534 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013535 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013536 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013537 continue;
13538 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013539 // A list item that appears in a reduction clause must not be
13540 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013541 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13542 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013543 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013544
13545 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013546 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13547 // If a list-item is a reference type then it must bind to the same object
13548 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013549 if (!ASE && !OASE) {
13550 if (VD) {
13551 VarDecl *VDDef = VD->getDefinition();
13552 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13553 DSARefChecker Check(Stack);
13554 if (Check.Visit(VDDef->getInit())) {
13555 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13556 << getOpenMPClauseName(ClauseKind) << ERange;
13557 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13558 continue;
13559 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013560 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013561 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013562
Alexey Bataevbc529672018-09-28 19:33:14 +000013563 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13564 // in a Construct]
13565 // Variables with the predetermined data-sharing attributes may not be
13566 // listed in data-sharing attributes clauses, except for the cases
13567 // listed below. For these exceptions only, listing a predetermined
13568 // variable in a data-sharing attribute clause is allowed and overrides
13569 // the variable's predetermined data-sharing attributes.
13570 // OpenMP [2.14.3.6, Restrictions, p.3]
13571 // Any number of reduction clauses can be specified on the directive,
13572 // but a list item can appear only once in the reduction clauses for that
13573 // directive.
13574 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13575 if (DVar.CKind == OMPC_reduction) {
13576 S.Diag(ELoc, diag::err_omp_once_referenced)
13577 << getOpenMPClauseName(ClauseKind);
13578 if (DVar.RefExpr)
13579 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13580 continue;
13581 }
13582 if (DVar.CKind != OMPC_unknown) {
13583 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13584 << getOpenMPClauseName(DVar.CKind)
13585 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013586 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013587 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013588 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013589
13590 // OpenMP [2.14.3.6, Restrictions, p.1]
13591 // A list item that appears in a reduction clause of a worksharing
13592 // construct must be shared in the parallel regions to which any of the
13593 // worksharing regions arising from the worksharing construct bind.
13594 if (isOpenMPWorksharingDirective(CurrDir) &&
13595 !isOpenMPParallelDirective(CurrDir) &&
13596 !isOpenMPTeamsDirective(CurrDir)) {
13597 DVar = Stack->getImplicitDSA(D, true);
13598 if (DVar.CKind != OMPC_shared) {
13599 S.Diag(ELoc, diag::err_omp_required_access)
13600 << getOpenMPClauseName(OMPC_reduction)
13601 << getOpenMPClauseName(OMPC_shared);
13602 reportOriginalDsa(S, Stack, D, DVar);
13603 continue;
13604 }
13605 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013606 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013607
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013608 // Try to find 'declare reduction' corresponding construct before using
13609 // builtin/overloaded operators.
13610 CXXCastPath BasePath;
13611 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013612 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013613 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13614 if (DeclareReductionRef.isInvalid())
13615 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013616 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013617 (DeclareReductionRef.isUnset() ||
13618 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013619 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013620 continue;
13621 }
13622 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13623 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013624 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013625 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013626 << Type << ReductionIdRange;
13627 continue;
13628 }
13629
13630 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13631 // The type of a list item that appears in a reduction clause must be valid
13632 // for the reduction-identifier. For a max or min reduction in C, the type
13633 // of the list item must be an allowed arithmetic data type: char, int,
13634 // float, double, or _Bool, possibly modified with long, short, signed, or
13635 // unsigned. For a max or min reduction in C++, the type of the list item
13636 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13637 // double, or bool, possibly modified with long, short, signed, or unsigned.
13638 if (DeclareReductionRef.isUnset()) {
13639 if ((BOK == BO_GT || BOK == BO_LT) &&
13640 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013641 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13642 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013643 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013644 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013645 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13646 VarDecl::DeclarationOnly;
13647 S.Diag(D->getLocation(),
13648 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013649 << D;
13650 }
13651 continue;
13652 }
13653 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013654 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013655 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13656 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013657 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013658 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13659 VarDecl::DeclarationOnly;
13660 S.Diag(D->getLocation(),
13661 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013662 << D;
13663 }
13664 continue;
13665 }
13666 }
13667
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013668 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013669 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13670 D->hasAttrs() ? &D->getAttrs() : nullptr);
13671 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13672 D->hasAttrs() ? &D->getAttrs() : nullptr);
13673 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013674
13675 // Try if we can determine constant lengths for all array sections and avoid
13676 // the VLA.
13677 bool ConstantLengthOASE = false;
13678 if (OASE) {
13679 bool SingleElement;
13680 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013681 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013682 Context, OASE, SingleElement, ArraySizes);
13683
13684 // If we don't have a single element, we must emit a constant array type.
13685 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013686 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013687 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13688 ArrayType::Normal,
13689 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013690 }
13691 }
13692
13693 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013694 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013695 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013696 if (!Context.getTargetInfo().isVLASupported()) {
13697 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13698 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13699 S.Diag(ELoc, diag::note_vla_unsupported);
13700 } else {
13701 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13702 S.targetDiag(ELoc, diag::note_vla_unsupported);
13703 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013704 continue;
13705 }
David Majnemer9d168222016-08-05 17:44:54 +000013706 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013707 // Create pseudo array type for private copy. The size for this array will
13708 // be generated during codegen.
13709 // For array subscripts or single variables Private Ty is the same as Type
13710 // (type of the variable or single array element).
13711 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013712 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013713 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013714 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013715 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013716 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013717 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013718 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013719 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013720 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013721 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13722 D->hasAttrs() ? &D->getAttrs() : nullptr,
13723 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013724 // Add initializer for private variable.
13725 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013726 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13727 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013728 if (DeclareReductionRef.isUsable()) {
13729 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13730 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13731 if (DRD->getInitializer()) {
13732 Init = DRDRef;
13733 RHSVD->setInit(DRDRef);
13734 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013735 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013736 } else {
13737 switch (BOK) {
13738 case BO_Add:
13739 case BO_Xor:
13740 case BO_Or:
13741 case BO_LOr:
13742 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13743 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013744 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013745 break;
13746 case BO_Mul:
13747 case BO_LAnd:
13748 if (Type->isScalarType() || Type->isAnyComplexType()) {
13749 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013750 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013751 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013752 break;
13753 case BO_And: {
13754 // '&' reduction op - initializer is '~0'.
13755 QualType OrigType = Type;
13756 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13757 Type = ComplexTy->getElementType();
13758 if (Type->isRealFloatingType()) {
13759 llvm::APFloat InitValue =
13760 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13761 /*isIEEE=*/true);
13762 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13763 Type, ELoc);
13764 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013765 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013766 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13767 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13768 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13769 }
13770 if (Init && OrigType->isAnyComplexType()) {
13771 // Init = 0xFFFF + 0xFFFFi;
13772 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013773 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013774 }
13775 Type = OrigType;
13776 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013777 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013778 case BO_LT:
13779 case BO_GT: {
13780 // 'min' reduction op - initializer is 'Largest representable number in
13781 // the reduction list item type'.
13782 // 'max' reduction op - initializer is 'Least representable number in
13783 // the reduction list item type'.
13784 if (Type->isIntegerType() || Type->isPointerType()) {
13785 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013786 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013787 QualType IntTy =
13788 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13789 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013790 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13791 : llvm::APInt::getMinValue(Size)
13792 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13793 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013794 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13795 if (Type->isPointerType()) {
13796 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013797 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000013798 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013799 if (CastExpr.isInvalid())
13800 continue;
13801 Init = CastExpr.get();
13802 }
13803 } else if (Type->isRealFloatingType()) {
13804 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13805 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13806 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13807 Type, ELoc);
13808 }
13809 break;
13810 }
13811 case BO_PtrMemD:
13812 case BO_PtrMemI:
13813 case BO_MulAssign:
13814 case BO_Div:
13815 case BO_Rem:
13816 case BO_Sub:
13817 case BO_Shl:
13818 case BO_Shr:
13819 case BO_LE:
13820 case BO_GE:
13821 case BO_EQ:
13822 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000013823 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013824 case BO_AndAssign:
13825 case BO_XorAssign:
13826 case BO_OrAssign:
13827 case BO_Assign:
13828 case BO_AddAssign:
13829 case BO_SubAssign:
13830 case BO_DivAssign:
13831 case BO_RemAssign:
13832 case BO_ShlAssign:
13833 case BO_ShrAssign:
13834 case BO_Comma:
13835 llvm_unreachable("Unexpected reduction operation");
13836 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013837 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013838 if (Init && DeclareReductionRef.isUnset())
13839 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13840 else if (!Init)
13841 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013842 if (RHSVD->isInvalidDecl())
13843 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000013844 if (!RHSVD->hasInit() &&
13845 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013846 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
13847 << Type << ReductionIdRange;
13848 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13849 VarDecl::DeclarationOnly;
13850 S.Diag(D->getLocation(),
13851 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000013852 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013853 continue;
13854 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013855 // Store initializer for single element in private copy. Will be used during
13856 // codegen.
13857 PrivateVD->setInit(RHSVD->getInit());
13858 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000013859 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013860 ExprResult ReductionOp;
13861 if (DeclareReductionRef.isUsable()) {
13862 QualType RedTy = DeclareReductionRef.get()->getType();
13863 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013864 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
13865 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013866 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013867 LHS = S.DefaultLvalueConversion(LHS.get());
13868 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013869 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13870 CK_UncheckedDerivedToBase, LHS.get(),
13871 &BasePath, LHS.get()->getValueKind());
13872 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13873 CK_UncheckedDerivedToBase, RHS.get(),
13874 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013875 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013876 FunctionProtoType::ExtProtoInfo EPI;
13877 QualType Params[] = {PtrRedTy, PtrRedTy};
13878 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
13879 auto *OVE = new (Context) OpaqueValueExpr(
13880 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013881 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013882 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000013883 ReductionOp =
13884 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013885 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013886 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013887 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013888 if (ReductionOp.isUsable()) {
13889 if (BOK != BO_LT && BOK != BO_GT) {
13890 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013891 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013892 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013893 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000013894 auto *ConditionalOp = new (Context)
13895 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
13896 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013897 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013898 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013899 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013900 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013901 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013902 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
13903 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013904 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013905 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013906 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013907 }
13908
Alexey Bataevfa312f32017-07-21 18:48:21 +000013909 // OpenMP [2.15.4.6, Restrictions, p.2]
13910 // A list item that appears in an in_reduction clause of a task construct
13911 // must appear in a task_reduction clause of a construct associated with a
13912 // taskgroup region that includes the participating task in its taskgroup
13913 // set. The construct associated with the innermost region that meets this
13914 // condition must specify the same reduction-identifier as the in_reduction
13915 // clause.
13916 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000013917 SourceRange ParentSR;
13918 BinaryOperatorKind ParentBOK;
13919 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000013920 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000013921 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013922 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
13923 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013924 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013925 Stack->getTopMostTaskgroupReductionData(
13926 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013927 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
13928 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
13929 if (!IsParentBOK && !IsParentReductionOp) {
13930 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
13931 continue;
13932 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000013933 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
13934 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
13935 IsParentReductionOp) {
13936 bool EmitError = true;
13937 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
13938 llvm::FoldingSetNodeID RedId, ParentRedId;
13939 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
13940 DeclareReductionRef.get()->Profile(RedId, Context,
13941 /*Canonical=*/true);
13942 EmitError = RedId != ParentRedId;
13943 }
13944 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013945 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000013946 diag::err_omp_reduction_identifier_mismatch)
13947 << ReductionIdRange << RefExpr->getSourceRange();
13948 S.Diag(ParentSR.getBegin(),
13949 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000013950 << ParentSR
13951 << (IsParentBOK ? ParentBOKDSA.RefExpr
13952 : ParentReductionOpDSA.RefExpr)
13953 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000013954 continue;
13955 }
13956 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013957 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
13958 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000013959 }
13960
Alexey Bataev60da77e2016-02-29 05:54:20 +000013961 DeclRefExpr *Ref = nullptr;
13962 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013963 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013964 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013965 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013966 VarsExpr =
13967 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
13968 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000013969 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013970 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013971 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013972 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013973 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013974 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013975 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013976 if (!RefRes.isUsable())
13977 continue;
13978 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013979 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13980 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013981 if (!PostUpdateRes.isUsable())
13982 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013983 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
13984 Stack->getCurrentDirective() == OMPD_taskgroup) {
13985 S.Diag(RefExpr->getExprLoc(),
13986 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000013987 << RefExpr->getSourceRange();
13988 continue;
13989 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013990 RD.ExprPostUpdates.emplace_back(
13991 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000013992 }
13993 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013994 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000013995 // All reduction items are still marked as reduction (to do not increase
13996 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013997 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013998 if (CurrDir == OMPD_taskgroup) {
13999 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014000 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14001 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014002 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014003 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014004 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014005 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14006 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014007 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014008 return RD.Vars.empty();
14009}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014010
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014011OMPClause *Sema::ActOnOpenMPReductionClause(
14012 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14013 SourceLocation ColonLoc, SourceLocation EndLoc,
14014 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14015 ArrayRef<Expr *> UnresolvedReductions) {
14016 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014017 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014018 StartLoc, LParenLoc, ColonLoc, EndLoc,
14019 ReductionIdScopeSpec, ReductionId,
14020 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014021 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014022
Alexey Bataevc5e02582014-06-16 07:08:35 +000014023 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014024 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14025 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14026 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14027 buildPreInits(Context, RD.ExprCaptures),
14028 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014029}
14030
Alexey Bataev169d96a2017-07-18 20:17:46 +000014031OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14032 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14033 SourceLocation ColonLoc, SourceLocation EndLoc,
14034 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14035 ArrayRef<Expr *> UnresolvedReductions) {
14036 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014037 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14038 StartLoc, LParenLoc, ColonLoc, EndLoc,
14039 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014040 UnresolvedReductions, RD))
14041 return nullptr;
14042
14043 return OMPTaskReductionClause::Create(
14044 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14045 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14046 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14047 buildPreInits(Context, RD.ExprCaptures),
14048 buildPostUpdate(*this, RD.ExprPostUpdates));
14049}
14050
Alexey Bataevfa312f32017-07-21 18:48:21 +000014051OMPClause *Sema::ActOnOpenMPInReductionClause(
14052 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14053 SourceLocation ColonLoc, SourceLocation EndLoc,
14054 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14055 ArrayRef<Expr *> UnresolvedReductions) {
14056 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014057 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014058 StartLoc, LParenLoc, ColonLoc, EndLoc,
14059 ReductionIdScopeSpec, ReductionId,
14060 UnresolvedReductions, RD))
14061 return nullptr;
14062
14063 return OMPInReductionClause::Create(
14064 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14065 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014066 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014067 buildPreInits(Context, RD.ExprCaptures),
14068 buildPostUpdate(*this, RD.ExprPostUpdates));
14069}
14070
Alexey Bataevecba70f2016-04-12 11:02:11 +000014071bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14072 SourceLocation LinLoc) {
14073 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14074 LinKind == OMPC_LINEAR_unknown) {
14075 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14076 return true;
14077 }
14078 return false;
14079}
14080
Alexey Bataeve3727102018-04-18 15:57:46 +000014081bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014082 OpenMPLinearClauseKind LinKind,
14083 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014084 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014085 // A variable must not have an incomplete type or a reference type.
14086 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14087 return true;
14088 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14089 !Type->isReferenceType()) {
14090 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14091 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14092 return true;
14093 }
14094 Type = Type.getNonReferenceType();
14095
Joel E. Dennybae586f2019-01-04 22:12:13 +000014096 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14097 // A variable that is privatized must not have a const-qualified type
14098 // unless it is of class type with a mutable member. This restriction does
14099 // not apply to the firstprivate clause.
14100 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014101 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014102
14103 // A list item must be of integral or pointer type.
14104 Type = Type.getUnqualifiedType().getCanonicalType();
14105 const auto *Ty = Type.getTypePtrOrNull();
14106 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
14107 !Ty->isPointerType())) {
14108 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14109 if (D) {
14110 bool IsDecl =
14111 !VD ||
14112 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14113 Diag(D->getLocation(),
14114 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14115 << D;
14116 }
14117 return true;
14118 }
14119 return false;
14120}
14121
Alexey Bataev182227b2015-08-20 10:54:39 +000014122OMPClause *Sema::ActOnOpenMPLinearClause(
14123 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14124 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14125 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014126 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014127 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014128 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014129 SmallVector<Decl *, 4> ExprCaptures;
14130 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014131 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014132 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014133 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014134 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014135 SourceLocation ELoc;
14136 SourceRange ERange;
14137 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014138 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014139 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014140 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014141 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014142 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014143 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014144 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014145 ValueDecl *D = Res.first;
14146 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014147 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014148
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014149 QualType Type = D->getType();
14150 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014151
14152 // OpenMP [2.14.3.7, linear clause]
14153 // A list-item cannot appear in more than one linear clause.
14154 // A list-item that appears in a linear clause cannot appear in any
14155 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014156 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014157 if (DVar.RefExpr) {
14158 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14159 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014160 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014161 continue;
14162 }
14163
Alexey Bataevecba70f2016-04-12 11:02:11 +000014164 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014165 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014166 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014167
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014168 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014169 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014170 buildVarDecl(*this, ELoc, Type, D->getName(),
14171 D->hasAttrs() ? &D->getAttrs() : nullptr,
14172 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014173 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014174 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014175 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014176 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014177 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014178 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014179 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014180 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014181 ExprCaptures.push_back(Ref->getDecl());
14182 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14183 ExprResult RefRes = DefaultLvalueConversion(Ref);
14184 if (!RefRes.isUsable())
14185 continue;
14186 ExprResult PostUpdateRes =
14187 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14188 SimpleRefExpr, RefRes.get());
14189 if (!PostUpdateRes.isUsable())
14190 continue;
14191 ExprPostUpdates.push_back(
14192 IgnoredValueConversions(PostUpdateRes.get()).get());
14193 }
14194 }
14195 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014196 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014197 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014198 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014199 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014200 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014201 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014202 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014203
14204 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014205 Vars.push_back((VD || CurContext->isDependentContext())
14206 ? RefExpr->IgnoreParens()
14207 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014208 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014209 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014210 }
14211
14212 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014213 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014214
14215 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014216 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014217 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14218 !Step->isInstantiationDependent() &&
14219 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014220 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014221 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014222 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014223 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014224 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014225
Alexander Musman3276a272015-03-21 10:12:56 +000014226 // Build var to save the step value.
14227 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014228 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014229 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014230 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014231 ExprResult CalcStep =
14232 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014233 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014234
Alexander Musman8dba6642014-04-22 13:09:42 +000014235 // Warn about zero linear step (it would be probably better specified as
14236 // making corresponding variables 'const').
14237 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014238 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14239 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014240 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14241 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014242 if (!IsConstant && CalcStep.isUsable()) {
14243 // Calculate the step beforehand instead of doing this on each iteration.
14244 // (This is not used if the number of iterations may be kfold-ed).
14245 CalcStepExpr = CalcStep.get();
14246 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014247 }
14248
Alexey Bataev182227b2015-08-20 10:54:39 +000014249 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14250 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014251 StepExpr, CalcStepExpr,
14252 buildPreInits(Context, ExprCaptures),
14253 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014254}
14255
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014256static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14257 Expr *NumIterations, Sema &SemaRef,
14258 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014259 // Walk the vars and build update/final expressions for the CodeGen.
14260 SmallVector<Expr *, 8> Updates;
14261 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014262 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014263 Expr *Step = Clause.getStep();
14264 Expr *CalcStep = Clause.getCalcStep();
14265 // OpenMP [2.14.3.7, linear clause]
14266 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014267 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014268 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014269 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014270 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14271 bool HasErrors = false;
14272 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014273 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014274 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14275 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014276 SourceLocation ELoc;
14277 SourceRange ERange;
14278 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014279 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014280 ValueDecl *D = Res.first;
14281 if (Res.second || !D) {
14282 Updates.push_back(nullptr);
14283 Finals.push_back(nullptr);
14284 HasErrors = true;
14285 continue;
14286 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014287 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014288 // OpenMP [2.15.11, distribute simd Construct]
14289 // A list item may not appear in a linear clause, unless it is the loop
14290 // iteration variable.
14291 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14292 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14293 SemaRef.Diag(ELoc,
14294 diag::err_omp_linear_distribute_var_non_loop_iteration);
14295 Updates.push_back(nullptr);
14296 Finals.push_back(nullptr);
14297 HasErrors = true;
14298 continue;
14299 }
Alexander Musman3276a272015-03-21 10:12:56 +000014300 Expr *InitExpr = *CurInit;
14301
14302 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014303 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014304 Expr *CapturedRef;
14305 if (LinKind == OMPC_LINEAR_uval)
14306 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14307 else
14308 CapturedRef =
14309 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14310 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14311 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014312
14313 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014314 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014315 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014316 Update = buildCounterUpdate(
14317 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14318 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014319 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014320 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014321 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014322 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014323
14324 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014325 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014326 if (!Info.first)
14327 Final =
14328 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014329 InitExpr, NumIterations, Step, /*Subtract=*/false,
14330 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014331 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014332 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014333 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014334 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014335
Alexander Musman3276a272015-03-21 10:12:56 +000014336 if (!Update.isUsable() || !Final.isUsable()) {
14337 Updates.push_back(nullptr);
14338 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014339 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014340 HasErrors = true;
14341 } else {
14342 Updates.push_back(Update.get());
14343 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014344 if (!Info.first)
14345 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014346 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014347 ++CurInit;
14348 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014349 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014350 if (Expr *S = Clause.getStep())
14351 UsedExprs.push_back(S);
14352 // Fill the remaining part with the nullptr.
14353 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014354 Clause.setUpdates(Updates);
14355 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014356 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014357 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014358}
14359
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014360OMPClause *Sema::ActOnOpenMPAlignedClause(
14361 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14362 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014363 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014364 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014365 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14366 SourceLocation ELoc;
14367 SourceRange ERange;
14368 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014369 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014370 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014371 // It will be analyzed later.
14372 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014373 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014374 ValueDecl *D = Res.first;
14375 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014376 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014377
Alexey Bataev1efd1662016-03-29 10:59:56 +000014378 QualType QType = D->getType();
14379 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014380
14381 // OpenMP [2.8.1, simd construct, Restrictions]
14382 // The type of list items appearing in the aligned clause must be
14383 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014384 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014385 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014386 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014387 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014388 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014389 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014390 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014391 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014392 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014393 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014394 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014395 continue;
14396 }
14397
14398 // OpenMP [2.8.1, simd construct, Restrictions]
14399 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014400 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000014401 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014402 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14403 << getOpenMPClauseName(OMPC_aligned);
14404 continue;
14405 }
14406
Alexey Bataev1efd1662016-03-29 10:59:56 +000014407 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014408 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014409 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14410 Vars.push_back(DefaultFunctionArrayConversion(
14411 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14412 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014413 }
14414
14415 // OpenMP [2.8.1, simd construct, Description]
14416 // The parameter of the aligned clause, alignment, must be a constant
14417 // positive integer expression.
14418 // If no optional parameter is specified, implementation-defined default
14419 // alignments for SIMD instructions on the target platforms are assumed.
14420 if (Alignment != nullptr) {
14421 ExprResult AlignResult =
14422 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14423 if (AlignResult.isInvalid())
14424 return nullptr;
14425 Alignment = AlignResult.get();
14426 }
14427 if (Vars.empty())
14428 return nullptr;
14429
14430 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14431 EndLoc, Vars, Alignment);
14432}
14433
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014434OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14435 SourceLocation StartLoc,
14436 SourceLocation LParenLoc,
14437 SourceLocation EndLoc) {
14438 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014439 SmallVector<Expr *, 8> SrcExprs;
14440 SmallVector<Expr *, 8> DstExprs;
14441 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014442 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014443 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14444 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014445 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014446 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014447 SrcExprs.push_back(nullptr);
14448 DstExprs.push_back(nullptr);
14449 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014450 continue;
14451 }
14452
Alexey Bataeved09d242014-05-28 05:53:51 +000014453 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014454 // OpenMP [2.1, C/C++]
14455 // A list item is a variable name.
14456 // OpenMP [2.14.4.1, Restrictions, p.1]
14457 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014458 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014459 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014460 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14461 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014462 continue;
14463 }
14464
14465 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014466 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014467
14468 QualType Type = VD->getType();
14469 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14470 // It will be analyzed later.
14471 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014472 SrcExprs.push_back(nullptr);
14473 DstExprs.push_back(nullptr);
14474 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014475 continue;
14476 }
14477
14478 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14479 // A list item that appears in a copyin clause must be threadprivate.
14480 if (!DSAStack->isThreadPrivate(VD)) {
14481 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014482 << getOpenMPClauseName(OMPC_copyin)
14483 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014484 continue;
14485 }
14486
14487 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14488 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014489 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014490 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014491 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14492 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014493 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014494 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014495 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014496 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014497 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014498 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014499 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014500 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014501 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014502 // For arrays generate assignment operation for single element and replace
14503 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014504 ExprResult AssignmentOp =
14505 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14506 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014507 if (AssignmentOp.isInvalid())
14508 continue;
14509 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014510 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014511 if (AssignmentOp.isInvalid())
14512 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014513
14514 DSAStack->addDSA(VD, DE, OMPC_copyin);
14515 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014516 SrcExprs.push_back(PseudoSrcExpr);
14517 DstExprs.push_back(PseudoDstExpr);
14518 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014519 }
14520
Alexey Bataeved09d242014-05-28 05:53:51 +000014521 if (Vars.empty())
14522 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014523
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014524 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14525 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014526}
14527
Alexey Bataevbae9a792014-06-27 10:37:06 +000014528OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14529 SourceLocation StartLoc,
14530 SourceLocation LParenLoc,
14531 SourceLocation EndLoc) {
14532 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014533 SmallVector<Expr *, 8> SrcExprs;
14534 SmallVector<Expr *, 8> DstExprs;
14535 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014536 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014537 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14538 SourceLocation ELoc;
14539 SourceRange ERange;
14540 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014541 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014542 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014543 // It will be analyzed later.
14544 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014545 SrcExprs.push_back(nullptr);
14546 DstExprs.push_back(nullptr);
14547 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014548 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014549 ValueDecl *D = Res.first;
14550 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014551 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014552
Alexey Bataeve122da12016-03-17 10:50:17 +000014553 QualType Type = D->getType();
14554 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014555
14556 // OpenMP [2.14.4.2, Restrictions, p.2]
14557 // A list item that appears in a copyprivate clause may not appear in a
14558 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014559 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014560 DSAStackTy::DSAVarData DVar =
14561 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014562 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14563 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014564 Diag(ELoc, diag::err_omp_wrong_dsa)
14565 << getOpenMPClauseName(DVar.CKind)
14566 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014567 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014568 continue;
14569 }
14570
14571 // OpenMP [2.11.4.2, Restrictions, p.1]
14572 // All list items that appear in a copyprivate clause must be either
14573 // threadprivate or private in the enclosing context.
14574 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014575 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014576 if (DVar.CKind == OMPC_shared) {
14577 Diag(ELoc, diag::err_omp_required_access)
14578 << getOpenMPClauseName(OMPC_copyprivate)
14579 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014580 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014581 continue;
14582 }
14583 }
14584 }
14585
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014586 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014587 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014588 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014589 << getOpenMPClauseName(OMPC_copyprivate) << Type
14590 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014591 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014592 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014593 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014594 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014595 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014596 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014597 continue;
14598 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014599
Alexey Bataevbae9a792014-06-27 10:37:06 +000014600 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14601 // A variable of class type (or array thereof) that appears in a
14602 // copyin clause requires an accessible, unambiguous copy assignment
14603 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014604 Type = Context.getBaseElementType(Type.getNonReferenceType())
14605 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014606 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014607 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014608 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014609 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14610 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014611 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014612 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014613 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14614 ExprResult AssignmentOp = BuildBinOp(
14615 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014616 if (AssignmentOp.isInvalid())
14617 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014618 AssignmentOp =
14619 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014620 if (AssignmentOp.isInvalid())
14621 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014622
14623 // No need to mark vars as copyprivate, they are already threadprivate or
14624 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014625 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014626 Vars.push_back(
14627 VD ? RefExpr->IgnoreParens()
14628 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014629 SrcExprs.push_back(PseudoSrcExpr);
14630 DstExprs.push_back(PseudoDstExpr);
14631 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014632 }
14633
14634 if (Vars.empty())
14635 return nullptr;
14636
Alexey Bataeva63048e2015-03-23 06:18:07 +000014637 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14638 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014639}
14640
Alexey Bataev6125da92014-07-21 11:26:11 +000014641OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14642 SourceLocation StartLoc,
14643 SourceLocation LParenLoc,
14644 SourceLocation EndLoc) {
14645 if (VarList.empty())
14646 return nullptr;
14647
14648 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14649}
Alexey Bataevdea47612014-07-23 07:46:59 +000014650
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014651OMPClause *
14652Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14653 SourceLocation DepLoc, SourceLocation ColonLoc,
14654 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14655 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014656 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014657 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014658 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014659 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014660 return nullptr;
14661 }
14662 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014663 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14664 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014665 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014666 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014667 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14668 /*Last=*/OMPC_DEPEND_unknown, Except)
14669 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014670 return nullptr;
14671 }
14672 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014673 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014674 llvm::APSInt DepCounter(/*BitWidth=*/32);
14675 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014676 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14677 if (const Expr *OrderedCountExpr =
14678 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014679 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14680 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014681 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014682 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014683 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014684 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14685 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14686 // It will be analyzed later.
14687 Vars.push_back(RefExpr);
14688 continue;
14689 }
14690
14691 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014692 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014693 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014694 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014695 DepCounter >= TotalDepCount) {
14696 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14697 continue;
14698 }
14699 ++DepCounter;
14700 // OpenMP [2.13.9, Summary]
14701 // depend(dependence-type : vec), where dependence-type is:
14702 // 'sink' and where vec is the iteration vector, which has the form:
14703 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14704 // where n is the value specified by the ordered clause in the loop
14705 // directive, xi denotes the loop iteration variable of the i-th nested
14706 // loop associated with the loop directive, and di is a constant
14707 // non-negative integer.
14708 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014709 // It will be analyzed later.
14710 Vars.push_back(RefExpr);
14711 continue;
14712 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014713 SimpleExpr = SimpleExpr->IgnoreImplicit();
14714 OverloadedOperatorKind OOK = OO_None;
14715 SourceLocation OOLoc;
14716 Expr *LHS = SimpleExpr;
14717 Expr *RHS = nullptr;
14718 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14719 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14720 OOLoc = BO->getOperatorLoc();
14721 LHS = BO->getLHS()->IgnoreParenImpCasts();
14722 RHS = BO->getRHS()->IgnoreParenImpCasts();
14723 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14724 OOK = OCE->getOperator();
14725 OOLoc = OCE->getOperatorLoc();
14726 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14727 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14728 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14729 OOK = MCE->getMethodDecl()
14730 ->getNameInfo()
14731 .getName()
14732 .getCXXOverloadedOperator();
14733 OOLoc = MCE->getCallee()->getExprLoc();
14734 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14735 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014736 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014737 SourceLocation ELoc;
14738 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014739 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014740 if (Res.second) {
14741 // It will be analyzed later.
14742 Vars.push_back(RefExpr);
14743 }
14744 ValueDecl *D = Res.first;
14745 if (!D)
14746 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014747
Alexey Bataev17daedf2018-02-15 22:42:57 +000014748 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14749 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14750 continue;
14751 }
14752 if (RHS) {
14753 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14754 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14755 if (RHSRes.isInvalid())
14756 continue;
14757 }
14758 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014759 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014760 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014761 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014762 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014763 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014764 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14765 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014766 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014767 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014768 continue;
14769 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014770 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014771 } else {
14772 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14773 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14774 (ASE &&
14775 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14776 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14777 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14778 << RefExpr->getSourceRange();
14779 continue;
14780 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014781
14782 ExprResult Res;
14783 {
14784 Sema::TentativeAnalysisScope Trap(*this);
14785 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14786 RefExpr->IgnoreParenImpCasts());
14787 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014788 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14789 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14790 << RefExpr->getSourceRange();
14791 continue;
14792 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014793 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014794 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014795 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014796
14797 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14798 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014799 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014800 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
14801 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14802 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
14803 }
14804 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14805 Vars.empty())
14806 return nullptr;
14807
Alexey Bataev8b427062016-05-25 12:36:08 +000014808 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000014809 DepKind, DepLoc, ColonLoc, Vars,
14810 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000014811 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14812 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000014813 DSAStack->addDoacrossDependClause(C, OpsOffs);
14814 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014815}
Michael Wonge710d542015-08-07 16:16:36 +000014816
14817OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14818 SourceLocation LParenLoc,
14819 SourceLocation EndLoc) {
14820 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014821 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000014822
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014823 // OpenMP [2.9.1, Restrictions]
14824 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014825 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000014826 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014827 return nullptr;
14828
Alexey Bataev931e19b2017-10-02 16:32:39 +000014829 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014830 OpenMPDirectiveKind CaptureRegion =
14831 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
14832 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014833 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014834 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014835 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14836 HelperValStmt = buildPreInits(Context, Captures);
14837 }
14838
Alexey Bataev8451efa2018-01-15 19:06:12 +000014839 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14840 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000014841}
Kelvin Li0bff7af2015-11-23 05:32:03 +000014842
Alexey Bataeve3727102018-04-18 15:57:46 +000014843static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000014844 DSAStackTy *Stack, QualType QTy,
14845 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000014846 NamedDecl *ND;
14847 if (QTy->isIncompleteType(&ND)) {
14848 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
14849 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014850 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000014851 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
14852 !QTy.isTrivialType(SemaRef.Context))
14853 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014854 return true;
14855}
14856
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014857/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014858/// (array section or array subscript) does NOT specify the whole size of the
14859/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014860static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014861 const Expr *E,
14862 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014863 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014864
14865 // If this is an array subscript, it refers to the whole size if the size of
14866 // the dimension is constant and equals 1. Also, an array section assumes the
14867 // format of an array subscript if no colon is used.
14868 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014869 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014870 return ATy->getSize().getSExtValue() != 1;
14871 // Size can't be evaluated statically.
14872 return false;
14873 }
14874
14875 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014876 const Expr *LowerBound = OASE->getLowerBound();
14877 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014878
14879 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000014880 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014881 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000014882 Expr::EvalResult Result;
14883 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014884 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000014885
14886 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014887 if (ConstLowerBound.getSExtValue())
14888 return true;
14889 }
14890
14891 // If we don't have a length we covering the whole dimension.
14892 if (!Length)
14893 return false;
14894
14895 // If the base is a pointer, we don't have a way to get the size of the
14896 // pointee.
14897 if (BaseQTy->isPointerType())
14898 return false;
14899
14900 // We can only check if the length is the same as the size of the dimension
14901 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000014902 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014903 if (!CATy)
14904 return false;
14905
Fangrui Song407659a2018-11-30 23:41:18 +000014906 Expr::EvalResult Result;
14907 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014908 return false; // Can't get the integer value as a constant.
14909
Fangrui Song407659a2018-11-30 23:41:18 +000014910 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014911 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
14912}
14913
14914// Return true if it can be proven that the provided array expression (array
14915// section or array subscript) does NOT specify a single element of the array
14916// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014917static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000014918 const Expr *E,
14919 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014920 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014921
14922 // An array subscript always refer to a single element. Also, an array section
14923 // assumes the format of an array subscript if no colon is used.
14924 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
14925 return false;
14926
14927 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014928 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014929
14930 // If we don't have a length we have to check if the array has unitary size
14931 // for this dimension. Also, we should always expect a length if the base type
14932 // is pointer.
14933 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014934 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014935 return ATy->getSize().getSExtValue() != 1;
14936 // We cannot assume anything.
14937 return false;
14938 }
14939
14940 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000014941 Expr::EvalResult Result;
14942 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014943 return false; // Can't get the integer value as a constant.
14944
Fangrui Song407659a2018-11-30 23:41:18 +000014945 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014946 return ConstLength.getSExtValue() != 1;
14947}
14948
Samuel Antao661c0902016-05-26 17:39:58 +000014949// Return the expression of the base of the mappable expression or null if it
14950// cannot be determined and do all the necessary checks to see if the expression
14951// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000014952// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014953static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000014954 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000014955 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014956 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014957 SourceLocation ELoc = E->getExprLoc();
14958 SourceRange ERange = E->getSourceRange();
14959
14960 // The base of elements of list in a map clause have to be either:
14961 // - a reference to variable or field.
14962 // - a member expression.
14963 // - an array expression.
14964 //
14965 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
14966 // reference to 'r'.
14967 //
14968 // If we have:
14969 //
14970 // struct SS {
14971 // Bla S;
14972 // foo() {
14973 // #pragma omp target map (S.Arr[:12]);
14974 // }
14975 // }
14976 //
14977 // We want to retrieve the member expression 'this->S';
14978
Alexey Bataeve3727102018-04-18 15:57:46 +000014979 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014980
Samuel Antao5de996e2016-01-22 20:21:36 +000014981 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
14982 // If a list item is an array section, it must specify contiguous storage.
14983 //
14984 // For this restriction it is sufficient that we make sure only references
14985 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014986 // exist except in the rightmost expression (unless they cover the whole
14987 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000014988 //
14989 // r.ArrS[3:5].Arr[6:7]
14990 //
14991 // r.ArrS[3:5].x
14992 //
14993 // but these would be valid:
14994 // r.ArrS[3].Arr[6:7]
14995 //
14996 // r.ArrS[3].x
14997
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014998 bool AllowUnitySizeArraySection = true;
14999 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015000
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015001 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015002 E = E->IgnoreParenImpCasts();
15003
15004 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15005 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015006 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015007
15008 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015009
15010 // If we got a reference to a declaration, we should not expect any array
15011 // section before that.
15012 AllowUnitySizeArraySection = false;
15013 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015014
15015 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015016 CurComponents.emplace_back(CurE, CurE->getDecl());
15017 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015018 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015019
15020 if (isa<CXXThisExpr>(BaseE))
15021 // We found a base expression: this->Val.
15022 RelevantExpr = CurE;
15023 else
15024 E = BaseE;
15025
15026 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015027 if (!NoDiagnose) {
15028 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15029 << CurE->getSourceRange();
15030 return nullptr;
15031 }
15032 if (RelevantExpr)
15033 return nullptr;
15034 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015035 }
15036
15037 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15038
15039 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15040 // A bit-field cannot appear in a map clause.
15041 //
15042 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015043 if (!NoDiagnose) {
15044 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15045 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15046 return nullptr;
15047 }
15048 if (RelevantExpr)
15049 return nullptr;
15050 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015051 }
15052
15053 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15054 // If the type of a list item is a reference to a type T then the type
15055 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015056 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015057
15058 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15059 // A list item cannot be a variable that is a member of a structure with
15060 // a union type.
15061 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015062 if (CurType->isUnionType()) {
15063 if (!NoDiagnose) {
15064 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15065 << CurE->getSourceRange();
15066 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015067 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015068 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015069 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015070
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015071 // If we got a member expression, we should not expect any array section
15072 // before that:
15073 //
15074 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15075 // If a list item is an element of a structure, only the rightmost symbol
15076 // of the variable reference can be an array section.
15077 //
15078 AllowUnitySizeArraySection = false;
15079 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015080
15081 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015082 CurComponents.emplace_back(CurE, FD);
15083 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015084 E = CurE->getBase()->IgnoreParenImpCasts();
15085
15086 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015087 if (!NoDiagnose) {
15088 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15089 << 0 << CurE->getSourceRange();
15090 return nullptr;
15091 }
15092 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015093 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015094
15095 // If we got an array subscript that express the whole dimension we
15096 // can have any array expressions before. If it only expressing part of
15097 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015098 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015099 E->getType()))
15100 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015101
Patrick Lystere13b1e32019-01-02 19:28:48 +000015102 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15103 Expr::EvalResult Result;
15104 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15105 if (!Result.Val.getInt().isNullValue()) {
15106 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15107 diag::err_omp_invalid_map_this_expr);
15108 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15109 diag::note_omp_invalid_subscript_on_this_ptr_map);
15110 }
15111 }
15112 RelevantExpr = TE;
15113 }
15114
Samuel Antao90927002016-04-26 14:54:23 +000015115 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015116 CurComponents.emplace_back(CurE, nullptr);
15117 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015118 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015119 E = CurE->getBase()->IgnoreParenImpCasts();
15120
Alexey Bataev27041fa2017-12-05 15:22:49 +000015121 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015122 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15123
Samuel Antao5de996e2016-01-22 20:21:36 +000015124 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15125 // If the type of a list item is a reference to a type T then the type
15126 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015127 if (CurType->isReferenceType())
15128 CurType = CurType->getPointeeType();
15129
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015130 bool IsPointer = CurType->isAnyPointerType();
15131
15132 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015133 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15134 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015135 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015136 }
15137
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015138 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015139 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015140 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015141 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015142
Samuel Antaodab51bb2016-07-18 23:22:11 +000015143 if (AllowWholeSizeArraySection) {
15144 // Any array section is currently allowed. Allowing a whole size array
15145 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015146 //
15147 // If this array section refers to the whole dimension we can still
15148 // accept other array sections before this one, except if the base is a
15149 // pointer. Otherwise, only unitary sections are accepted.
15150 if (NotWhole || IsPointer)
15151 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015152 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015153 // A unity or whole array section is not allowed and that is not
15154 // compatible with the properties of the current array section.
15155 SemaRef.Diag(
15156 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15157 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015158 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015159 }
Samuel Antao90927002016-04-26 14:54:23 +000015160
Patrick Lystere13b1e32019-01-02 19:28:48 +000015161 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15162 Expr::EvalResult ResultR;
15163 Expr::EvalResult ResultL;
15164 if (CurE->getLength()->EvaluateAsInt(ResultR,
15165 SemaRef.getASTContext())) {
15166 if (!ResultR.Val.getInt().isOneValue()) {
15167 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15168 diag::err_omp_invalid_map_this_expr);
15169 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15170 diag::note_omp_invalid_length_on_this_ptr_mapping);
15171 }
15172 }
15173 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15174 ResultL, SemaRef.getASTContext())) {
15175 if (!ResultL.Val.getInt().isNullValue()) {
15176 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15177 diag::err_omp_invalid_map_this_expr);
15178 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15179 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15180 }
15181 }
15182 RelevantExpr = TE;
15183 }
15184
Samuel Antao90927002016-04-26 14:54:23 +000015185 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015186 CurComponents.emplace_back(CurE, nullptr);
15187 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015188 if (!NoDiagnose) {
15189 // If nothing else worked, this is not a valid map clause expression.
15190 SemaRef.Diag(
15191 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15192 << ERange;
15193 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015194 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015195 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015196 }
15197
15198 return RelevantExpr;
15199}
15200
15201// Return true if expression E associated with value VD has conflicts with other
15202// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015203static bool checkMapConflicts(
15204 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015205 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015206 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15207 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015208 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015209 SourceLocation ELoc = E->getExprLoc();
15210 SourceRange ERange = E->getSourceRange();
15211
15212 // In order to easily check the conflicts we need to match each component of
15213 // the expression under test with the components of the expressions that are
15214 // already in the stack.
15215
Samuel Antao5de996e2016-01-22 20:21:36 +000015216 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015217 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015218 "Map clause expression with unexpected base!");
15219
15220 // Variables to help detecting enclosing problems in data environment nests.
15221 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015222 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015223
Samuel Antao90927002016-04-26 14:54:23 +000015224 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15225 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015226 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15227 ERange, CKind, &EnclosingExpr,
15228 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15229 StackComponents,
15230 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015231 assert(!StackComponents.empty() &&
15232 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015233 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015234 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015235 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015236
Samuel Antao90927002016-04-26 14:54:23 +000015237 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015238 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015239
Samuel Antao5de996e2016-01-22 20:21:36 +000015240 // Expressions must start from the same base. Here we detect at which
15241 // point both expressions diverge from each other and see if we can
15242 // detect if the memory referred to both expressions is contiguous and
15243 // do not overlap.
15244 auto CI = CurComponents.rbegin();
15245 auto CE = CurComponents.rend();
15246 auto SI = StackComponents.rbegin();
15247 auto SE = StackComponents.rend();
15248 for (; CI != CE && SI != SE; ++CI, ++SI) {
15249
15250 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15251 // At most one list item can be an array item derived from a given
15252 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015253 if (CurrentRegionOnly &&
15254 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15255 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15256 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15257 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15258 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015259 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015260 << CI->getAssociatedExpression()->getSourceRange();
15261 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15262 diag::note_used_here)
15263 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015264 return true;
15265 }
15266
15267 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015268 if (CI->getAssociatedExpression()->getStmtClass() !=
15269 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015270 break;
15271
15272 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015273 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015274 break;
15275 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015276 // Check if the extra components of the expressions in the enclosing
15277 // data environment are redundant for the current base declaration.
15278 // If they are, the maps completely overlap, which is legal.
15279 for (; SI != SE; ++SI) {
15280 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015281 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015282 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015283 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015284 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015285 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015286 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015287 Type =
15288 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15289 }
15290 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015291 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015292 SemaRef, SI->getAssociatedExpression(), Type))
15293 break;
15294 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015295
15296 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15297 // List items of map clauses in the same construct must not share
15298 // original storage.
15299 //
15300 // If the expressions are exactly the same or one is a subset of the
15301 // other, it means they are sharing storage.
15302 if (CI == CE && SI == SE) {
15303 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015304 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015305 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015306 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015307 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015308 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15309 << ERange;
15310 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015311 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15312 << RE->getSourceRange();
15313 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015314 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015315 // If we find the same expression in the enclosing data environment,
15316 // that is legal.
15317 IsEnclosedByDataEnvironmentExpr = true;
15318 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015319 }
15320
Samuel Antao90927002016-04-26 14:54:23 +000015321 QualType DerivedType =
15322 std::prev(CI)->getAssociatedDeclaration()->getType();
15323 SourceLocation DerivedLoc =
15324 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015325
15326 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15327 // If the type of a list item is a reference to a type T then the type
15328 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015329 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015330
15331 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15332 // A variable for which the type is pointer and an array section
15333 // derived from that variable must not appear as list items of map
15334 // clauses of the same construct.
15335 //
15336 // Also, cover one of the cases in:
15337 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15338 // If any part of the original storage of a list item has corresponding
15339 // storage in the device data environment, all of the original storage
15340 // must have corresponding storage in the device data environment.
15341 //
15342 if (DerivedType->isAnyPointerType()) {
15343 if (CI == CE || SI == SE) {
15344 SemaRef.Diag(
15345 DerivedLoc,
15346 diag::err_omp_pointer_mapped_along_with_derived_section)
15347 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015348 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15349 << RE->getSourceRange();
15350 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015351 }
15352 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015353 SI->getAssociatedExpression()->getStmtClass() ||
15354 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15355 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015356 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015357 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015358 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015359 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15360 << RE->getSourceRange();
15361 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015362 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015363 }
15364
15365 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15366 // List items of map clauses in the same construct must not share
15367 // original storage.
15368 //
15369 // An expression is a subset of the other.
15370 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015371 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015372 if (CI != CE || SI != SE) {
15373 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15374 // a pointer.
15375 auto Begin =
15376 CI != CE ? CurComponents.begin() : StackComponents.begin();
15377 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15378 auto It = Begin;
15379 while (It != End && !It->getAssociatedDeclaration())
15380 std::advance(It, 1);
15381 assert(It != End &&
15382 "Expected at least one component with the declaration.");
15383 if (It != Begin && It->getAssociatedDeclaration()
15384 ->getType()
15385 .getCanonicalType()
15386 ->isAnyPointerType()) {
15387 IsEnclosedByDataEnvironmentExpr = false;
15388 EnclosingExpr = nullptr;
15389 return false;
15390 }
15391 }
Samuel Antao661c0902016-05-26 17:39:58 +000015392 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015393 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015394 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015395 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15396 << ERange;
15397 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015398 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15399 << RE->getSourceRange();
15400 return true;
15401 }
15402
15403 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015404 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015405 if (!CurrentRegionOnly && SI != SE)
15406 EnclosingExpr = RE;
15407
15408 // The current expression is a subset of the expression in the data
15409 // environment.
15410 IsEnclosedByDataEnvironmentExpr |=
15411 (!CurrentRegionOnly && CI != CE && SI == SE);
15412
15413 return false;
15414 });
15415
15416 if (CurrentRegionOnly)
15417 return FoundError;
15418
15419 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15420 // If any part of the original storage of a list item has corresponding
15421 // storage in the device data environment, all of the original storage must
15422 // have corresponding storage in the device data environment.
15423 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15424 // If a list item is an element of a structure, and a different element of
15425 // the structure has a corresponding list item in the device data environment
15426 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015427 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015428 // data environment prior to the task encountering the construct.
15429 //
15430 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15431 SemaRef.Diag(ELoc,
15432 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15433 << ERange;
15434 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15435 << EnclosingExpr->getSourceRange();
15436 return true;
15437 }
15438
15439 return FoundError;
15440}
15441
Michael Kruse4304e9d2019-02-19 16:38:20 +000015442// Look up the user-defined mapper given the mapper name and mapped type, and
15443// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015444static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15445 CXXScopeSpec &MapperIdScopeSpec,
15446 const DeclarationNameInfo &MapperId,
15447 QualType Type,
15448 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015449 if (MapperIdScopeSpec.isInvalid())
15450 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015451 // Get the actual type for the array type.
15452 if (Type->isArrayType()) {
15453 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15454 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15455 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015456 // Find all user-defined mappers with the given MapperId.
15457 SmallVector<UnresolvedSet<8>, 4> Lookups;
15458 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15459 Lookup.suppressDiagnostics();
15460 if (S) {
15461 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15462 NamedDecl *D = Lookup.getRepresentativeDecl();
15463 while (S && !S->isDeclScope(D))
15464 S = S->getParent();
15465 if (S)
15466 S = S->getParent();
15467 Lookups.emplace_back();
15468 Lookups.back().append(Lookup.begin(), Lookup.end());
15469 Lookup.clear();
15470 }
15471 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15472 // Extract the user-defined mappers with the given MapperId.
15473 Lookups.push_back(UnresolvedSet<8>());
15474 for (NamedDecl *D : ULE->decls()) {
15475 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15476 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15477 Lookups.back().addDecl(DMD);
15478 }
15479 }
15480 // Defer the lookup for dependent types. The results will be passed through
15481 // UnresolvedMapper on instantiation.
15482 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15483 Type->isInstantiationDependentType() ||
15484 Type->containsUnexpandedParameterPack() ||
15485 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15486 return !D->isInvalidDecl() &&
15487 (D->getType()->isDependentType() ||
15488 D->getType()->isInstantiationDependentType() ||
15489 D->getType()->containsUnexpandedParameterPack());
15490 })) {
15491 UnresolvedSet<8> URS;
15492 for (const UnresolvedSet<8> &Set : Lookups) {
15493 if (Set.empty())
15494 continue;
15495 URS.append(Set.begin(), Set.end());
15496 }
15497 return UnresolvedLookupExpr::Create(
15498 SemaRef.Context, /*NamingClass=*/nullptr,
15499 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15500 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15501 }
Michael Kruse945249b2019-09-26 22:53:01 +000015502 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015503 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15504 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015505 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15506 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15507 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15508 return ExprError();
15509 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015510 // Perform argument dependent lookup.
15511 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15512 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15513 // Return the first user-defined mapper with the desired type.
15514 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15515 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15516 if (!D->isInvalidDecl() &&
15517 SemaRef.Context.hasSameType(D->getType(), Type))
15518 return D;
15519 return nullptr;
15520 }))
15521 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15522 // Find the first user-defined mapper with a type derived from the desired
15523 // type.
15524 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15525 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15526 if (!D->isInvalidDecl() &&
15527 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15528 !Type.isMoreQualifiedThan(D->getType()))
15529 return D;
15530 return nullptr;
15531 })) {
15532 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15533 /*DetectVirtual=*/false);
15534 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15535 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15536 VD->getType().getUnqualifiedType()))) {
15537 if (SemaRef.CheckBaseClassAccess(
15538 Loc, VD->getType(), Type, Paths.front(),
15539 /*DiagID=*/0) != Sema::AR_inaccessible) {
15540 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15541 }
15542 }
15543 }
15544 }
15545 // Report error if a mapper is specified, but cannot be found.
15546 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15547 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15548 << Type << MapperId.getName();
15549 return ExprError();
15550 }
15551 return ExprEmpty();
15552}
15553
Samuel Antao661c0902016-05-26 17:39:58 +000015554namespace {
15555// Utility struct that gathers all the related lists associated with a mappable
15556// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015557struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015558 // The list of expressions.
15559 ArrayRef<Expr *> VarList;
15560 // The list of processed expressions.
15561 SmallVector<Expr *, 16> ProcessedVarList;
15562 // The mappble components for each expression.
15563 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15564 // The base declaration of the variable.
15565 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015566 // The reference to the user-defined mapper associated with every expression.
15567 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015568
15569 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15570 // We have a list of components and base declarations for each entry in the
15571 // variable list.
15572 VarComponents.reserve(VarList.size());
15573 VarBaseDeclarations.reserve(VarList.size());
15574 }
15575};
15576}
15577
15578// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015579// \a CKind. In the check process the valid expressions, mappable expression
15580// components, variables, and user-defined mappers are extracted and used to
15581// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15582// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15583// and \a MapperId are expected to be valid if the clause kind is 'map'.
15584static void checkMappableExpressionList(
15585 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15586 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015587 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15588 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015589 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015590 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015591 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15592 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015593 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015594
15595 // If the identifier of user-defined mapper is not specified, it is "default".
15596 // We do not change the actual name in this clause to distinguish whether a
15597 // mapper is specified explicitly, i.e., it is not explicitly specified when
15598 // MapperId.getName() is empty.
15599 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15600 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15601 MapperId.setName(DeclNames.getIdentifier(
15602 &SemaRef.getASTContext().Idents.get("default")));
15603 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015604
15605 // Iterators to find the current unresolved mapper expression.
15606 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15607 bool UpdateUMIt = false;
15608 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015609
Samuel Antao90927002016-04-26 14:54:23 +000015610 // Keep track of the mappable components and base declarations in this clause.
15611 // Each entry in the list is going to have a list of components associated. We
15612 // record each set of the components so that we can build the clause later on.
15613 // In the end we should have the same amount of declarations and component
15614 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015615
Alexey Bataeve3727102018-04-18 15:57:46 +000015616 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015617 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015618 SourceLocation ELoc = RE->getExprLoc();
15619
Michael Kruse4304e9d2019-02-19 16:38:20 +000015620 // Find the current unresolved mapper expression.
15621 if (UpdateUMIt && UMIt != UMEnd) {
15622 UMIt++;
15623 assert(
15624 UMIt != UMEnd &&
15625 "Expect the size of UnresolvedMappers to match with that of VarList");
15626 }
15627 UpdateUMIt = true;
15628 if (UMIt != UMEnd)
15629 UnresolvedMapper = *UMIt;
15630
Alexey Bataeve3727102018-04-18 15:57:46 +000015631 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015632
15633 if (VE->isValueDependent() || VE->isTypeDependent() ||
15634 VE->isInstantiationDependent() ||
15635 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015636 // Try to find the associated user-defined mapper.
15637 ExprResult ER = buildUserDefinedMapperRef(
15638 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15639 VE->getType().getCanonicalType(), UnresolvedMapper);
15640 if (ER.isInvalid())
15641 continue;
15642 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015643 // We can only analyze this information once the missing information is
15644 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015645 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015646 continue;
15647 }
15648
Alexey Bataeve3727102018-04-18 15:57:46 +000015649 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015650
Samuel Antao5de996e2016-01-22 20:21:36 +000015651 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015652 SemaRef.Diag(ELoc,
15653 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015654 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015655 continue;
15656 }
15657
Samuel Antao90927002016-04-26 14:54:23 +000015658 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15659 ValueDecl *CurDeclaration = nullptr;
15660
15661 // Obtain the array or member expression bases if required. Also, fill the
15662 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015663 const Expr *BE = checkMapClauseExpressionBase(
15664 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015665 if (!BE)
15666 continue;
15667
Samuel Antao90927002016-04-26 14:54:23 +000015668 assert(!CurComponents.empty() &&
15669 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015670
Patrick Lystere13b1e32019-01-02 19:28:48 +000015671 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15672 // Add store "this" pointer to class in DSAStackTy for future checking
15673 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015674 // Try to find the associated user-defined mapper.
15675 ExprResult ER = buildUserDefinedMapperRef(
15676 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15677 VE->getType().getCanonicalType(), UnresolvedMapper);
15678 if (ER.isInvalid())
15679 continue;
15680 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015681 // Skip restriction checking for variable or field declarations
15682 MVLI.ProcessedVarList.push_back(RE);
15683 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15684 MVLI.VarComponents.back().append(CurComponents.begin(),
15685 CurComponents.end());
15686 MVLI.VarBaseDeclarations.push_back(nullptr);
15687 continue;
15688 }
15689
Samuel Antao90927002016-04-26 14:54:23 +000015690 // For the following checks, we rely on the base declaration which is
15691 // expected to be associated with the last component. The declaration is
15692 // expected to be a variable or a field (if 'this' is being mapped).
15693 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15694 assert(CurDeclaration && "Null decl on map clause.");
15695 assert(
15696 CurDeclaration->isCanonicalDecl() &&
15697 "Expecting components to have associated only canonical declarations.");
15698
15699 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015700 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015701
15702 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015703 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015704
15705 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015706 // threadprivate variables cannot appear in a map clause.
15707 // OpenMP 4.5 [2.10.5, target update Construct]
15708 // threadprivate variables cannot appear in a from clause.
15709 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015710 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015711 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15712 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015713 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015714 continue;
15715 }
15716
Samuel Antao5de996e2016-01-22 20:21:36 +000015717 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15718 // A list item cannot appear in both a map clause and a data-sharing
15719 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015720
Samuel Antao5de996e2016-01-22 20:21:36 +000015721 // Check conflicts with other map clause expressions. We check the conflicts
15722 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015723 // environment, because the restrictions are different. We only have to
15724 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015725 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015726 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015727 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015728 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015729 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015730 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015731 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015732
Samuel Antao661c0902016-05-26 17:39:58 +000015733 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015734 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15735 // If the type of a list item is a reference to a type T then the type will
15736 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015737 auto I = llvm::find_if(
15738 CurComponents,
15739 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15740 return MC.getAssociatedDeclaration();
15741 });
15742 assert(I != CurComponents.end() && "Null decl on map clause.");
15743 QualType Type =
15744 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015745
Samuel Antao661c0902016-05-26 17:39:58 +000015746 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15747 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000015748 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000015749 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000015750 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000015751 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000015752 continue;
15753
Samuel Antao661c0902016-05-26 17:39:58 +000015754 if (CKind == OMPC_map) {
15755 // target enter data
15756 // OpenMP [2.10.2, Restrictions, p. 99]
15757 // A map-type must be specified in all map clauses and must be either
15758 // to or alloc.
15759 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15760 if (DKind == OMPD_target_enter_data &&
15761 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15762 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15763 << (IsMapTypeImplicit ? 1 : 0)
15764 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15765 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015766 continue;
15767 }
Samuel Antao661c0902016-05-26 17:39:58 +000015768
15769 // target exit_data
15770 // OpenMP [2.10.3, Restrictions, p. 102]
15771 // A map-type must be specified in all map clauses and must be either
15772 // from, release, or delete.
15773 if (DKind == OMPD_target_exit_data &&
15774 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15775 MapType == OMPC_MAP_delete)) {
15776 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15777 << (IsMapTypeImplicit ? 1 : 0)
15778 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15779 << getOpenMPDirectiveName(DKind);
15780 continue;
15781 }
15782
15783 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15784 // A list item cannot appear in both a map clause and a data-sharing
15785 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000015786 //
15787 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15788 // A list item cannot appear in both a map clause and a data-sharing
15789 // attribute clause on the same construct unless the construct is a
15790 // combined construct.
15791 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15792 isOpenMPTargetExecutionDirective(DKind)) ||
15793 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015794 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015795 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000015796 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000015797 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000015798 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000015799 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015800 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000015801 continue;
15802 }
15803 }
Michael Kruse01f670d2019-02-22 22:29:42 +000015804 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015805
Michael Kruse01f670d2019-02-22 22:29:42 +000015806 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000015807 ExprResult ER = buildUserDefinedMapperRef(
15808 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15809 Type.getCanonicalType(), UnresolvedMapper);
15810 if (ER.isInvalid())
15811 continue;
15812 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015813
Samuel Antao90927002016-04-26 14:54:23 +000015814 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000015815 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000015816
15817 // Store the components in the stack so that they can be used to check
15818 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000015819 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15820 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000015821
15822 // Save the components and declaration to create the clause. For purposes of
15823 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000015824 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000015825 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15826 MVLI.VarComponents.back().append(CurComponents.begin(),
15827 CurComponents.end());
15828 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15829 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015830 }
Samuel Antao661c0902016-05-26 17:39:58 +000015831}
15832
Michael Kruse4304e9d2019-02-19 16:38:20 +000015833OMPClause *Sema::ActOnOpenMPMapClause(
15834 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15835 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15836 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15837 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15838 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15839 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15840 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15841 OMPC_MAP_MODIFIER_unknown,
15842 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000015843 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15844
15845 // Process map-type-modifiers, flag errors for duplicate modifiers.
15846 unsigned Count = 0;
15847 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
15848 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
15849 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
15850 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
15851 continue;
15852 }
15853 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000015854 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000015855 Modifiers[Count] = MapTypeModifiers[I];
15856 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
15857 ++Count;
15858 }
15859
Michael Kruse4304e9d2019-02-19 16:38:20 +000015860 MappableVarListInfo MVLI(VarList);
15861 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015862 MapperIdScopeSpec, MapperId, UnresolvedMappers,
15863 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000015864
Samuel Antao5de996e2016-01-22 20:21:36 +000015865 // We need to produce a map clause even if we don't have variables so that
15866 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000015867 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
15868 MVLI.VarBaseDeclarations, MVLI.VarComponents,
15869 MVLI.UDMapperList, Modifiers, ModifiersLoc,
15870 MapperIdScopeSpec.getWithLocInContext(Context),
15871 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015872}
Kelvin Li099bb8c2015-11-24 20:50:12 +000015873
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015874QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
15875 TypeResult ParsedType) {
15876 assert(ParsedType.isUsable());
15877
15878 QualType ReductionType = GetTypeFromParser(ParsedType.get());
15879 if (ReductionType.isNull())
15880 return QualType();
15881
15882 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
15883 // A type name in a declare reduction directive cannot be a function type, an
15884 // array type, a reference type, or a type qualified with const, volatile or
15885 // restrict.
15886 if (ReductionType.hasQualifiers()) {
15887 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
15888 return QualType();
15889 }
15890
15891 if (ReductionType->isFunctionType()) {
15892 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
15893 return QualType();
15894 }
15895 if (ReductionType->isReferenceType()) {
15896 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
15897 return QualType();
15898 }
15899 if (ReductionType->isArrayType()) {
15900 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
15901 return QualType();
15902 }
15903 return ReductionType;
15904}
15905
15906Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
15907 Scope *S, DeclContext *DC, DeclarationName Name,
15908 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
15909 AccessSpecifier AS, Decl *PrevDeclInScope) {
15910 SmallVector<Decl *, 8> Decls;
15911 Decls.reserve(ReductionTypes.size());
15912
15913 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000015914 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015915 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
15916 // A reduction-identifier may not be re-declared in the current scope for the
15917 // same type or for a type that is compatible according to the base language
15918 // rules.
15919 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15920 OMPDeclareReductionDecl *PrevDRD = nullptr;
15921 bool InCompoundScope = true;
15922 if (S != nullptr) {
15923 // Find previous declaration with the same name not referenced in other
15924 // declarations.
15925 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15926 InCompoundScope =
15927 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15928 LookupName(Lookup, S);
15929 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15930 /*AllowInlineNamespace=*/false);
15931 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000015932 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015933 while (Filter.hasNext()) {
15934 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
15935 if (InCompoundScope) {
15936 auto I = UsedAsPrevious.find(PrevDecl);
15937 if (I == UsedAsPrevious.end())
15938 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000015939 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015940 UsedAsPrevious[D] = true;
15941 }
15942 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15943 PrevDecl->getLocation();
15944 }
15945 Filter.done();
15946 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015947 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015948 if (!PrevData.second) {
15949 PrevDRD = PrevData.first;
15950 break;
15951 }
15952 }
15953 }
15954 } else if (PrevDeclInScope != nullptr) {
15955 auto *PrevDRDInScope = PrevDRD =
15956 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
15957 do {
15958 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
15959 PrevDRDInScope->getLocation();
15960 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
15961 } while (PrevDRDInScope != nullptr);
15962 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015963 for (const auto &TyData : ReductionTypes) {
15964 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015965 bool Invalid = false;
15966 if (I != PreviousRedeclTypes.end()) {
15967 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
15968 << TyData.first;
15969 Diag(I->second, diag::note_previous_definition);
15970 Invalid = true;
15971 }
15972 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
15973 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
15974 Name, TyData.first, PrevDRD);
15975 DC->addDecl(DRD);
15976 DRD->setAccess(AS);
15977 Decls.push_back(DRD);
15978 if (Invalid)
15979 DRD->setInvalidDecl();
15980 else
15981 PrevDRD = DRD;
15982 }
15983
15984 return DeclGroupPtrTy::make(
15985 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
15986}
15987
15988void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
15989 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15990
15991 // Enter new function scope.
15992 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015993 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015994 getCurFunction()->setHasOMPDeclareReductionCombiner();
15995
15996 if (S != nullptr)
15997 PushDeclContext(S, DRD);
15998 else
15999 CurContext = DRD;
16000
Faisal Valid143a0c2017-04-01 21:30:49 +000016001 PushExpressionEvaluationContext(
16002 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016003
16004 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016005 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16006 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16007 // uses semantics of argument handles by value, but it should be passed by
16008 // reference. C lang does not support references, so pass all parameters as
16009 // pointers.
16010 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016011 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016012 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016013 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16014 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16015 // uses semantics of argument handles by value, but it should be passed by
16016 // reference. C lang does not support references, so pass all parameters as
16017 // pointers.
16018 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016019 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016020 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16021 if (S != nullptr) {
16022 PushOnScopeChains(OmpInParm, S);
16023 PushOnScopeChains(OmpOutParm, S);
16024 } else {
16025 DRD->addDecl(OmpInParm);
16026 DRD->addDecl(OmpOutParm);
16027 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016028 Expr *InE =
16029 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16030 Expr *OutE =
16031 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16032 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016033}
16034
16035void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16036 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16037 DiscardCleanupsInEvaluationContext();
16038 PopExpressionEvaluationContext();
16039
16040 PopDeclContext();
16041 PopFunctionScopeInfo();
16042
16043 if (Combiner != nullptr)
16044 DRD->setCombiner(Combiner);
16045 else
16046 DRD->setInvalidDecl();
16047}
16048
Alexey Bataev070f43a2017-09-06 14:49:58 +000016049VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016050 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16051
16052 // Enter new function scope.
16053 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016054 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016055
16056 if (S != nullptr)
16057 PushDeclContext(S, DRD);
16058 else
16059 CurContext = DRD;
16060
Faisal Valid143a0c2017-04-01 21:30:49 +000016061 PushExpressionEvaluationContext(
16062 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016063
16064 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016065 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16066 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16067 // uses semantics of argument handles by value, but it should be passed by
16068 // reference. C lang does not support references, so pass all parameters as
16069 // pointers.
16070 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016071 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016072 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016073 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16074 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16075 // uses semantics of argument handles by value, but it should be passed by
16076 // reference. C lang does not support references, so pass all parameters as
16077 // pointers.
16078 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016079 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016080 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016081 if (S != nullptr) {
16082 PushOnScopeChains(OmpPrivParm, S);
16083 PushOnScopeChains(OmpOrigParm, S);
16084 } else {
16085 DRD->addDecl(OmpPrivParm);
16086 DRD->addDecl(OmpOrigParm);
16087 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016088 Expr *OrigE =
16089 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16090 Expr *PrivE =
16091 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16092 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016093 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016094}
16095
Alexey Bataev070f43a2017-09-06 14:49:58 +000016096void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16097 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016098 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16099 DiscardCleanupsInEvaluationContext();
16100 PopExpressionEvaluationContext();
16101
16102 PopDeclContext();
16103 PopFunctionScopeInfo();
16104
Alexey Bataev070f43a2017-09-06 14:49:58 +000016105 if (Initializer != nullptr) {
16106 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16107 } else if (OmpPrivParm->hasInit()) {
16108 DRD->setInitializer(OmpPrivParm->getInit(),
16109 OmpPrivParm->isDirectInit()
16110 ? OMPDeclareReductionDecl::DirectInit
16111 : OMPDeclareReductionDecl::CopyInit);
16112 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016113 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016114 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016115}
16116
16117Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16118 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016119 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016120 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016121 if (S)
16122 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16123 /*AddToContext=*/false);
16124 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016125 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016126 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016127 }
16128 return DeclReductions;
16129}
16130
Michael Kruse251e1482019-02-01 20:25:04 +000016131TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16132 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16133 QualType T = TInfo->getType();
16134 if (D.isInvalidType())
16135 return true;
16136
16137 if (getLangOpts().CPlusPlus) {
16138 // Check that there are no default arguments (C++ only).
16139 CheckExtraCXXDefaultArguments(D);
16140 }
16141
16142 return CreateParsedType(T, TInfo);
16143}
16144
16145QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16146 TypeResult ParsedType) {
16147 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16148
16149 QualType MapperType = GetTypeFromParser(ParsedType.get());
16150 assert(!MapperType.isNull() && "Expect valid mapper type");
16151
16152 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16153 // The type must be of struct, union or class type in C and C++
16154 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16155 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16156 return QualType();
16157 }
16158 return MapperType;
16159}
16160
16161OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16162 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16163 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16164 Decl *PrevDeclInScope) {
16165 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16166 forRedeclarationInCurContext());
16167 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16168 // A mapper-identifier may not be redeclared in the current scope for the
16169 // same type or for a type that is compatible according to the base language
16170 // rules.
16171 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16172 OMPDeclareMapperDecl *PrevDMD = nullptr;
16173 bool InCompoundScope = true;
16174 if (S != nullptr) {
16175 // Find previous declaration with the same name not referenced in other
16176 // declarations.
16177 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16178 InCompoundScope =
16179 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16180 LookupName(Lookup, S);
16181 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16182 /*AllowInlineNamespace=*/false);
16183 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16184 LookupResult::Filter Filter = Lookup.makeFilter();
16185 while (Filter.hasNext()) {
16186 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16187 if (InCompoundScope) {
16188 auto I = UsedAsPrevious.find(PrevDecl);
16189 if (I == UsedAsPrevious.end())
16190 UsedAsPrevious[PrevDecl] = false;
16191 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16192 UsedAsPrevious[D] = true;
16193 }
16194 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16195 PrevDecl->getLocation();
16196 }
16197 Filter.done();
16198 if (InCompoundScope) {
16199 for (const auto &PrevData : UsedAsPrevious) {
16200 if (!PrevData.second) {
16201 PrevDMD = PrevData.first;
16202 break;
16203 }
16204 }
16205 }
16206 } else if (PrevDeclInScope) {
16207 auto *PrevDMDInScope = PrevDMD =
16208 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16209 do {
16210 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16211 PrevDMDInScope->getLocation();
16212 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16213 } while (PrevDMDInScope != nullptr);
16214 }
16215 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16216 bool Invalid = false;
16217 if (I != PreviousRedeclTypes.end()) {
16218 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16219 << MapperType << Name;
16220 Diag(I->second, diag::note_previous_definition);
16221 Invalid = true;
16222 }
16223 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16224 MapperType, VN, PrevDMD);
16225 DC->addDecl(DMD);
16226 DMD->setAccess(AS);
16227 if (Invalid)
16228 DMD->setInvalidDecl();
16229
16230 // Enter new function scope.
16231 PushFunctionScope();
16232 setFunctionHasBranchProtectedScope();
16233
16234 CurContext = DMD;
16235
16236 return DMD;
16237}
16238
16239void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16240 Scope *S,
16241 QualType MapperType,
16242 SourceLocation StartLoc,
16243 DeclarationName VN) {
16244 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16245 if (S)
16246 PushOnScopeChains(VD, S);
16247 else
16248 DMD->addDecl(VD);
16249 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16250 DMD->setMapperVarRef(MapperVarRefExpr);
16251}
16252
16253Sema::DeclGroupPtrTy
16254Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16255 ArrayRef<OMPClause *> ClauseList) {
16256 PopDeclContext();
16257 PopFunctionScopeInfo();
16258
16259 if (D) {
16260 if (S)
16261 PushOnScopeChains(D, S, /*AddToContext=*/false);
16262 D->CreateClauses(Context, ClauseList);
16263 }
16264
16265 return DeclGroupPtrTy::make(DeclGroupRef(D));
16266}
16267
David Majnemer9d168222016-08-05 17:44:54 +000016268OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016269 SourceLocation StartLoc,
16270 SourceLocation LParenLoc,
16271 SourceLocation EndLoc) {
16272 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016273 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016274
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016275 // OpenMP [teams Constrcut, Restrictions]
16276 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016277 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016278 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016279 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016280
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016281 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016282 OpenMPDirectiveKind CaptureRegion =
16283 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
16284 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016285 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016286 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016287 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16288 HelperValStmt = buildPreInits(Context, Captures);
16289 }
16290
16291 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16292 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016293}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016294
16295OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16296 SourceLocation StartLoc,
16297 SourceLocation LParenLoc,
16298 SourceLocation EndLoc) {
16299 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016300 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016301
16302 // OpenMP [teams Constrcut, Restrictions]
16303 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016304 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016305 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016306 return nullptr;
16307
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016308 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016309 OpenMPDirectiveKind CaptureRegion =
16310 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
16311 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016312 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016313 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016314 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16315 HelperValStmt = buildPreInits(Context, Captures);
16316 }
16317
16318 return new (Context) OMPThreadLimitClause(
16319 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016320}
Alexey Bataeva0569352015-12-01 10:17:31 +000016321
16322OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16323 SourceLocation StartLoc,
16324 SourceLocation LParenLoc,
16325 SourceLocation EndLoc) {
16326 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016327 Stmt *HelperValStmt = nullptr;
16328 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016329
16330 // OpenMP [2.9.1, task Constrcut]
16331 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016332 if (!isNonNegativeIntegerValue(
16333 ValExpr, *this, OMPC_priority,
16334 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16335 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016336 return nullptr;
16337
Alexey Bataev31ba4762019-10-16 18:09:37 +000016338 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16339 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016340}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016341
16342OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16343 SourceLocation StartLoc,
16344 SourceLocation LParenLoc,
16345 SourceLocation EndLoc) {
16346 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016347 Stmt *HelperValStmt = nullptr;
16348 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016349
16350 // OpenMP [2.9.2, taskloop Constrcut]
16351 // The parameter of the grainsize clause must be a positive integer
16352 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016353 if (!isNonNegativeIntegerValue(
16354 ValExpr, *this, OMPC_grainsize,
16355 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16356 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016357 return nullptr;
16358
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016359 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16360 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016361}
Alexey Bataev382967a2015-12-08 12:06:20 +000016362
16363OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16364 SourceLocation StartLoc,
16365 SourceLocation LParenLoc,
16366 SourceLocation EndLoc) {
16367 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016368 Stmt *HelperValStmt = nullptr;
16369 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016370
16371 // OpenMP [2.9.2, taskloop Constrcut]
16372 // The parameter of the num_tasks clause must be a positive integer
16373 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016374 if (!isNonNegativeIntegerValue(
16375 ValExpr, *this, OMPC_num_tasks,
16376 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16377 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016378 return nullptr;
16379
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016380 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16381 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016382}
16383
Alexey Bataev28c75412015-12-15 08:19:24 +000016384OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16385 SourceLocation LParenLoc,
16386 SourceLocation EndLoc) {
16387 // OpenMP [2.13.2, critical construct, Description]
16388 // ... where hint-expression is an integer constant expression that evaluates
16389 // to a valid lock hint.
16390 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16391 if (HintExpr.isInvalid())
16392 return nullptr;
16393 return new (Context)
16394 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16395}
16396
Carlo Bertollib4adf552016-01-15 18:50:31 +000016397OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16398 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16399 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16400 SourceLocation EndLoc) {
16401 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16402 std::string Values;
16403 Values += "'";
16404 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16405 Values += "'";
16406 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16407 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16408 return nullptr;
16409 }
16410 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016411 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016412 if (ChunkSize) {
16413 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16414 !ChunkSize->isInstantiationDependent() &&
16415 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016416 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016417 ExprResult Val =
16418 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16419 if (Val.isInvalid())
16420 return nullptr;
16421
16422 ValExpr = Val.get();
16423
16424 // OpenMP [2.7.1, Restrictions]
16425 // chunk_size must be a loop invariant integer expression with a positive
16426 // value.
16427 llvm::APSInt Result;
16428 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16429 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16430 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16431 << "dist_schedule" << ChunkSize->getSourceRange();
16432 return nullptr;
16433 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016434 } else if (getOpenMPCaptureRegionForClause(
16435 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
16436 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016437 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016438 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016439 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016440 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16441 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016442 }
16443 }
16444 }
16445
16446 return new (Context)
16447 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016448 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016449}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016450
16451OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16452 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16453 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16454 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016455 if (getLangOpts().OpenMP < 50) {
16456 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16457 Kind != OMPC_DEFAULTMAP_scalar) {
16458 std::string Value;
16459 SourceLocation Loc;
16460 Value += "'";
16461 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16462 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16463 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16464 Loc = MLoc;
16465 } else {
16466 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16467 OMPC_DEFAULTMAP_scalar);
16468 Loc = KindLoc;
16469 }
16470 Value += "'";
16471 Diag(Loc, diag::err_omp_unexpected_clause_value)
16472 << Value << getOpenMPClauseName(OMPC_defaultmap);
16473 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016474 }
cchene06f3e02019-11-15 13:02:06 -050016475 } else {
16476 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16477 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16478 if (!isDefaultmapKind || !isDefaultmapModifier) {
16479 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16480 "'firstprivate', 'none', 'default'";
16481 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16482 if (!isDefaultmapKind && isDefaultmapModifier) {
16483 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16484 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16485 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16486 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16487 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16488 } else {
16489 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16490 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16491 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16492 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16493 }
16494 return nullptr;
16495 }
16496
16497 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
16498 // At most one defaultmap clause for each category can appear on the
16499 // directive.
16500 if (DSAStack->checkDefaultmapCategory(Kind)) {
16501 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
16502 return nullptr;
16503 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016504 }
cchene06f3e02019-11-15 13:02:06 -050016505 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016506
16507 return new (Context)
16508 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16509}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016510
16511bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16512 DeclContext *CurLexicalContext = getCurLexicalContext();
16513 if (!CurLexicalContext->isFileContext() &&
16514 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016515 !CurLexicalContext->isExternCXXContext() &&
16516 !isa<CXXRecordDecl>(CurLexicalContext) &&
16517 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16518 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16519 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016520 Diag(Loc, diag::err_omp_region_not_file_context);
16521 return false;
16522 }
Kelvin Libc38e632018-09-10 02:07:09 +000016523 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016524 return true;
16525}
16526
16527void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016528 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016529 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016530 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016531}
16532
Alexey Bataev729e2422019-08-23 16:11:14 +000016533NamedDecl *
16534Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16535 const DeclarationNameInfo &Id,
16536 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016537 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16538 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16539
16540 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016541 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016542 Lookup.suppressDiagnostics();
16543
16544 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016545 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016546 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016547 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016548 CTK_ErrorRecovery)) {
16549 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16550 << Id.getName());
16551 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016552 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016553 }
16554
16555 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016556 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016557 }
16558
16559 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016560 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16561 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016562 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016563 return nullptr;
16564 }
16565 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16566 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16567 return ND;
16568}
16569
16570void Sema::ActOnOpenMPDeclareTargetName(
16571 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16572 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16573 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16574 isa<FunctionTemplateDecl>(ND)) &&
16575 "Expected variable, function or function template.");
16576
16577 // Diagnose marking after use as it may lead to incorrect diagnosis and
16578 // codegen.
16579 if (LangOpts.OpenMP >= 50 &&
16580 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16581 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16582
16583 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16584 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16585 if (DevTy.hasValue() && *DevTy != DT) {
16586 Diag(Loc, diag::err_omp_device_type_mismatch)
16587 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16588 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16589 return;
16590 }
16591 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16592 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16593 if (!Res) {
16594 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16595 SourceRange(Loc, Loc));
16596 ND->addAttr(A);
16597 if (ASTMutationListener *ML = Context.getASTMutationListener())
16598 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16599 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16600 } else if (*Res != MT) {
16601 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016602 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016603}
16604
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016605static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16606 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016607 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016608 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016609 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016610 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16611 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16612 if (SemaRef.LangOpts.OpenMP >= 50 &&
16613 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16614 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16615 VD->hasGlobalStorage()) {
16616 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16617 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16618 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16619 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16620 // If a lambda declaration and definition appears between a
16621 // declare target directive and the matching end declare target
16622 // directive, all variables that are captured by the lambda
16623 // expression must also appear in a to clause.
16624 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016625 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016626 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16627 << VD << 0 << SR;
16628 return;
16629 }
16630 }
16631 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016632 return;
16633 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16634 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016635}
16636
16637static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16638 Sema &SemaRef, DSAStackTy *Stack,
16639 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016640 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016641 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16642 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016643}
16644
Kelvin Li1ce87c72017-12-12 20:08:12 +000016645void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16646 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016647 if (!D || D->isInvalidDecl())
16648 return;
16649 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016650 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016651 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016652 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016653 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16654 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016655 return;
16656 // 2.10.6: threadprivate variable cannot appear in a declare target
16657 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016658 if (DSAStack->isThreadPrivate(VD)) {
16659 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016660 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016661 return;
16662 }
16663 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016664 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16665 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016666 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016667 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16668 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016669 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016670 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16671 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16672 return;
16673 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016674 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016675 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16676 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16677 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16678 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016679 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016680 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16681 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16682 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016683 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016684 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16685 // Problem if any with var declared with incomplete type will be reported
16686 // as normal, so no need to check it here.
16687 if ((E || !VD->getType()->isIncompleteType()) &&
16688 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16689 return;
16690 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16691 // Checking declaration inside declare target region.
16692 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16693 isa<FunctionTemplateDecl>(D)) {
16694 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016695 Context, OMPDeclareTargetDeclAttr::MT_To,
16696 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000016697 D->addAttr(A);
16698 if (ASTMutationListener *ML = Context.getASTMutationListener())
16699 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16700 }
16701 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016702 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016703 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016704 if (!E)
16705 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016706 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16707}
Samuel Antao661c0902016-05-26 17:39:58 +000016708
16709OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000016710 CXXScopeSpec &MapperIdScopeSpec,
16711 DeclarationNameInfo &MapperId,
16712 const OMPVarListLocTy &Locs,
16713 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000016714 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016715 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
16716 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000016717 if (MVLI.ProcessedVarList.empty())
16718 return nullptr;
16719
Michael Kruse01f670d2019-02-22 22:29:42 +000016720 return OMPToClause::Create(
16721 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16722 MVLI.VarComponents, MVLI.UDMapperList,
16723 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000016724}
Samuel Antaoec172c62016-05-26 17:49:04 +000016725
16726OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000016727 CXXScopeSpec &MapperIdScopeSpec,
16728 DeclarationNameInfo &MapperId,
16729 const OMPVarListLocTy &Locs,
16730 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016731 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016732 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
16733 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000016734 if (MVLI.ProcessedVarList.empty())
16735 return nullptr;
16736
Michael Kruse0336c752019-02-25 20:34:15 +000016737 return OMPFromClause::Create(
16738 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16739 MVLI.VarComponents, MVLI.UDMapperList,
16740 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016741}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016742
16743OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016744 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016745 MappableVarListInfo MVLI(VarList);
16746 SmallVector<Expr *, 8> PrivateCopies;
16747 SmallVector<Expr *, 8> Inits;
16748
Alexey Bataeve3727102018-04-18 15:57:46 +000016749 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016750 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
16751 SourceLocation ELoc;
16752 SourceRange ERange;
16753 Expr *SimpleRefExpr = RefExpr;
16754 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16755 if (Res.second) {
16756 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000016757 MVLI.ProcessedVarList.push_back(RefExpr);
16758 PrivateCopies.push_back(nullptr);
16759 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016760 }
16761 ValueDecl *D = Res.first;
16762 if (!D)
16763 continue;
16764
16765 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000016766 Type = Type.getNonReferenceType().getUnqualifiedType();
16767
16768 auto *VD = dyn_cast<VarDecl>(D);
16769
16770 // Item should be a pointer or reference to pointer.
16771 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016772 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16773 << 0 << RefExpr->getSourceRange();
16774 continue;
16775 }
Samuel Antaocc10b852016-07-28 14:23:26 +000016776
16777 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000016778 auto VDPrivate =
16779 buildVarDecl(*this, ELoc, Type, D->getName(),
16780 D->hasAttrs() ? &D->getAttrs() : nullptr,
16781 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000016782 if (VDPrivate->isInvalidDecl())
16783 continue;
16784
16785 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000016786 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000016787 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16788
16789 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000016790 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000016791 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000016792 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
16793 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000016794 AddInitializerToDecl(VDPrivate,
16795 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000016796 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000016797
16798 // If required, build a capture to implement the privatization initialized
16799 // with the current list item value.
16800 DeclRefExpr *Ref = nullptr;
16801 if (!VD)
16802 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16803 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16804 PrivateCopies.push_back(VDPrivateRefExpr);
16805 Inits.push_back(VDInitRefExpr);
16806
16807 // We need to add a data sharing attribute for this variable to make sure it
16808 // is correctly captured. A variable that shows up in a use_device_ptr has
16809 // similar properties of a first private variable.
16810 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16811
16812 // Create a mappable component for the list item. List items in this clause
16813 // only need a component.
16814 MVLI.VarBaseDeclarations.push_back(D);
16815 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16816 MVLI.VarComponents.back().push_back(
16817 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000016818 }
16819
Samuel Antaocc10b852016-07-28 14:23:26 +000016820 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000016821 return nullptr;
16822
Samuel Antaocc10b852016-07-28 14:23:26 +000016823 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000016824 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16825 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016826}
Carlo Bertolli70594e92016-07-13 17:16:49 +000016827
16828OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016829 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000016830 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000016831 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000016832 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000016833 SourceLocation ELoc;
16834 SourceRange ERange;
16835 Expr *SimpleRefExpr = RefExpr;
16836 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16837 if (Res.second) {
16838 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000016839 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016840 }
16841 ValueDecl *D = Res.first;
16842 if (!D)
16843 continue;
16844
16845 QualType Type = D->getType();
16846 // item should be a pointer or array or reference to pointer or array
16847 if (!Type.getNonReferenceType()->isPointerType() &&
16848 !Type.getNonReferenceType()->isArrayType()) {
16849 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
16850 << 0 << RefExpr->getSourceRange();
16851 continue;
16852 }
Samuel Antao6890b092016-07-28 14:25:09 +000016853
16854 // Check if the declaration in the clause does not show up in any data
16855 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000016856 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000016857 if (isOpenMPPrivate(DVar.CKind)) {
16858 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16859 << getOpenMPClauseName(DVar.CKind)
16860 << getOpenMPClauseName(OMPC_is_device_ptr)
16861 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016862 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000016863 continue;
16864 }
16865
Alexey Bataeve3727102018-04-18 15:57:46 +000016866 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000016867 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000016868 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000016869 [&ConflictExpr](
16870 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
16871 OpenMPClauseKind) -> bool {
16872 ConflictExpr = R.front().getAssociatedExpression();
16873 return true;
16874 })) {
16875 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
16876 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
16877 << ConflictExpr->getSourceRange();
16878 continue;
16879 }
16880
16881 // Store the components in the stack so that they can be used to check
16882 // against other clauses later on.
16883 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
16884 DSAStack->addMappableExpressionComponents(
16885 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
16886
16887 // Record the expression we've just processed.
16888 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
16889
16890 // Create a mappable component for the list item. List items in this clause
16891 // only need a component. We use a null declaration to signal fields in
16892 // 'this'.
16893 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
16894 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
16895 "Unexpected device pointer expression!");
16896 MVLI.VarBaseDeclarations.push_back(
16897 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
16898 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16899 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016900 }
16901
Samuel Antao6890b092016-07-28 14:25:09 +000016902 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000016903 return nullptr;
16904
Michael Kruse4304e9d2019-02-19 16:38:20 +000016905 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
16906 MVLI.VarBaseDeclarations,
16907 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016908}
Alexey Bataeve04483e2019-03-27 14:14:31 +000016909
16910OMPClause *Sema::ActOnOpenMPAllocateClause(
16911 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16912 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16913 if (Allocator) {
16914 // OpenMP [2.11.4 allocate Clause, Description]
16915 // allocator is an expression of omp_allocator_handle_t type.
16916 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
16917 return nullptr;
16918
16919 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
16920 if (AllocatorRes.isInvalid())
16921 return nullptr;
16922 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
16923 DSAStack->getOMPAllocatorHandleT(),
16924 Sema::AA_Initializing,
16925 /*AllowExplicit=*/true);
16926 if (AllocatorRes.isInvalid())
16927 return nullptr;
16928 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000016929 } else {
16930 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
16931 // allocate clauses that appear on a target construct or on constructs in a
16932 // target region must specify an allocator expression unless a requires
16933 // directive with the dynamic_allocators clause is present in the same
16934 // compilation unit.
16935 if (LangOpts.OpenMPIsDevice &&
16936 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
16937 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000016938 }
16939 // Analyze and build list of variables.
16940 SmallVector<Expr *, 8> Vars;
16941 for (Expr *RefExpr : VarList) {
16942 assert(RefExpr && "NULL expr in OpenMP private clause.");
16943 SourceLocation ELoc;
16944 SourceRange ERange;
16945 Expr *SimpleRefExpr = RefExpr;
16946 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16947 if (Res.second) {
16948 // It will be analyzed later.
16949 Vars.push_back(RefExpr);
16950 }
16951 ValueDecl *D = Res.first;
16952 if (!D)
16953 continue;
16954
16955 auto *VD = dyn_cast<VarDecl>(D);
16956 DeclRefExpr *Ref = nullptr;
16957 if (!VD && !CurContext->isDependentContext())
16958 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16959 Vars.push_back((VD || CurContext->isDependentContext())
16960 ? RefExpr->IgnoreParens()
16961 : Ref);
16962 }
16963
16964 if (Vars.empty())
16965 return nullptr;
16966
16967 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
16968 ColonLoc, EndLoc, Vars);
16969}