blob: decda442fed894dd2173156b2ca45c0302705005 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev0ee89c12019-12-12 14:13:02 -050026#include "clang/Basic/PartialDiagnostic.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000027#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000028#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Scope.h"
30#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000031#include "clang/Sema/SemaInternal.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060032#include "llvm/ADT/IndexedMap.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000033#include "llvm/ADT/PointerEmbeddedInt.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060034#include "llvm/Frontend/OpenMP/OMPConstants.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000035using namespace clang;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060036using namespace llvm::omp;
Alexey Bataeva769e072013-03-22 06:34:35 +000037
Alexey Bataev758e55e2013-09-06 18:03:48 +000038//===----------------------------------------------------------------------===//
39// Stack of data-sharing attributes for variables
40//===----------------------------------------------------------------------===//
41
Alexey Bataeve3727102018-04-18 15:57:46 +000042static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000043 Sema &SemaRef, Expr *E,
44 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000045 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000046
Alexey Bataev758e55e2013-09-06 18:03:48 +000047namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000049enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050 DSA_unspecified = 0, /// Data sharing attribute not specified.
51 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
52 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000053};
54
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000055/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000056/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000057class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000058public:
Alexey Bataeve3727102018-04-18 15:57:46 +000059 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000060 OpenMPDirectiveKind DKind = OMPD_unknown;
61 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000062 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000063 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000064 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000065 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000066 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
67 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
68 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000069 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
70 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000071 };
Alexey Bataeve3727102018-04-18 15:57:46 +000072 using OperatorOffsetTy =
73 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000074 using DoacrossDependMapTy =
75 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000076
Alexey Bataev758e55e2013-09-06 18:03:48 +000077private:
Alexey Bataeve3727102018-04-18 15:57:46 +000078 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000079 OpenMPClauseKind Attributes = OMPC_unknown;
80 /// Pointer to a reference expression and a flag which shows that the
81 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000082 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000083 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000084 };
Alexey Bataeve3727102018-04-18 15:57:46 +000085 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
Alexey Bataevb6e70842019-12-16 15:54:17 -050086 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
Alexey Bataeve3727102018-04-18 15:57:46 +000087 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
88 using LoopControlVariablesMapTy =
89 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000090 /// Struct that associates a component with the clause kind where they are
91 /// found.
92 struct MappedExprComponentTy {
93 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
94 OpenMPClauseKind Kind = OMPC_unknown;
95 };
Alexey Bataeve3727102018-04-18 15:57:46 +000096 using MappedExprComponentsTy =
97 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
98 using CriticalsWithHintsTy =
99 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000100 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000101 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 ReductionData() = default;
105 void set(BinaryOperatorKind BO, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = BO;
108 }
109 void set(const Expr *RefExpr, SourceRange RR) {
110 ReductionRange = RR;
111 ReductionOp = RefExpr;
112 }
113 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000114 using DeclReductionMapTy =
115 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
cchene06f3e02019-11-15 13:02:06 -0500116 struct DefaultmapInfo {
117 OpenMPDefaultmapClauseModifier ImplicitBehavior =
118 OMPC_DEFAULTMAP_MODIFIER_unknown;
119 SourceLocation SLoc;
120 DefaultmapInfo() = default;
121 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
122 : ImplicitBehavior(M), SLoc(Loc) {}
123 };
Alexey Bataev758e55e2013-09-06 18:03:48 +0000124
Alexey Bataeve3727102018-04-18 15:57:46 +0000125 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000126 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000127 DeclReductionMapTy ReductionMap;
Alexey Bataevb6e70842019-12-16 15:54:17 -0500128 UsedRefMapTy AlignedMap;
129 UsedRefMapTy NontemporalMap;
Samuel Antao90927002016-04-26 14:54:23 +0000130 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000131 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000132 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000133 SourceLocation DefaultAttrLoc;
cchene06f3e02019-11-15 13:02:06 -0500134 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000135 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000138 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000139 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
140 /// get the data (loop counters etc.) about enclosing loop-based construct.
141 /// This data is required during codegen.
142 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000143 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000144 /// 'ordered' clause, the second one is true if the regions has 'ordered'
145 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000146 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000147 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000148 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000149 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000150 bool NowaitRegion = false;
151 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000152 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000153 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000154 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000155 /// Reference to the taskgroup task_reduction reference expression.
156 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000157 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000158 /// List of globals marked as declare target link in this target region
159 /// (isOpenMPTargetExecutionDirective(Directive) == true).
160 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000161 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000162 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000163 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
164 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000165 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000166 };
167
Alexey Bataeve3727102018-04-18 15:57:46 +0000168 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000169
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000170 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000171 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000172 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
173 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000174 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000175 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000176 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000177 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000178 bool ForceCapturing = false;
Alexey Bataevd1caf932019-09-30 14:05:26 +0000179 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000180 /// captured by reference.
181 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000182 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000183 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000184
Richard Smith375dec52019-05-30 23:21:14 +0000185 /// Iterators over the stack iterate in order from innermost to outermost
186 /// directive.
187 using const_iterator = StackTy::const_reverse_iterator;
188 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000189 return Stack.empty() ? const_iterator()
190 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000191 }
192 const_iterator end() const {
193 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
194 }
195 using iterator = StackTy::reverse_iterator;
196 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000197 return Stack.empty() ? iterator()
198 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000199 }
200 iterator end() {
201 return Stack.empty() ? iterator() : Stack.back().first.rend();
202 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000203
Richard Smith375dec52019-05-30 23:21:14 +0000204 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000205
Alexey Bataev4b465392017-04-26 15:06:24 +0000206 bool isStackEmpty() const {
207 return Stack.empty() ||
208 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000209 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000210 }
Richard Smith375dec52019-05-30 23:21:14 +0000211 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000212 return isStackEmpty() ? 0
213 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000214 }
215
216 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000217 size_t Size = getStackSize();
218 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000219 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000220 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000221 }
222 const SharingMapTy *getTopOfStackOrNull() const {
223 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
224 }
225 SharingMapTy &getTopOfStack() {
226 assert(!isStackEmpty() && "no current directive");
227 return *getTopOfStackOrNull();
228 }
229 const SharingMapTy &getTopOfStack() const {
230 return const_cast<DSAStackTy&>(*this).getTopOfStack();
231 }
232
233 SharingMapTy *getSecondOnStackOrNull() {
234 size_t Size = getStackSize();
235 if (Size <= 1)
236 return nullptr;
237 return &Stack.back().first[Size - 2];
238 }
239 const SharingMapTy *getSecondOnStackOrNull() const {
240 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
241 }
242
243 /// Get the stack element at a certain level (previously returned by
244 /// \c getNestingLevel).
245 ///
246 /// Note that nesting levels count from outermost to innermost, and this is
247 /// the reverse of our iteration order where new inner levels are pushed at
248 /// the front of the stack.
249 SharingMapTy &getStackElemAtLevel(unsigned Level) {
250 assert(Level < getStackSize() && "no such stack element");
251 return Stack.back().first[Level];
252 }
253 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
254 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
255 }
256
257 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
258
259 /// Checks if the variable is a local for OpenMP region.
260 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000261
Kelvin Li1408f912018-09-26 04:28:39 +0000262 /// Vector of previously declared requires directives
263 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000264 /// omp_allocator_handle_t type.
265 QualType OMPAllocatorHandleT;
266 /// Expression for the predefined allocators.
267 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
268 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000269 /// Vector of previously encountered target directives
270 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000271
Alexey Bataev758e55e2013-09-06 18:03:48 +0000272public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000273 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000274
Alexey Bataev27ef9512019-03-20 20:14:22 +0000275 /// Sets omp_allocator_handle_t type.
276 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
277 /// Gets omp_allocator_handle_t type.
278 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
279 /// Sets the given default allocator.
280 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
281 Expr *Allocator) {
282 OMPPredefinedAllocators[AllocatorKind] = Allocator;
283 }
284 /// Returns the specified default allocator.
285 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
286 return OMPPredefinedAllocators[AllocatorKind];
287 }
288
Alexey Bataevaac108a2015-06-23 04:51:00 +0000289 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000290 OpenMPClauseKind getClauseParsingMode() const {
291 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
292 return ClauseKindMode;
293 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000294 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000295
Richard Smith0621a8f2019-05-31 00:45:10 +0000296 bool isBodyComplete() const {
297 const SharingMapTy *Top = getTopOfStackOrNull();
298 return Top && Top->BodyComplete;
299 }
300 void setBodyComplete() {
301 getTopOfStack().BodyComplete = true;
302 }
303
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000304 bool isForceVarCapturing() const { return ForceCapturing; }
305 void setForceVarCapturing(bool V) { ForceCapturing = V; }
306
Alexey Bataev60705422018-10-30 15:50:12 +0000307 void setForceCaptureByReferenceInTargetExecutable(bool V) {
308 ForceCaptureByReferenceInTargetExecutable = V;
309 }
310 bool isForceCaptureByReferenceInTargetExecutable() const {
311 return ForceCaptureByReferenceInTargetExecutable;
312 }
313
Alexey Bataev758e55e2013-09-06 18:03:48 +0000314 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000315 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000316 assert(!IgnoredStackElements &&
317 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000318 if (Stack.empty() ||
319 Stack.back().second != CurrentNonCapturingFunctionScope)
320 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
321 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
322 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000323 }
324
325 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000326 assert(!IgnoredStackElements &&
327 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000328 assert(!Stack.back().first.empty() &&
329 "Data-sharing attributes stack is empty!");
330 Stack.back().first.pop_back();
331 }
332
Richard Smith0621a8f2019-05-31 00:45:10 +0000333 /// RAII object to temporarily leave the scope of a directive when we want to
334 /// logically operate in its parent.
335 class ParentDirectiveScope {
336 DSAStackTy &Self;
337 bool Active;
338 public:
339 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
340 : Self(Self), Active(false) {
341 if (Activate)
342 enable();
343 }
344 ~ParentDirectiveScope() { disable(); }
345 void disable() {
346 if (Active) {
347 --Self.IgnoredStackElements;
348 Active = false;
349 }
350 }
351 void enable() {
352 if (!Active) {
353 ++Self.IgnoredStackElements;
354 Active = true;
355 }
356 }
357 };
358
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000359 /// Marks that we're started loop parsing.
360 void loopInit() {
361 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
362 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000363 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000364 }
365 /// Start capturing of the variables in the loop context.
366 void loopStart() {
367 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
368 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000369 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000370 }
371 /// true, if variables are captured, false otherwise.
372 bool isLoopStarted() const {
373 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
374 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000375 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000376 }
377 /// Marks (or clears) declaration as possibly loop counter.
378 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000379 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000380 D ? D->getCanonicalDecl() : D;
381 }
382 /// Gets the possible loop counter decl.
383 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000384 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000385 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000386 /// Start new OpenMP region stack in new non-capturing function.
387 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000388 assert(!IgnoredStackElements &&
389 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000390 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
391 assert(!isa<CapturingScopeInfo>(CurFnScope));
392 CurrentNonCapturingFunctionScope = CurFnScope;
393 }
394 /// Pop region stack for non-capturing function.
395 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000396 assert(!IgnoredStackElements &&
397 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000398 if (!Stack.empty() && Stack.back().second == OldFSI) {
399 assert(Stack.back().first.empty());
400 Stack.pop_back();
401 }
402 CurrentNonCapturingFunctionScope = nullptr;
403 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
404 if (!isa<CapturingScopeInfo>(FSI)) {
405 CurrentNonCapturingFunctionScope = FSI;
406 break;
407 }
408 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000409 }
410
Alexey Bataeve3727102018-04-18 15:57:46 +0000411 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000412 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000413 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000414 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000415 getCriticalWithHint(const DeclarationNameInfo &Name) const {
416 auto I = Criticals.find(Name.getAsString());
417 if (I != Criticals.end())
418 return I->second;
419 return std::make_pair(nullptr, llvm::APSInt());
420 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000421 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000422 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000423 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000424 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexey Bataevb6e70842019-12-16 15:54:17 -0500425 /// If 'nontemporal' declaration for given variable \a D was not seen yet,
426 /// add it and return NULL; otherwise return previous occurrence's expression
427 /// for diagnostics.
428 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000430 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000431 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000433 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000434 /// \return The index of the loop control variable in the list of associated
435 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000436 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000438 /// parent region.
439 /// \return The index of the loop control variable in the list of associated
440 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000441 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000442 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000443 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000444 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000445
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000446 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000447 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000448 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000449
Alexey Bataevfa312f32017-07-21 18:48:21 +0000450 /// Adds additional information for the reduction items with the reduction id
451 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000452 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000453 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000454 /// Adds additional information for the reduction items with the reduction id
455 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000456 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000457 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000458 /// Returns the location and reduction operation from the innermost parent
459 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000460 const DSAVarData
461 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
462 BinaryOperatorKind &BOK,
463 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000464 /// Returns the location and reduction operation from the innermost parent
465 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000466 const DSAVarData
467 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
468 const Expr *&ReductionRef,
469 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000470 /// Return reduction reference expression for the current taskgroup.
471 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000472 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000473 "taskgroup reference expression requested for non taskgroup "
474 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000475 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000476 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000477 /// Checks if the given \p VD declaration is actually a taskgroup reduction
478 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000479 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000480 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
481 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000482 ->getDecl() == VD;
483 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000484
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000485 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000486 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000487 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000488 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000489 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000490 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000491 /// match specified \a CPred predicate in any directive which matches \a DPred
492 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000493 const DSAVarData
494 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
495 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
496 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000497 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000498 /// match specified \a CPred predicate in any innermost directive which
499 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000500 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000501 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000502 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
503 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000504 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000505 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000506 /// attributes which match specified \a CPred predicate at the specified
507 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000508 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000509 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000510 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000511
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000512 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000513 /// specified \a DPred predicate.
514 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000515 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000516 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000517
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000518 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000519 bool hasDirective(
520 const llvm::function_ref<bool(
521 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
522 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000523 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000524
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000526 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000527 const SharingMapTy *Top = getTopOfStackOrNull();
528 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000529 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000530 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000531 OpenMPDirectiveKind getDirective(unsigned Level) const {
532 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000533 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000534 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000535 /// Returns the capture region at the specified level.
536 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
537 unsigned OpenMPCaptureLevel) const {
538 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
539 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
540 return CaptureRegions[OpenMPCaptureLevel];
541 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000543 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000544 const SharingMapTy *Parent = getSecondOnStackOrNull();
545 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000546 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000547
Kelvin Li1408f912018-09-26 04:28:39 +0000548 /// Add requires decl to internal vector
549 void addRequiresDecl(OMPRequiresDecl *RD) {
550 RequiresDecls.push_back(RD);
551 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000552
Alexey Bataev318f431b2019-03-22 15:25:12 +0000553 /// Checks if the defined 'requires' directive has specified type of clause.
554 template <typename ClauseType>
555 bool hasRequiresDeclWithClause() {
556 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
557 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
558 return isa<ClauseType>(C);
559 });
560 });
561 }
562
Kelvin Li1408f912018-09-26 04:28:39 +0000563 /// Checks for a duplicate clause amongst previously declared requires
564 /// directives
565 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
566 bool IsDuplicate = false;
567 for (OMPClause *CNew : ClauseList) {
568 for (const OMPRequiresDecl *D : RequiresDecls) {
569 for (const OMPClause *CPrev : D->clauselists()) {
570 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
571 SemaRef.Diag(CNew->getBeginLoc(),
572 diag::err_omp_requires_clause_redeclaration)
573 << getOpenMPClauseName(CNew->getClauseKind());
574 SemaRef.Diag(CPrev->getBeginLoc(),
575 diag::note_omp_requires_previous_clause)
576 << getOpenMPClauseName(CPrev->getClauseKind());
577 IsDuplicate = true;
578 }
579 }
580 }
581 }
582 return IsDuplicate;
583 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000584
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000585 /// Add location of previously encountered target to internal vector
586 void addTargetDirLocation(SourceLocation LocStart) {
587 TargetLocations.push_back(LocStart);
588 }
589
590 // Return previously encountered target region locations.
591 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
592 return TargetLocations;
593 }
594
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000595 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000596 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000597 getTopOfStack().DefaultAttr = DSA_none;
598 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000599 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000600 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000601 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000602 getTopOfStack().DefaultAttr = DSA_shared;
603 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000604 }
cchene06f3e02019-11-15 13:02:06 -0500605 /// Set default data mapping attribute to Modifier:Kind
606 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
607 OpenMPDefaultmapClauseKind Kind,
608 SourceLocation Loc) {
609 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
610 DMI.ImplicitBehavior = M;
611 DMI.SLoc = Loc;
612 }
613 /// Check whether the implicit-behavior has been set in defaultmap
614 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
615 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
616 OMPC_DEFAULTMAP_MODIFIER_unknown;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000617 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000618
619 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000620 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000621 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000622 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000623 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000624 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000625 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000626 }
cchene06f3e02019-11-15 13:02:06 -0500627 OpenMPDefaultmapClauseModifier
628 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
629 return isStackEmpty()
630 ? OMPC_DEFAULTMAP_MODIFIER_unknown
631 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000632 }
cchene06f3e02019-11-15 13:02:06 -0500633 OpenMPDefaultmapClauseModifier
634 getDefaultmapModifierAtLevel(unsigned Level,
635 OpenMPDefaultmapClauseKind Kind) const {
636 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000637 }
cchene06f3e02019-11-15 13:02:06 -0500638 bool isDefaultmapCapturedByRef(unsigned Level,
639 OpenMPDefaultmapClauseKind Kind) const {
640 OpenMPDefaultmapClauseModifier M =
641 getDefaultmapModifierAtLevel(Level, Kind);
642 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
643 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
644 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
645 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
646 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
647 }
648 return true;
649 }
650 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
651 OpenMPDefaultmapClauseKind Kind) {
652 switch (Kind) {
653 case OMPC_DEFAULTMAP_scalar:
654 case OMPC_DEFAULTMAP_pointer:
655 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
656 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
657 (M == OMPC_DEFAULTMAP_MODIFIER_default);
658 case OMPC_DEFAULTMAP_aggregate:
659 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000660 default:
661 break;
cchene06f3e02019-11-15 13:02:06 -0500662 }
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000663 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
cchene06f3e02019-11-15 13:02:06 -0500664 }
665 bool mustBeFirstprivateAtLevel(unsigned Level,
666 OpenMPDefaultmapClauseKind Kind) const {
667 OpenMPDefaultmapClauseModifier M =
668 getDefaultmapModifierAtLevel(Level, Kind);
669 return mustBeFirstprivateBase(M, Kind);
670 }
671 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
672 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
673 return mustBeFirstprivateBase(M, Kind);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000674 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000675
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000676 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000677 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000678 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000679 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000680 }
681
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000682 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000683 void setOrderedRegion(bool IsOrdered, const Expr *Param,
684 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000685 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000686 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000687 else
Richard Smith375dec52019-05-30 23:21:14 +0000688 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000689 }
690 /// Returns true, if region is ordered (has associated 'ordered' clause),
691 /// false - otherwise.
692 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000693 if (const SharingMapTy *Top = getTopOfStackOrNull())
694 return Top->OrderedRegion.hasValue();
695 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000696 }
697 /// Returns optional parameter for the ordered region.
698 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000699 if (const SharingMapTy *Top = getTopOfStackOrNull())
700 if (Top->OrderedRegion.hasValue())
701 return Top->OrderedRegion.getValue();
702 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000703 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000704 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000705 /// 'ordered' clause), false - otherwise.
706 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000707 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
708 return Parent->OrderedRegion.hasValue();
709 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000710 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000711 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000712 std::pair<const Expr *, OMPOrderedClause *>
713 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000714 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
715 if (Parent->OrderedRegion.hasValue())
716 return Parent->OrderedRegion.getValue();
717 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000718 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000719 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000720 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000721 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000722 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000723 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000724 /// 'nowait' clause), false - otherwise.
725 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000726 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
727 return Parent->NowaitRegion;
728 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000729 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000730 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000731 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000732 if (SharingMapTy *Parent = getSecondOnStackOrNull())
733 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000734 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000735 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000736 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000737 const SharingMapTy *Top = getTopOfStackOrNull();
738 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000739 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000740
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000741 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000742 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000743 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000744 if (Val > 1)
745 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000746 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000747 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000748 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000749 const SharingMapTy *Top = getTopOfStackOrNull();
750 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000751 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000752 /// Returns true if the construct is associated with multiple loops.
753 bool hasMutipleLoops() const {
754 const SharingMapTy *Top = getTopOfStackOrNull();
755 return Top ? Top->HasMutipleLoops : false;
756 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000757
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000758 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000759 /// region.
760 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000761 if (SharingMapTy *Parent = getSecondOnStackOrNull())
762 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000763 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000764 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000765 bool hasInnerTeamsRegion() const {
766 return getInnerTeamsRegionLoc().isValid();
767 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000768 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000769 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000770 const SharingMapTy *Top = getTopOfStackOrNull();
771 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000772 }
773
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000774 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000775 const SharingMapTy *Top = getTopOfStackOrNull();
776 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000777 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000778 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000779 const SharingMapTy *Top = getTopOfStackOrNull();
780 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000781 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000782
Samuel Antao4c8035b2016-12-12 18:00:20 +0000783 /// Do the check specified in \a Check to all component lists and return true
784 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000785 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000786 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000787 const llvm::function_ref<
788 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000789 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000790 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000791 if (isStackEmpty())
792 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000793 auto SI = begin();
794 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000795
796 if (SI == SE)
797 return false;
798
Alexey Bataeve3727102018-04-18 15:57:46 +0000799 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000800 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000801 else
802 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000803
804 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000805 auto MI = SI->MappedExprComponents.find(VD);
806 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000807 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
808 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000809 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000810 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000811 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000812 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000813 }
814
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000815 /// Do the check specified in \a Check to all component lists at a given level
816 /// and return true if any issue is found.
817 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000818 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000819 const llvm::function_ref<
820 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000821 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000822 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000823 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000824 return false;
825
Richard Smith375dec52019-05-30 23:21:14 +0000826 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
827 auto MI = StackElem.MappedExprComponents.find(VD);
828 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000829 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
830 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000831 if (Check(L, MI->second.Kind))
832 return true;
833 return false;
834 }
835
Samuel Antao4c8035b2016-12-12 18:00:20 +0000836 /// Create a new mappable expression component list associated with a given
837 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000838 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000839 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000840 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
841 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000842 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000843 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000844 MEC.Components.resize(MEC.Components.size() + 1);
845 MEC.Components.back().append(Components.begin(), Components.end());
846 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000847 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000848
849 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000850 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000851 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000852 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000853 void addDoacrossDependClause(OMPDependClause *C,
854 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000855 SharingMapTy *Parent = getSecondOnStackOrNull();
856 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
857 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000858 }
859 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
860 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000861 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000862 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000863 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000864 return llvm::make_range(Ref.begin(), Ref.end());
865 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000866 return llvm::make_range(StackElem.DoacrossDepends.end(),
867 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000868 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000869
870 // Store types of classes which have been explicitly mapped
871 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000872 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000873 StackElem.MappedClassesQualTypes.insert(QT);
874 }
875
876 // Return set of mapped classes types
877 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000878 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000879 return StackElem.MappedClassesQualTypes.count(QT) != 0;
880 }
881
Alexey Bataeva495c642019-03-11 19:51:42 +0000882 /// Adds global declare target to the parent target region.
883 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
884 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
885 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
886 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000887 for (auto &Elem : *this) {
888 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
889 Elem.DeclareTargetLinkVarDecls.push_back(E);
890 return;
891 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000892 }
893 }
894
895 /// Returns the list of globals with declare target link if current directive
896 /// is target.
897 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
898 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
899 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000900 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000901 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000902};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000903
904bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
905 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
906}
907
908bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000909 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
910 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000911}
Alexey Bataeve3727102018-04-18 15:57:46 +0000912
Alexey Bataeved09d242014-05-28 05:53:51 +0000913} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000914
Alexey Bataeve3727102018-04-18 15:57:46 +0000915static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000916 if (const auto *FE = dyn_cast<FullExpr>(E))
917 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000918
Alexey Bataeve3727102018-04-18 15:57:46 +0000919 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +0100920 E = MTE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000921
Alexey Bataeve3727102018-04-18 15:57:46 +0000922 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000923 E = Binder->getSubExpr();
924
Alexey Bataeve3727102018-04-18 15:57:46 +0000925 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000926 E = ICE->getSubExprAsWritten();
927 return E->IgnoreParens();
928}
929
Alexey Bataeve3727102018-04-18 15:57:46 +0000930static Expr *getExprAsWritten(Expr *E) {
931 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
932}
933
934static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
935 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
936 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000937 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000938 const auto *VD = dyn_cast<VarDecl>(D);
939 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000940 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000941 VD = VD->getCanonicalDecl();
942 D = VD;
943 } else {
944 assert(FD);
945 FD = FD->getCanonicalDecl();
946 D = FD;
947 }
948 return D;
949}
950
Alexey Bataeve3727102018-04-18 15:57:46 +0000951static ValueDecl *getCanonicalDecl(ValueDecl *D) {
952 return const_cast<ValueDecl *>(
953 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
954}
955
Richard Smith375dec52019-05-30 23:21:14 +0000956DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000957 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000958 D = getCanonicalDecl(D);
959 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000960 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000961 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000962 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000963 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
964 // in a region but not in construct]
965 // File-scope or namespace-scope variables referenced in called routines
966 // in the region are shared unless they appear in a threadprivate
967 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000968 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000969 DVar.CKind = OMPC_shared;
970
971 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
972 // in a region but not in construct]
973 // Variables with static storage duration that are declared in called
974 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000975 if (VD && VD->hasGlobalStorage())
976 DVar.CKind = OMPC_shared;
977
978 // Non-static data members are shared by default.
979 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000980 DVar.CKind = OMPC_shared;
981
Alexey Bataev758e55e2013-09-06 18:03:48 +0000982 return DVar;
983 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000984
Alexey Bataevec3da872014-01-31 05:15:34 +0000985 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
986 // in a Construct, C/C++, predetermined, p.1]
987 // Variables with automatic storage duration that are declared in a scope
988 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000989 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
990 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000991 DVar.CKind = OMPC_private;
992 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000993 }
994
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000995 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000996 // Explicitly specified attributes and local variables with predetermined
997 // attributes.
998 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000999 const DSAInfo &Data = Iter->SharingMap.lookup(D);
1000 DVar.RefExpr = Data.RefExpr.getPointer();
1001 DVar.PrivateCopy = Data.PrivateCopy;
1002 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001003 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001004 return DVar;
1005 }
1006
1007 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1008 // in a Construct, C/C++, implicitly determined, p.1]
1009 // In a parallel or task construct, the data-sharing attributes of these
1010 // variables are determined by the default clause, if present.
1011 switch (Iter->DefaultAttr) {
1012 case DSA_shared:
1013 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001014 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001015 return DVar;
1016 case DSA_none:
1017 return DVar;
1018 case DSA_unspecified:
1019 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1020 // in a Construct, implicitly determined, p.2]
1021 // In a parallel construct, if no default clause is present, these
1022 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +00001023 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001024 if ((isOpenMPParallelDirective(DVar.DKind) &&
1025 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001026 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001027 DVar.CKind = OMPC_shared;
1028 return DVar;
1029 }
1030
1031 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1032 // in a Construct, implicitly determined, p.4]
1033 // In a task construct, if no default clause is present, a variable that in
1034 // the enclosing context is determined to be shared by all implicit tasks
1035 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001036 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001037 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +00001038 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001039 do {
1040 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001041 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +00001042 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +00001043 // In a task construct, if no default clause is present, a variable
1044 // whose data-sharing attribute is not determined by the rules above is
1045 // firstprivate.
1046 DVarTemp = getDSA(I, D);
1047 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001048 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001049 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001050 return DVar;
1051 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001052 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +00001054 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001055 return DVar;
1056 }
1057 }
1058 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1059 // in a Construct, implicitly determined, p.3]
1060 // For constructs other than task, if no default clause is present, these
1061 // variables inherit their data-sharing attributes from the enclosing
1062 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001063 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064}
1065
Alexey Bataeve3727102018-04-18 15:57:46 +00001066const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1067 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001068 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001069 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001070 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001071 auto It = StackElem.AlignedMap.find(D);
1072 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001073 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001074 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001075 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001076 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001077 assert(It->second && "Unexpected nullptr expr in the aligned map");
1078 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001079}
1080
Alexey Bataevb6e70842019-12-16 15:54:17 -05001081const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1082 const Expr *NewDE) {
1083 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1084 D = getCanonicalDecl(D);
1085 SharingMapTy &StackElem = getTopOfStack();
1086 auto It = StackElem.NontemporalMap.find(D);
1087 if (It == StackElem.NontemporalMap.end()) {
1088 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1089 StackElem.NontemporalMap[D] = NewDE;
1090 return nullptr;
1091 }
1092 assert(It->second && "Unexpected nullptr expr in the aligned map");
1093 return It->second;
1094}
1095
Alexey Bataeve3727102018-04-18 15:57:46 +00001096void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001097 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001098 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001099 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001100 StackElem.LCVMap.try_emplace(
1101 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001102}
1103
Alexey Bataeve3727102018-04-18 15:57:46 +00001104const DSAStackTy::LCDeclInfo
1105DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001106 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001107 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001108 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001109 auto It = StackElem.LCVMap.find(D);
1110 if (It != StackElem.LCVMap.end())
1111 return It->second;
1112 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001113}
1114
Alexey Bataeve3727102018-04-18 15:57:46 +00001115const DSAStackTy::LCDeclInfo
1116DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001117 const SharingMapTy *Parent = getSecondOnStackOrNull();
1118 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001119 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001120 auto It = Parent->LCVMap.find(D);
1121 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001122 return It->second;
1123 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001124}
1125
Alexey Bataeve3727102018-04-18 15:57:46 +00001126const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001127 const SharingMapTy *Parent = getSecondOnStackOrNull();
1128 assert(Parent && "Data-sharing attributes stack is empty");
1129 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001130 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001131 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001132 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001133 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001134 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001135}
1136
Alexey Bataeve3727102018-04-18 15:57:46 +00001137void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001138 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001139 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001140 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001141 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001142 Data.Attributes = A;
1143 Data.RefExpr.setPointer(E);
1144 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001145 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001146 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001147 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1148 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1149 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1150 (isLoopControlVariable(D).first && A == OMPC_private));
1151 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1152 Data.RefExpr.setInt(/*IntVal=*/true);
1153 return;
1154 }
1155 const bool IsLastprivate =
1156 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1157 Data.Attributes = A;
1158 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1159 Data.PrivateCopy = PrivateCopy;
1160 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001161 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001162 Data.Attributes = A;
1163 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1164 Data.PrivateCopy = nullptr;
1165 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001166 }
1167}
1168
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001169/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001170static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001171 StringRef Name, const AttrVec *Attrs = nullptr,
1172 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001173 DeclContext *DC = SemaRef.CurContext;
1174 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1175 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001176 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001177 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1178 if (Attrs) {
1179 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1180 I != E; ++I)
1181 Decl->addAttr(*I);
1182 }
1183 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001184 if (OrigRef) {
1185 Decl->addAttr(
1186 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1187 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001188 return Decl;
1189}
1190
1191static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1192 SourceLocation Loc,
1193 bool RefersToCapture = false) {
1194 D->setReferenced();
1195 D->markUsed(S.Context);
1196 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1197 SourceLocation(), D, RefersToCapture, Loc, Ty,
1198 VK_LValue);
1199}
1200
Alexey Bataeve3727102018-04-18 15:57:46 +00001201void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001202 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001203 D = getCanonicalDecl(D);
1204 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001205 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001206 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001207 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001208 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001209 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001210 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001211 "Additional reduction info may be specified only once for reduction "
1212 "items.");
1213 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001214 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001215 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001216 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001217 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1218 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001219 TaskgroupReductionRef =
1220 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001221 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001222}
1223
Alexey Bataeve3727102018-04-18 15:57:46 +00001224void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001225 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001226 D = getCanonicalDecl(D);
1227 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001228 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001229 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001230 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001231 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001232 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001233 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001234 "Additional reduction info may be specified only once for reduction "
1235 "items.");
1236 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001237 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001238 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001239 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001240 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1241 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001242 TaskgroupReductionRef =
1243 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001244 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001245}
1246
Alexey Bataeve3727102018-04-18 15:57:46 +00001247const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1248 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1249 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001250 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001251 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001252 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001253 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001254 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001255 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001256 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001257 if (!ReductionData.ReductionOp ||
1258 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001259 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001260 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001261 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001262 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1263 "expression for the descriptor is not "
1264 "set.");
1265 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001266 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1267 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001268 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001269 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001270}
1271
Alexey Bataeve3727102018-04-18 15:57:46 +00001272const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1273 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1274 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001275 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001276 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001277 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001278 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001279 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001280 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001281 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001282 if (!ReductionData.ReductionOp ||
1283 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001284 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001285 SR = ReductionData.ReductionRange;
1286 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001287 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1288 "expression for the descriptor is not "
1289 "set.");
1290 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001291 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1292 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001293 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001294 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001295}
1296
Richard Smith375dec52019-05-30 23:21:14 +00001297bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001298 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001299 for (const_iterator E = end(); I != E; ++I) {
1300 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1301 isOpenMPTargetExecutionDirective(I->Directive)) {
1302 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1303 Scope *CurScope = getCurScope();
1304 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1305 CurScope = CurScope->getParent();
1306 return CurScope != TopScope;
1307 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001308 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001309 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001310}
1311
Joel E. Dennyd2649292019-01-04 22:11:56 +00001312static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1313 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001314 bool *IsClassType = nullptr) {
1315 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001316 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001317 bool IsConstant = Type.isConstant(Context);
1318 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001319 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1320 ? Type->getAsCXXRecordDecl()
1321 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001322 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1323 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1324 RD = CTD->getTemplatedDecl();
1325 if (IsClassType)
1326 *IsClassType = RD;
1327 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1328 RD->hasDefinition() && RD->hasMutableFields());
1329}
1330
Joel E. Dennyd2649292019-01-04 22:11:56 +00001331static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1332 QualType Type, OpenMPClauseKind CKind,
1333 SourceLocation ELoc,
1334 bool AcceptIfMutable = true,
1335 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001336 ASTContext &Context = SemaRef.getASTContext();
1337 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001338 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1339 unsigned Diag = ListItemNotVar
1340 ? diag::err_omp_const_list_item
1341 : IsClassType ? diag::err_omp_const_not_mutable_variable
1342 : diag::err_omp_const_variable;
1343 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1344 if (!ListItemNotVar && D) {
1345 const VarDecl *VD = dyn_cast<VarDecl>(D);
1346 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1347 VarDecl::DeclarationOnly;
1348 SemaRef.Diag(D->getLocation(),
1349 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1350 << D;
1351 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001352 return true;
1353 }
1354 return false;
1355}
1356
Alexey Bataeve3727102018-04-18 15:57:46 +00001357const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1358 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001359 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001360 DSAVarData DVar;
1361
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001362 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001363 auto TI = Threadprivates.find(D);
1364 if (TI != Threadprivates.end()) {
1365 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001366 DVar.CKind = OMPC_threadprivate;
1367 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001368 }
1369 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001370 DVar.RefExpr = buildDeclRefExpr(
1371 SemaRef, VD, D->getType().getNonReferenceType(),
1372 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1373 DVar.CKind = OMPC_threadprivate;
1374 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001375 return DVar;
1376 }
1377 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1378 // in a Construct, C/C++, predetermined, p.1]
1379 // Variables appearing in threadprivate directives are threadprivate.
1380 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1381 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1382 SemaRef.getLangOpts().OpenMPUseTLS &&
1383 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1384 (VD && VD->getStorageClass() == SC_Register &&
1385 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1386 DVar.RefExpr = buildDeclRefExpr(
1387 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1388 DVar.CKind = OMPC_threadprivate;
1389 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1390 return DVar;
1391 }
1392 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1393 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1394 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001395 const_iterator IterTarget =
1396 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1397 return isOpenMPTargetExecutionDirective(Data.Directive);
1398 });
1399 if (IterTarget != end()) {
1400 const_iterator ParentIterTarget = IterTarget + 1;
1401 for (const_iterator Iter = begin();
1402 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001403 if (isOpenMPLocal(VD, Iter)) {
1404 DVar.RefExpr =
1405 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1406 D->getLocation());
1407 DVar.CKind = OMPC_threadprivate;
1408 return DVar;
1409 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001410 }
Richard Smith375dec52019-05-30 23:21:14 +00001411 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001412 auto DSAIter = IterTarget->SharingMap.find(D);
1413 if (DSAIter != IterTarget->SharingMap.end() &&
1414 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1415 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1416 DVar.CKind = OMPC_threadprivate;
1417 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001418 }
Richard Smith375dec52019-05-30 23:21:14 +00001419 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001420 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001421 D, std::distance(ParentIterTarget, End),
1422 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001423 DVar.RefExpr =
1424 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1425 IterTarget->ConstructLoc);
1426 DVar.CKind = OMPC_threadprivate;
1427 return DVar;
1428 }
1429 }
1430 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001431 }
1432
Alexey Bataev4b465392017-04-26 15:06:24 +00001433 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001434 // Not in OpenMP execution region and top scope was already checked.
1435 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001436
Alexey Bataev758e55e2013-09-06 18:03:48 +00001437 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001438 // in a Construct, C/C++, predetermined, p.4]
1439 // Static data members are shared.
1440 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1441 // in a Construct, C/C++, predetermined, p.7]
1442 // Variables with static storage duration that are declared in a scope
1443 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001445 // Check for explicitly specified attributes.
1446 const_iterator I = begin();
1447 const_iterator EndI = end();
1448 if (FromParent && I != EndI)
1449 ++I;
1450 auto It = I->SharingMap.find(D);
1451 if (It != I->SharingMap.end()) {
1452 const DSAInfo &Data = It->getSecond();
1453 DVar.RefExpr = Data.RefExpr.getPointer();
1454 DVar.PrivateCopy = Data.PrivateCopy;
1455 DVar.CKind = Data.Attributes;
1456 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1457 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001458 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001459 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001460
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001461 DVar.CKind = OMPC_shared;
1462 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001463 }
1464
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001465 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001466 // The predetermined shared attribute for const-qualified types having no
1467 // mutable members was removed after OpenMP 3.1.
1468 if (SemaRef.LangOpts.OpenMP <= 31) {
1469 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1470 // in a Construct, C/C++, predetermined, p.6]
1471 // Variables with const qualified type having no mutable member are
1472 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001473 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001474 // Variables with const-qualified type having no mutable member may be
1475 // listed in a firstprivate clause, even if they are static data members.
1476 DSAVarData DVarTemp = hasInnermostDSA(
1477 D,
1478 [](OpenMPClauseKind C) {
1479 return C == OMPC_firstprivate || C == OMPC_shared;
1480 },
1481 MatchesAlways, FromParent);
1482 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1483 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001484
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001485 DVar.CKind = OMPC_shared;
1486 return DVar;
1487 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001488 }
1489
Alexey Bataev758e55e2013-09-06 18:03:48 +00001490 // Explicitly specified attributes and local variables with predetermined
1491 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001492 const_iterator I = begin();
1493 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001494 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001495 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001496 auto It = I->SharingMap.find(D);
1497 if (It != I->SharingMap.end()) {
1498 const DSAInfo &Data = It->getSecond();
1499 DVar.RefExpr = Data.RefExpr.getPointer();
1500 DVar.PrivateCopy = Data.PrivateCopy;
1501 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001502 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001503 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001504 }
1505
1506 return DVar;
1507}
1508
Alexey Bataeve3727102018-04-18 15:57:46 +00001509const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1510 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001511 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001512 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001513 return getDSA(I, D);
1514 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001515 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001516 const_iterator StartI = begin();
1517 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001518 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001519 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001520 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001521}
1522
Alexey Bataeve3727102018-04-18 15:57:46 +00001523const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001524DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001525 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1526 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001527 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001528 if (isStackEmpty())
1529 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001530 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001531 const_iterator I = begin();
1532 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001533 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001534 ++I;
1535 for (; I != EndI; ++I) {
1536 if (!DPred(I->Directive) &&
1537 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001538 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001539 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001540 DSAVarData DVar = getDSA(NewI, D);
1541 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001542 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001543 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001544 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001545}
1546
Alexey Bataeve3727102018-04-18 15:57:46 +00001547const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001548 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1549 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001550 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001551 if (isStackEmpty())
1552 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001553 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001554 const_iterator StartI = begin();
1555 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001556 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001557 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001558 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001559 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001560 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001561 DSAVarData DVar = getDSA(NewI, D);
1562 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001563}
1564
Alexey Bataevaac108a2015-06-23 04:51:00 +00001565bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001566 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1567 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001568 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001569 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001570 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001571 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1572 auto I = StackElem.SharingMap.find(D);
1573 if (I != StackElem.SharingMap.end() &&
1574 I->getSecond().RefExpr.getPointer() &&
1575 CPred(I->getSecond().Attributes) &&
1576 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001577 return true;
1578 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001579 auto LI = StackElem.LCVMap.find(D);
1580 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001581 return CPred(OMPC_private);
1582 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001583}
1584
Samuel Antao4be30e92015-10-02 17:14:03 +00001585bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001586 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1587 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001588 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001589 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001590 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1591 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001592}
1593
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001594bool DSAStackTy::hasDirective(
1595 const llvm::function_ref<bool(OpenMPDirectiveKind,
1596 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001597 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001598 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001599 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001600 size_t Skip = FromParent ? 2 : 1;
1601 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1602 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001603 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1604 return true;
1605 }
1606 return false;
1607}
1608
Alexey Bataev758e55e2013-09-06 18:03:48 +00001609void Sema::InitDataSharingAttributesStack() {
1610 VarDataSharingAttributesStack = new DSAStackTy(*this);
1611}
1612
1613#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1614
Alexey Bataev4b465392017-04-26 15:06:24 +00001615void Sema::pushOpenMPFunctionRegion() {
1616 DSAStack->pushFunction();
1617}
1618
1619void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1620 DSAStack->popFunction(OldFSI);
1621}
1622
Alexey Bataevc416e642019-02-08 18:02:25 +00001623static bool isOpenMPDeviceDelayedContext(Sema &S) {
1624 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1625 "Expected OpenMP device compilation.");
1626 return !S.isInOpenMPTargetExecutionDirective() &&
1627 !S.isInOpenMPDeclareTargetContext();
1628}
1629
Alexey Bataev729e2422019-08-23 16:11:14 +00001630namespace {
1631/// Status of the function emission on the host/device.
1632enum class FunctionEmissionStatus {
1633 Emitted,
1634 Discarded,
1635 Unknown,
1636};
1637} // anonymous namespace
1638
Alexey Bataevc416e642019-02-08 18:02:25 +00001639Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1640 unsigned DiagID) {
1641 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1642 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001643 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001644 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1645 switch (FES) {
1646 case FunctionEmissionStatus::Emitted:
1647 Kind = DeviceDiagBuilder::K_Immediate;
1648 break;
1649 case FunctionEmissionStatus::Unknown:
1650 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1651 : DeviceDiagBuilder::K_Immediate;
1652 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001653 case FunctionEmissionStatus::TemplateDiscarded:
1654 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001655 Kind = DeviceDiagBuilder::K_Nop;
1656 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001657 case FunctionEmissionStatus::CUDADiscarded:
1658 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1659 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001660 }
1661
1662 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1663}
1664
Alexey Bataev729e2422019-08-23 16:11:14 +00001665Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1666 unsigned DiagID) {
1667 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1668 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001669 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001670 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1671 switch (FES) {
1672 case FunctionEmissionStatus::Emitted:
1673 Kind = DeviceDiagBuilder::K_Immediate;
1674 break;
1675 case FunctionEmissionStatus::Unknown:
1676 Kind = DeviceDiagBuilder::K_Deferred;
1677 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001678 case FunctionEmissionStatus::TemplateDiscarded:
1679 case FunctionEmissionStatus::OMPDiscarded:
1680 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001681 Kind = DeviceDiagBuilder::K_Nop;
1682 break;
1683 }
1684
1685 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001686}
1687
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001688void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1689 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001690 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1691 "Expected OpenMP device compilation.");
1692 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001693 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001694 FunctionDecl *Caller = getCurFunctionDecl();
1695
Alexey Bataev729e2422019-08-23 16:11:14 +00001696 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001697 if (Caller) {
1698 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1699 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1700 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1701 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1702 "CUDADiscarded unexpected in OpenMP device function check");
1703 if ((CallerS == FunctionEmissionStatus::Emitted ||
1704 (!isOpenMPDeviceDelayedContext(*this) &&
1705 CallerS == FunctionEmissionStatus::Unknown)) &&
1706 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1707 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1708 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1709 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1710 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1711 diag::note_omp_marked_device_type_here)
1712 << HostDevTy;
1713 return;
1714 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001715 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001716 // If the caller is known-emitted, mark the callee as known-emitted.
1717 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001718 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1719 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001720 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001721 markKnownEmitted(*this, Caller, Callee, Loc,
1722 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001723 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001724 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001725 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001726 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001727 else if (Caller)
1728 DeviceCallGraph[Caller].insert({Callee, Loc});
1729}
1730
Alexey Bataev729e2422019-08-23 16:11:14 +00001731void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1732 bool CheckCaller) {
1733 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1734 "Expected OpenMP host compilation.");
1735 assert(Callee && "Callee may not be null.");
1736 Callee = Callee->getMostRecentDecl();
1737 FunctionDecl *Caller = getCurFunctionDecl();
1738
1739 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001740 if (Caller) {
1741 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1742 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1743 assert(
1744 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1745 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1746 "CUDADiscarded unexpected in OpenMP host function check");
1747 if (CallerS == FunctionEmissionStatus::Emitted &&
1748 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1749 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1750 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1751 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1752 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1753 diag::note_omp_marked_device_type_here)
1754 << NoHostDevTy;
1755 return;
1756 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001757 }
1758 // If the caller is known-emitted, mark the callee as known-emitted.
1759 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001760 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1761 if ((!CheckCaller && !Caller) ||
1762 (Caller &&
1763 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1764 markKnownEmitted(
1765 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1766 return CheckCaller &&
1767 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1768 });
1769 else if (Caller)
1770 DeviceCallGraph[Caller].insert({Callee, Loc});
1771 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001772}
1773
Alexey Bataev123ad192019-02-27 20:29:45 +00001774void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1775 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1776 "OpenMP device compilation mode is expected.");
1777 QualType Ty = E->getType();
1778 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001779 ((Ty->isFloat128Type() ||
1780 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1781 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001782 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1783 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001784 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1785 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1786 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001787}
1788
cchene06f3e02019-11-15 13:02:06 -05001789static OpenMPDefaultmapClauseKind
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001790getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1791 if (LO.OpenMP <= 45) {
1792 if (VD->getType().getNonReferenceType()->isScalarType())
1793 return OMPC_DEFAULTMAP_scalar;
1794 return OMPC_DEFAULTMAP_aggregate;
1795 }
cchene06f3e02019-11-15 13:02:06 -05001796 if (VD->getType().getNonReferenceType()->isAnyPointerType())
1797 return OMPC_DEFAULTMAP_pointer;
1798 if (VD->getType().getNonReferenceType()->isScalarType())
1799 return OMPC_DEFAULTMAP_scalar;
1800 return OMPC_DEFAULTMAP_aggregate;
1801}
1802
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001803bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1804 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001805 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1806
Alexey Bataeve3727102018-04-18 15:57:46 +00001807 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001808 bool IsByRef = true;
1809
1810 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001811 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001812 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001813
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001814 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001815 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001816 // This table summarizes how a given variable should be passed to the device
1817 // given its type and the clauses where it appears. This table is based on
1818 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1819 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1820 //
1821 // =========================================================================
1822 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1823 // | |(tofrom:scalar)| | pvt | | | |
1824 // =========================================================================
1825 // | scl | | | | - | | bycopy|
1826 // | scl | | - | x | - | - | bycopy|
1827 // | scl | | x | - | - | - | null |
1828 // | scl | x | | | - | | byref |
1829 // | scl | x | - | x | - | - | bycopy|
1830 // | scl | x | x | - | - | - | null |
1831 // | scl | | - | - | - | x | byref |
1832 // | scl | x | - | - | - | x | byref |
1833 //
1834 // | agg | n.a. | | | - | | byref |
1835 // | agg | n.a. | - | x | - | - | byref |
1836 // | agg | n.a. | x | - | - | - | null |
1837 // | agg | n.a. | - | - | - | x | byref |
1838 // | agg | n.a. | - | - | - | x[] | byref |
1839 //
1840 // | ptr | n.a. | | | - | | bycopy|
1841 // | ptr | n.a. | - | x | - | - | bycopy|
1842 // | ptr | n.a. | x | - | - | - | null |
1843 // | ptr | n.a. | - | - | - | x | byref |
1844 // | ptr | n.a. | - | - | - | x[] | bycopy|
1845 // | ptr | n.a. | - | - | x | | bycopy|
1846 // | ptr | n.a. | - | - | x | x | bycopy|
1847 // | ptr | n.a. | - | - | x | x[] | bycopy|
1848 // =========================================================================
1849 // Legend:
1850 // scl - scalar
1851 // ptr - pointer
1852 // agg - aggregate
1853 // x - applies
1854 // - - invalid in this combination
1855 // [] - mapped with an array section
1856 // byref - should be mapped by reference
1857 // byval - should be mapped by value
1858 // null - initialize a local variable to null on the device
1859 //
1860 // Observations:
1861 // - All scalar declarations that show up in a map clause have to be passed
1862 // by reference, because they may have been mapped in the enclosing data
1863 // environment.
1864 // - If the scalar value does not fit the size of uintptr, it has to be
1865 // passed by reference, regardless the result in the table above.
1866 // - For pointers mapped by value that have either an implicit map or an
1867 // array section, the runtime library may pass the NULL value to the
1868 // device instead of the value passed to it by the compiler.
1869
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001870 if (Ty->isReferenceType())
1871 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001872
1873 // Locate map clauses and see if the variable being captured is referred to
1874 // in any of those clauses. Here we only care about variables, not fields,
1875 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001876 bool IsVariableAssociatedWithSection = false;
1877
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001878 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001879 D, Level,
1880 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1881 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001882 MapExprComponents,
1883 OpenMPClauseKind WhereFoundClauseKind) {
1884 // Only the map clause information influences how a variable is
1885 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001886 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001887 if (WhereFoundClauseKind != OMPC_map)
1888 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001889
1890 auto EI = MapExprComponents.rbegin();
1891 auto EE = MapExprComponents.rend();
1892
1893 assert(EI != EE && "Invalid map expression!");
1894
1895 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1896 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1897
1898 ++EI;
1899 if (EI == EE)
1900 return false;
1901
1902 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1903 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1904 isa<MemberExpr>(EI->getAssociatedExpression())) {
1905 IsVariableAssociatedWithSection = true;
1906 // There is nothing more we need to know about this variable.
1907 return true;
1908 }
1909
1910 // Keep looking for more map info.
1911 return false;
1912 });
1913
1914 if (IsVariableUsedInMapClause) {
1915 // If variable is identified in a map clause it is always captured by
1916 // reference except if it is a pointer that is dereferenced somehow.
1917 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1918 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001919 // By default, all the data that has a scalar type is mapped by copy
1920 // (except for reduction variables).
cchene06f3e02019-11-15 13:02:06 -05001921 // Defaultmap scalar is mutual exclusive to defaultmap pointer
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001922 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001923 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1924 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001925 !Ty->isScalarType() ||
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001926 DSAStack->isDefaultmapCapturedByRef(
1927 Level, getVariableCategoryFromDecl(LangOpts, D)) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001928 DSAStack->hasExplicitDSA(
1929 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001930 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001931 }
1932
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001933 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001934 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001935 ((IsVariableUsedInMapClause &&
1936 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1937 OMPD_target) ||
1938 !DSAStack->hasExplicitDSA(
1939 D,
1940 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1941 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001942 // If the variable is artificial and must be captured by value - try to
1943 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001944 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1945 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001946 }
1947
Samuel Antao86ace552016-04-27 22:40:57 +00001948 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001949 // and alignment, because the runtime library only deals with uintptr types.
1950 // If it does not fit the uintptr size, we need to pass the data by reference
1951 // instead.
1952 if (!IsByRef &&
1953 (Ctx.getTypeSizeInChars(Ty) >
1954 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001955 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001956 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001958
1959 return IsByRef;
1960}
1961
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001962unsigned Sema::getOpenMPNestingLevel() const {
1963 assert(getLangOpts().OpenMP);
1964 return DSAStack->getNestingLevel();
1965}
1966
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001967bool Sema::isInOpenMPTargetExecutionDirective() const {
1968 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1969 !DSAStack->isClauseParsingMode()) ||
1970 DSAStack->hasDirective(
1971 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1972 SourceLocation) -> bool {
1973 return isOpenMPTargetExecutionDirective(K);
1974 },
1975 false);
1976}
1977
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001978VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1979 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001980 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001981 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001982
Alexey Bataev7c860692019-10-25 16:35:32 -04001983 auto *VD = dyn_cast<VarDecl>(D);
1984 // Do not capture constexpr variables.
1985 if (VD && VD->isConstexpr())
1986 return nullptr;
1987
Richard Smith0621a8f2019-05-31 00:45:10 +00001988 // If we want to determine whether the variable should be captured from the
1989 // perspective of the current capturing scope, and we've already left all the
1990 // capturing scopes of the top directive on the stack, check from the
1991 // perspective of its parent directive (if any) instead.
1992 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1993 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1994
Samuel Antao4be30e92015-10-02 17:14:03 +00001995 // If we are attempting to capture a global variable in a directive with
1996 // 'target' we return true so that this global is also mapped to the device.
1997 //
Richard Smith0621a8f2019-05-31 00:45:10 +00001998 if (VD && !VD->hasLocalStorage() &&
1999 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2000 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002001 // Try to mark variable as declare target if it is used in capturing
2002 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00002003 if (LangOpts.OpenMP <= 45 &&
2004 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002005 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002006 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002007 } else if (isInOpenMPTargetExecutionDirective()) {
2008 // If the declaration is enclosed in a 'declare target' directive,
2009 // then it should not be captured.
2010 //
Alexey Bataev97b72212018-08-14 18:31:20 +00002011 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002012 return nullptr;
2013 return VD;
2014 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002015 }
Samuel Antao4be30e92015-10-02 17:14:03 +00002016
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002017 if (CheckScopeInfo) {
2018 bool OpenMPFound = false;
2019 for (unsigned I = StopAt + 1; I > 0; --I) {
2020 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2021 if(!isa<CapturingScopeInfo>(FSI))
2022 return nullptr;
2023 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2024 if (RSI->CapRegionKind == CR_OpenMP) {
2025 OpenMPFound = true;
2026 break;
2027 }
2028 }
2029 if (!OpenMPFound)
2030 return nullptr;
2031 }
2032
Alexey Bataev48977c32015-08-04 08:10:48 +00002033 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2034 (!DSAStack->isClauseParsingMode() ||
2035 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002036 auto &&Info = DSAStack->isLoopControlVariable(D);
2037 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002038 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002039 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002040 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002041 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00002042 DSAStackTy::DSAVarData DVarPrivate =
2043 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002044 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002045 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00002046 // Threadprivate variables must not be captured.
2047 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
2048 return nullptr;
2049 // The variable is not private or it is the variable in the directive with
2050 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002051 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
2052 [](OpenMPDirectiveKind) { return true; },
2053 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002054 if (DVarPrivate.CKind != OMPC_unknown ||
2055 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002056 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002057 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00002058 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00002059}
2060
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002061void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2062 unsigned Level) const {
2063 SmallVector<OpenMPDirectiveKind, 4> Regions;
2064 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2065 FunctionScopesIndex -= Regions.size();
2066}
2067
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002068void Sema::startOpenMPLoop() {
2069 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2070 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2071 DSAStack->loopInit();
2072}
2073
Alexey Bataevbef93a92019-10-07 18:54:57 +00002074void Sema::startOpenMPCXXRangeFor() {
2075 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2076 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2077 DSAStack->resetPossibleLoopCounter();
2078 DSAStack->loopStart();
2079 }
2080}
2081
Alexey Bataeve3727102018-04-18 15:57:46 +00002082bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002083 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002084 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2085 if (DSAStack->getAssociatedLoops() > 0 &&
2086 !DSAStack->isLoopStarted()) {
2087 DSAStack->resetPossibleLoopCounter(D);
2088 DSAStack->loopStart();
2089 return true;
2090 }
2091 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2092 DSAStack->isLoopControlVariable(D).first) &&
2093 !DSAStack->hasExplicitDSA(
2094 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2095 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2096 return true;
2097 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002098 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2099 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2100 DSAStack->isForceVarCapturing() &&
2101 !DSAStack->hasExplicitDSA(
2102 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2103 return true;
2104 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002105 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002106 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002107 (DSAStack->isClauseParsingMode() &&
2108 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002109 // Consider taskgroup reduction descriptor variable a private to avoid
2110 // possible capture in the region.
2111 (DSAStack->hasExplicitDirective(
2112 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2113 Level) &&
2114 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002115}
2116
Alexey Bataeve3727102018-04-18 15:57:46 +00002117void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2118 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002119 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2120 D = getCanonicalDecl(D);
2121 OpenMPClauseKind OMPC = OMPC_unknown;
2122 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2123 const unsigned NewLevel = I - 1;
2124 if (DSAStack->hasExplicitDSA(D,
2125 [&OMPC](const OpenMPClauseKind K) {
2126 if (isOpenMPPrivate(K)) {
2127 OMPC = K;
2128 return true;
2129 }
2130 return false;
2131 },
2132 NewLevel))
2133 break;
2134 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2135 D, NewLevel,
2136 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2137 OpenMPClauseKind) { return true; })) {
2138 OMPC = OMPC_map;
2139 break;
2140 }
2141 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2142 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002143 OMPC = OMPC_map;
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002144 if (DSAStack->mustBeFirstprivateAtLevel(
2145 NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002146 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002147 break;
2148 }
2149 }
2150 if (OMPC != OMPC_unknown)
2151 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2152}
2153
Alexey Bataeve3727102018-04-18 15:57:46 +00002154bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2155 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002156 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2157 // Return true if the current level is no longer enclosed in a target region.
2158
Alexey Bataeve3727102018-04-18 15:57:46 +00002159 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002160 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002161 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2162 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00002163}
2164
Alexey Bataeved09d242014-05-28 05:53:51 +00002165void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002166
Alexey Bataev729e2422019-08-23 16:11:14 +00002167void Sema::finalizeOpenMPDelayedAnalysis() {
2168 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2169 // Diagnose implicit declare target functions and their callees.
2170 for (const auto &CallerCallees : DeviceCallGraph) {
2171 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2172 OMPDeclareTargetDeclAttr::getDeviceType(
2173 CallerCallees.getFirst()->getMostRecentDecl());
2174 // Ignore host functions during device analyzis.
2175 if (LangOpts.OpenMPIsDevice && DevTy &&
2176 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2177 continue;
2178 // Ignore nohost functions during host analyzis.
2179 if (!LangOpts.OpenMPIsDevice && DevTy &&
2180 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2181 continue;
2182 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2183 &Callee : CallerCallees.getSecond()) {
2184 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2185 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2186 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2187 if (LangOpts.OpenMPIsDevice && DevTy &&
2188 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2189 // Diagnose host function called during device codegen.
2190 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2191 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2192 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2193 << HostDevTy << 0;
2194 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2195 diag::note_omp_marked_device_type_here)
2196 << HostDevTy;
2197 continue;
2198 }
2199 if (!LangOpts.OpenMPIsDevice && DevTy &&
2200 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2201 // Diagnose nohost function called during host codegen.
2202 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2203 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2204 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2205 << NoHostDevTy << 1;
2206 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2207 diag::note_omp_marked_device_type_here)
2208 << NoHostDevTy;
2209 continue;
2210 }
2211 }
2212 }
2213}
2214
Alexey Bataev758e55e2013-09-06 18:03:48 +00002215void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2216 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002217 Scope *CurScope, SourceLocation Loc) {
2218 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002219 PushExpressionEvaluationContext(
2220 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002221}
2222
Alexey Bataevaac108a2015-06-23 04:51:00 +00002223void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2224 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002225}
2226
Alexey Bataevaac108a2015-06-23 04:51:00 +00002227void Sema::EndOpenMPClause() {
2228 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002229}
2230
Alexey Bataeve106f252019-04-01 14:25:31 +00002231static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2232 ArrayRef<OMPClause *> Clauses);
Alexey Bataev0860db92019-12-19 10:01:10 -05002233static std::pair<ValueDecl *, bool>
2234getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2235 SourceRange &ERange, bool AllowArraySection = false);
2236static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2237 bool WithInit);
Alexey Bataeve106f252019-04-01 14:25:31 +00002238
Alexey Bataev758e55e2013-09-06 18:03:48 +00002239void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002240 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2241 // A variable of class type (or array thereof) that appears in a lastprivate
2242 // clause requires an accessible, unambiguous default constructor for the
2243 // class type, unless the list item is also specified in a firstprivate
2244 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002245 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2246 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002247 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2248 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002249 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002250 if (DE->isValueDependent() || DE->isTypeDependent()) {
2251 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002252 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002253 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002254 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002255 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002256 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002257 const DSAStackTy::DSAVarData DVar =
2258 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002259 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002260 // Generate helper private variable and initialize it with the
2261 // default value. The address of the original variable is replaced
2262 // by the address of the new private variable in CodeGen. This new
2263 // variable is not added to IdResolver, so the code in the OpenMP
2264 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002265 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002266 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002267 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002268 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002269 if (VDPrivate->isInvalidDecl()) {
2270 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002271 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002272 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002273 PrivateCopies.push_back(buildDeclRefExpr(
2274 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002275 } else {
2276 // The variable is also a firstprivate, so initialization sequence
2277 // for private copy is generated already.
2278 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002279 }
2280 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002281 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataev0860db92019-12-19 10:01:10 -05002282 continue;
2283 }
2284 // Finalize nontemporal clause by handling private copies, if any.
2285 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2286 SmallVector<Expr *, 8> PrivateRefs;
2287 for (Expr *RefExpr : Clause->varlists()) {
2288 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2289 SourceLocation ELoc;
2290 SourceRange ERange;
2291 Expr *SimpleRefExpr = RefExpr;
2292 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2293 if (Res.second)
2294 // It will be analyzed later.
2295 PrivateRefs.push_back(RefExpr);
2296 ValueDecl *D = Res.first;
2297 if (!D)
2298 continue;
2299
2300 const DSAStackTy::DSAVarData DVar =
2301 DSAStack->getTopDSA(D, /*FromParent=*/false);
2302 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2303 : SimpleRefExpr);
2304 }
2305 Clause->setPrivateRefs(PrivateRefs);
2306 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002307 }
2308 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002309 // Check allocate clauses.
2310 if (!CurContext->isDependentContext())
2311 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002312 }
2313
Alexey Bataev758e55e2013-09-06 18:03:48 +00002314 DSAStack->pop();
2315 DiscardCleanupsInEvaluationContext();
2316 PopExpressionEvaluationContext();
2317}
2318
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002319static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2320 Expr *NumIterations, Sema &SemaRef,
2321 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002322
Alexey Bataeva769e072013-03-22 06:34:35 +00002323namespace {
2324
Alexey Bataeve3727102018-04-18 15:57:46 +00002325class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002326private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002327 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002328
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002329public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002330 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002331 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002332 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002333 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002334 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002335 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2336 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002337 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002338 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002339 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002340
2341 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002342 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002343 }
2344
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002345};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002346
Alexey Bataeve3727102018-04-18 15:57:46 +00002347class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002348private:
2349 Sema &SemaRef;
2350
2351public:
2352 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2353 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2354 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002355 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2356 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002357 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2358 SemaRef.getCurScope());
2359 }
2360 return false;
2361 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002362
2363 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002364 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002365 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002366};
2367
Alexey Bataeved09d242014-05-28 05:53:51 +00002368} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002369
2370ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2371 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002372 const DeclarationNameInfo &Id,
2373 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002374 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2375 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2376
2377 if (Lookup.isAmbiguous())
2378 return ExprError();
2379
2380 VarDecl *VD;
2381 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002382 VarDeclFilterCCC CCC(*this);
2383 if (TypoCorrection Corrected =
2384 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2385 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002386 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002387 PDiag(Lookup.empty()
2388 ? diag::err_undeclared_var_use_suggest
2389 : diag::err_omp_expected_var_arg_suggest)
2390 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002391 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002392 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002393 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2394 : diag::err_omp_expected_var_arg)
2395 << Id.getName();
2396 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002397 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002398 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2399 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2400 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2401 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002402 }
2403 Lookup.suppressDiagnostics();
2404
2405 // OpenMP [2.9.2, Syntax, C/C++]
2406 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002407 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002408 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002409 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002410 bool IsDecl =
2411 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002412 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002413 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2414 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002415 return ExprError();
2416 }
2417
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002418 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002419 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002420 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2421 // A threadprivate directive for file-scope variables must appear outside
2422 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002423 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2424 !getCurLexicalContext()->isTranslationUnit()) {
2425 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002426 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002427 bool IsDecl =
2428 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2429 Diag(VD->getLocation(),
2430 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2431 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002432 return ExprError();
2433 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002434 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2435 // A threadprivate directive for static class member variables must appear
2436 // in the class definition, in the same scope in which the member
2437 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002438 if (CanonicalVD->isStaticDataMember() &&
2439 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2440 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002441 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002442 bool IsDecl =
2443 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2444 Diag(VD->getLocation(),
2445 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2446 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002447 return ExprError();
2448 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002449 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2450 // A threadprivate directive for namespace-scope variables must appear
2451 // outside any definition or declaration other than the namespace
2452 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002453 if (CanonicalVD->getDeclContext()->isNamespace() &&
2454 (!getCurLexicalContext()->isFileContext() ||
2455 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2456 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002457 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002458 bool IsDecl =
2459 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2460 Diag(VD->getLocation(),
2461 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2462 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002463 return ExprError();
2464 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002465 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2466 // A threadprivate directive for static block-scope variables must appear
2467 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002468 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002469 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002470 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002471 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002472 bool IsDecl =
2473 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2474 Diag(VD->getLocation(),
2475 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2476 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002477 return ExprError();
2478 }
2479
2480 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2481 // A threadprivate directive must lexically precede all references to any
2482 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002483 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2484 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002485 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002486 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002487 return ExprError();
2488 }
2489
2490 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002491 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2492 SourceLocation(), VD,
2493 /*RefersToEnclosingVariableOrCapture=*/false,
2494 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002495}
2496
Alexey Bataeved09d242014-05-28 05:53:51 +00002497Sema::DeclGroupPtrTy
2498Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2499 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002500 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002501 CurContext->addDecl(D);
2502 return DeclGroupPtrTy::make(DeclGroupRef(D));
2503 }
David Blaikie0403cb12016-01-15 23:43:25 +00002504 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002505}
2506
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002507namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002508class LocalVarRefChecker final
2509 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002510 Sema &SemaRef;
2511
2512public:
2513 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002514 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002515 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002516 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002517 diag::err_omp_local_var_in_threadprivate_init)
2518 << E->getSourceRange();
2519 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2520 << VD << VD->getSourceRange();
2521 return true;
2522 }
2523 }
2524 return false;
2525 }
2526 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002527 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002528 if (Child && Visit(Child))
2529 return true;
2530 }
2531 return false;
2532 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002533 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002534};
2535} // namespace
2536
Alexey Bataeved09d242014-05-28 05:53:51 +00002537OMPThreadPrivateDecl *
2538Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002539 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002540 for (Expr *RefExpr : VarList) {
2541 auto *DE = cast<DeclRefExpr>(RefExpr);
2542 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002543 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002544
Alexey Bataev376b4a42016-02-09 09:41:09 +00002545 // Mark variable as used.
2546 VD->setReferenced();
2547 VD->markUsed(Context);
2548
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002549 QualType QType = VD->getType();
2550 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2551 // It will be analyzed later.
2552 Vars.push_back(DE);
2553 continue;
2554 }
2555
Alexey Bataeva769e072013-03-22 06:34:35 +00002556 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2557 // A threadprivate variable must not have an incomplete type.
2558 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002559 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002560 continue;
2561 }
2562
2563 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2564 // A threadprivate variable must not have a reference type.
2565 if (VD->getType()->isReferenceType()) {
2566 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002567 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2568 bool IsDecl =
2569 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2570 Diag(VD->getLocation(),
2571 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2572 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002573 continue;
2574 }
2575
Samuel Antaof8b50122015-07-13 22:54:53 +00002576 // Check if this is a TLS variable. If TLS is not being supported, produce
2577 // the corresponding diagnostic.
2578 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2579 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2580 getLangOpts().OpenMPUseTLS &&
2581 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002582 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2583 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002584 Diag(ILoc, diag::err_omp_var_thread_local)
2585 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002586 bool IsDecl =
2587 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2588 Diag(VD->getLocation(),
2589 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2590 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002591 continue;
2592 }
2593
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002594 // Check if initial value of threadprivate variable reference variable with
2595 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002596 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002597 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002598 if (Checker.Visit(Init))
2599 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002600 }
2601
Alexey Bataeved09d242014-05-28 05:53:51 +00002602 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002603 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002604 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2605 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002606 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002607 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002608 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002609 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002610 if (!Vars.empty()) {
2611 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2612 Vars);
2613 D->setAccess(AS_public);
2614 }
2615 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002616}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002617
Alexey Bataev27ef9512019-03-20 20:14:22 +00002618static OMPAllocateDeclAttr::AllocatorTypeTy
2619getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2620 if (!Allocator)
2621 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2622 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2623 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002624 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002625 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002626 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002627 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002628 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2629 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2630 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002631 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002632 llvm::FoldingSetNodeID AEId, DAEId;
2633 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2634 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2635 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002636 AllocatorKindRes = AllocatorKind;
2637 break;
2638 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002639 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002640 return AllocatorKindRes;
2641}
2642
Alexey Bataeve106f252019-04-01 14:25:31 +00002643static bool checkPreviousOMPAllocateAttribute(
2644 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2645 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2646 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2647 return false;
2648 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2649 Expr *PrevAllocator = A->getAllocator();
2650 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2651 getAllocatorKind(S, Stack, PrevAllocator);
2652 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2653 if (AllocatorsMatch &&
2654 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2655 Allocator && PrevAllocator) {
2656 const Expr *AE = Allocator->IgnoreParenImpCasts();
2657 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2658 llvm::FoldingSetNodeID AEId, PAEId;
2659 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2660 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2661 AllocatorsMatch = AEId == PAEId;
2662 }
2663 if (!AllocatorsMatch) {
2664 SmallString<256> AllocatorBuffer;
2665 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2666 if (Allocator)
2667 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2668 SmallString<256> PrevAllocatorBuffer;
2669 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2670 if (PrevAllocator)
2671 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2672 S.getPrintingPolicy());
2673
2674 SourceLocation AllocatorLoc =
2675 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2676 SourceRange AllocatorRange =
2677 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2678 SourceLocation PrevAllocatorLoc =
2679 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2680 SourceRange PrevAllocatorRange =
2681 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2682 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2683 << (Allocator ? 1 : 0) << AllocatorStream.str()
2684 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2685 << AllocatorRange;
2686 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2687 << PrevAllocatorRange;
2688 return true;
2689 }
2690 return false;
2691}
2692
2693static void
2694applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2695 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2696 Expr *Allocator, SourceRange SR) {
2697 if (VD->hasAttr<OMPAllocateDeclAttr>())
2698 return;
2699 if (Allocator &&
2700 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2701 Allocator->isInstantiationDependent() ||
2702 Allocator->containsUnexpandedParameterPack()))
2703 return;
2704 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2705 Allocator, SR);
2706 VD->addAttr(A);
2707 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2708 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2709}
2710
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002711Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2712 SourceLocation Loc, ArrayRef<Expr *> VarList,
2713 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2714 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2715 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002716 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002717 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2718 // allocate directives that appear in a target region must specify an
2719 // allocator clause unless a requires directive with the dynamic_allocators
2720 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002721 if (LangOpts.OpenMPIsDevice &&
2722 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002723 targetDiag(Loc, diag::err_expected_allocator_clause);
2724 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002725 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002726 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002727 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2728 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002729 SmallVector<Expr *, 8> Vars;
2730 for (Expr *RefExpr : VarList) {
2731 auto *DE = cast<DeclRefExpr>(RefExpr);
2732 auto *VD = cast<VarDecl>(DE->getDecl());
2733
2734 // Check if this is a TLS variable or global register.
2735 if (VD->getTLSKind() != VarDecl::TLS_None ||
2736 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2737 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2738 !VD->isLocalVarDecl()))
2739 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002740
Alexey Bataev282555a2019-03-19 20:33:44 +00002741 // If the used several times in the allocate directive, the same allocator
2742 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002743 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2744 AllocatorKind, Allocator))
2745 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002746
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002747 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2748 // If a list item has a static storage type, the allocator expression in the
2749 // allocator clause must be a constant expression that evaluates to one of
2750 // the predefined memory allocator values.
2751 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002752 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002753 Diag(Allocator->getExprLoc(),
2754 diag::err_omp_expected_predefined_allocator)
2755 << Allocator->getSourceRange();
2756 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2757 VarDecl::DeclarationOnly;
2758 Diag(VD->getLocation(),
2759 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2760 << VD;
2761 continue;
2762 }
2763 }
2764
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002765 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002766 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2767 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002768 }
2769 if (Vars.empty())
2770 return nullptr;
2771 if (!Owner)
2772 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002773 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002774 D->setAccess(AS_public);
2775 Owner->addDecl(D);
2776 return DeclGroupPtrTy::make(DeclGroupRef(D));
2777}
2778
2779Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002780Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2781 ArrayRef<OMPClause *> ClauseList) {
2782 OMPRequiresDecl *D = nullptr;
2783 if (!CurContext->isFileContext()) {
2784 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2785 } else {
2786 D = CheckOMPRequiresDecl(Loc, ClauseList);
2787 if (D) {
2788 CurContext->addDecl(D);
2789 DSAStack->addRequiresDecl(D);
2790 }
2791 }
2792 return DeclGroupPtrTy::make(DeclGroupRef(D));
2793}
2794
2795OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2796 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002797 /// For target specific clauses, the requires directive cannot be
2798 /// specified after the handling of any of the target regions in the
2799 /// current compilation unit.
2800 ArrayRef<SourceLocation> TargetLocations =
2801 DSAStack->getEncounteredTargetLocs();
2802 if (!TargetLocations.empty()) {
2803 for (const OMPClause *CNew : ClauseList) {
2804 // Check if any of the requires clauses affect target regions.
2805 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2806 isa<OMPUnifiedAddressClause>(CNew) ||
2807 isa<OMPReverseOffloadClause>(CNew) ||
2808 isa<OMPDynamicAllocatorsClause>(CNew)) {
2809 Diag(Loc, diag::err_omp_target_before_requires)
2810 << getOpenMPClauseName(CNew->getClauseKind());
2811 for (SourceLocation TargetLoc : TargetLocations) {
2812 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2813 }
2814 }
2815 }
2816 }
2817
Kelvin Li1408f912018-09-26 04:28:39 +00002818 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2819 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2820 ClauseList);
2821 return nullptr;
2822}
2823
Alexey Bataeve3727102018-04-18 15:57:46 +00002824static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2825 const ValueDecl *D,
2826 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002827 bool IsLoopIterVar = false) {
2828 if (DVar.RefExpr) {
2829 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2830 << getOpenMPClauseName(DVar.CKind);
2831 return;
2832 }
2833 enum {
2834 PDSA_StaticMemberShared,
2835 PDSA_StaticLocalVarShared,
2836 PDSA_LoopIterVarPrivate,
2837 PDSA_LoopIterVarLinear,
2838 PDSA_LoopIterVarLastprivate,
2839 PDSA_ConstVarShared,
2840 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002841 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002842 PDSA_LocalVarPrivate,
2843 PDSA_Implicit
2844 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002845 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002846 auto ReportLoc = D->getLocation();
2847 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002848 if (IsLoopIterVar) {
2849 if (DVar.CKind == OMPC_private)
2850 Reason = PDSA_LoopIterVarPrivate;
2851 else if (DVar.CKind == OMPC_lastprivate)
2852 Reason = PDSA_LoopIterVarLastprivate;
2853 else
2854 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002855 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2856 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002857 Reason = PDSA_TaskVarFirstprivate;
2858 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002859 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002860 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002861 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002862 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002863 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002864 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002865 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002866 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002867 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002868 ReportHint = true;
2869 Reason = PDSA_LocalVarPrivate;
2870 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002871 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002872 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002873 << Reason << ReportHint
2874 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2875 } else if (DVar.ImplicitDSALoc.isValid()) {
2876 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2877 << getOpenMPClauseName(DVar.CKind);
2878 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002879}
2880
cchene06f3e02019-11-15 13:02:06 -05002881static OpenMPMapClauseKind
2882getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
2883 bool IsAggregateOrDeclareTarget) {
2884 OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
2885 switch (M) {
2886 case OMPC_DEFAULTMAP_MODIFIER_alloc:
2887 Kind = OMPC_MAP_alloc;
2888 break;
2889 case OMPC_DEFAULTMAP_MODIFIER_to:
2890 Kind = OMPC_MAP_to;
2891 break;
2892 case OMPC_DEFAULTMAP_MODIFIER_from:
2893 Kind = OMPC_MAP_from;
2894 break;
2895 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
2896 Kind = OMPC_MAP_tofrom;
2897 break;
2898 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
2899 case OMPC_DEFAULTMAP_MODIFIER_last:
2900 llvm_unreachable("Unexpected defaultmap implicit behavior");
2901 case OMPC_DEFAULTMAP_MODIFIER_none:
2902 case OMPC_DEFAULTMAP_MODIFIER_default:
2903 case OMPC_DEFAULTMAP_MODIFIER_unknown:
2904 // IsAggregateOrDeclareTarget could be true if:
2905 // 1. the implicit behavior for aggregate is tofrom
2906 // 2. it's a declare target link
2907 if (IsAggregateOrDeclareTarget) {
2908 Kind = OMPC_MAP_tofrom;
2909 break;
2910 }
2911 llvm_unreachable("Unexpected defaultmap implicit behavior");
2912 }
2913 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
2914 return Kind;
2915}
2916
Alexey Bataev758e55e2013-09-06 18:03:48 +00002917namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002918class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002919 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002920 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002921 bool ErrorFound = false;
Alexey Bataevc09c0652019-10-29 10:06:11 -04002922 bool TryCaptureCXXThisMembers = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00002923 CapturedStmt *CS = nullptr;
2924 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
cchene06f3e02019-11-15 13:02:06 -05002925 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
Alexey Bataeve3727102018-04-18 15:57:46 +00002926 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2927 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002928
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002929 void VisitSubCaptures(OMPExecutableDirective *S) {
2930 // Check implicitly captured variables.
2931 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2932 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002933 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataevc09c0652019-10-29 10:06:11 -04002934 // Try to capture inner this->member references to generate correct mappings
2935 // and diagnostics.
2936 if (TryCaptureCXXThisMembers ||
2937 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2938 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2939 [](const CapturedStmt::Capture &C) {
2940 return C.capturesThis();
2941 }))) {
2942 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2943 TryCaptureCXXThisMembers = true;
2944 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2945 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2946 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002947 }
2948
Alexey Bataev758e55e2013-09-06 18:03:48 +00002949public:
2950 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataevc09c0652019-10-29 10:06:11 -04002951 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
2952 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
2953 E->isInstantiationDependent())
Alexey Bataev07b79c22016-04-29 09:56:11 +00002954 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002955 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002956 // Check the datasharing rules for the expressions in the clauses.
2957 if (!CS) {
2958 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2959 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2960 Visit(CED->getInit());
2961 return;
2962 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002963 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2964 // Do not analyze internal variables and do not enclose them into
2965 // implicit clauses.
2966 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002967 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002968 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002969 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002970 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002971
Alexey Bataeve3727102018-04-18 15:57:46 +00002972 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002973 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002974 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002975 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002976
Alexey Bataevafe50572017-10-06 17:00:28 +00002977 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002978 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002979 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002980 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002981 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2982 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002983 return;
2984
Alexey Bataeve3727102018-04-18 15:57:46 +00002985 SourceLocation ELoc = E->getExprLoc();
2986 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002987 // The default(none) clause requires that each variable that is referenced
2988 // in the construct, and does not have a predetermined data-sharing
2989 // attribute, must have its data-sharing attribute explicitly determined
2990 // by being listed in a data-sharing attribute clause.
2991 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002992 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002993 VarsWithInheritedDSA.count(VD) == 0) {
2994 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002995 return;
2996 }
2997
cchene06f3e02019-11-15 13:02:06 -05002998 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
2999 // If implicit-behavior is none, each variable referenced in the
3000 // construct that does not have a predetermined data-sharing attribute
3001 // and does not appear in a to or link clause on a declare target
3002 // directive must be listed in a data-mapping attribute clause, a
3003 // data-haring attribute clause (including a data-sharing attribute
3004 // clause on a combined construct where target. is one of the
3005 // constituent constructs), or an is_device_ptr clause.
Alexey Bataev6f7c8762019-11-22 11:09:33 -05003006 OpenMPDefaultmapClauseKind ClauseKind =
3007 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
cchene06f3e02019-11-15 13:02:06 -05003008 if (SemaRef.getLangOpts().OpenMP >= 50) {
3009 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3010 OMPC_DEFAULTMAP_MODIFIER_none;
3011 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3012 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3013 // Only check for data-mapping attribute and is_device_ptr here
3014 // since we have already make sure that the declaration does not
3015 // have a data-sharing attribute above
3016 if (!Stack->checkMappableExprComponentListsForDecl(
3017 VD, /*CurrentRegionOnly=*/true,
3018 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3019 MapExprComponents,
3020 OpenMPClauseKind) {
3021 auto MI = MapExprComponents.rbegin();
3022 auto ME = MapExprComponents.rend();
3023 return MI != ME && MI->getAssociatedDeclaration() == VD;
3024 })) {
3025 VarsWithInheritedDSA[VD] = E;
3026 return;
3027 }
3028 }
3029 }
3030
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003031 if (isOpenMPTargetExecutionDirective(DKind) &&
3032 !Stack->isLoopControlVariable(VD).first) {
3033 if (!Stack->checkMappableExprComponentListsForDecl(
3034 VD, /*CurrentRegionOnly=*/true,
3035 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3036 StackComponents,
3037 OpenMPClauseKind) {
3038 // Variable is used if it has been marked as an array, array
3039 // section or the variable iself.
3040 return StackComponents.size() == 1 ||
3041 std::all_of(
3042 std::next(StackComponents.rbegin()),
3043 StackComponents.rend(),
3044 [](const OMPClauseMappableExprCommon::
3045 MappableComponent &MC) {
3046 return MC.getAssociatedDeclaration() ==
3047 nullptr &&
3048 (isa<OMPArraySectionExpr>(
3049 MC.getAssociatedExpression()) ||
3050 isa<ArraySubscriptExpr>(
3051 MC.getAssociatedExpression()));
3052 });
3053 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003054 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003055 // By default lambdas are captured as firstprivates.
3056 if (const auto *RD =
3057 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003058 IsFirstprivate = RD->isLambda();
3059 IsFirstprivate =
cchene06f3e02019-11-15 13:02:06 -05003060 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3061 if (IsFirstprivate) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003062 ImplicitFirstprivate.emplace_back(E);
cchene06f3e02019-11-15 13:02:06 -05003063 } else {
3064 OpenMPDefaultmapClauseModifier M =
3065 Stack->getDefaultmapModifier(ClauseKind);
3066 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3067 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3068 ImplicitMap[Kind].emplace_back(E);
3069 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003070 return;
3071 }
3072 }
3073
Alexey Bataev758e55e2013-09-06 18:03:48 +00003074 // OpenMP [2.9.3.6, Restrictions, p.2]
3075 // A list item that appears in a reduction clause of the innermost
3076 // enclosing worksharing or parallel construct may not be accessed in an
3077 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003078 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003079 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3080 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003081 return isOpenMPParallelDirective(K) ||
3082 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3083 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00003084 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003085 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00003086 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00003087 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003088 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00003089 return;
3090 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003091
3092 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003093 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003094 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00003095 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003096 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00003097 return;
3098 }
3099
3100 // Store implicitly used globals with declare target link for parent
3101 // target.
3102 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3103 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3104 Stack->addToParentTargetRegionLinkGlobals(E);
3105 return;
3106 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003107 }
3108 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003109 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00003110 if (E->isTypeDependent() || E->isValueDependent() ||
3111 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3112 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003113 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003114 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00003115 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003116 if (!FD)
3117 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003118 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003119 // Check if the variable has explicit DSA set and stop analysis if it
3120 // so.
3121 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3122 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003123
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003124 if (isOpenMPTargetExecutionDirective(DKind) &&
3125 !Stack->isLoopControlVariable(FD).first &&
3126 !Stack->checkMappableExprComponentListsForDecl(
3127 FD, /*CurrentRegionOnly=*/true,
3128 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3129 StackComponents,
3130 OpenMPClauseKind) {
3131 return isa<CXXThisExpr>(
3132 cast<MemberExpr>(
3133 StackComponents.back().getAssociatedExpression())
3134 ->getBase()
3135 ->IgnoreParens());
3136 })) {
3137 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3138 // A bit-field cannot appear in a map clause.
3139 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003140 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003141 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00003142
3143 // Check to see if the member expression is referencing a class that
3144 // has already been explicitly mapped
3145 if (Stack->isClassPreviouslyMapped(TE->getType()))
3146 return;
3147
cchene06f3e02019-11-15 13:02:06 -05003148 OpenMPDefaultmapClauseModifier Modifier =
3149 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3150 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3151 Modifier, /*IsAggregateOrDeclareTarget*/ true);
3152 ImplicitMap[Kind].emplace_back(E);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003153 return;
3154 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003155
Alexey Bataeve3727102018-04-18 15:57:46 +00003156 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003157 // OpenMP [2.9.3.6, Restrictions, p.2]
3158 // A list item that appears in a reduction clause of the innermost
3159 // enclosing worksharing or parallel construct may not be accessed in
3160 // an explicit task.
3161 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003162 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3163 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003164 return isOpenMPParallelDirective(K) ||
3165 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3166 },
3167 /*FromParent=*/true);
3168 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3169 ErrorFound = true;
3170 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003171 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003172 return;
3173 }
3174
3175 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003176 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003177 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00003178 !Stack->isLoopControlVariable(FD).first) {
3179 // Check if there is a captured expression for the current field in the
3180 // region. Do not mark it as firstprivate unless there is no captured
3181 // expression.
3182 // TODO: try to make it firstprivate.
3183 if (DVar.CKind != OMPC_unknown)
3184 ImplicitFirstprivate.push_back(E);
3185 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003186 return;
3187 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003188 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003189 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00003190 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003191 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003192 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003193 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003194 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3195 if (!Stack->checkMappableExprComponentListsForDecl(
3196 VD, /*CurrentRegionOnly=*/true,
3197 [&CurComponents](
3198 OMPClauseMappableExprCommon::MappableExprComponentListRef
3199 StackComponents,
3200 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003201 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003202 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003203 for (const auto &SC : llvm::reverse(StackComponents)) {
3204 // Do both expressions have the same kind?
3205 if (CCI->getAssociatedExpression()->getStmtClass() !=
3206 SC.getAssociatedExpression()->getStmtClass())
3207 if (!(isa<OMPArraySectionExpr>(
3208 SC.getAssociatedExpression()) &&
3209 isa<ArraySubscriptExpr>(
3210 CCI->getAssociatedExpression())))
3211 return false;
3212
Alexey Bataeve3727102018-04-18 15:57:46 +00003213 const Decl *CCD = CCI->getAssociatedDeclaration();
3214 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003215 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3216 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3217 if (SCD != CCD)
3218 return false;
3219 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003220 if (CCI == CCE)
3221 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003222 }
3223 return true;
3224 })) {
3225 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003226 }
Alexey Bataevc09c0652019-10-29 10:06:11 -04003227 } else if (!TryCaptureCXXThisMembers) {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003228 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003229 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003230 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003231 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003232 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003233 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003234 // for task|target directives.
3235 // Skip analysis of arguments of implicitly defined map clause for target
3236 // directives.
3237 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3238 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003239 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003240 if (CC)
3241 Visit(CC);
3242 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003243 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003244 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003245 // Check implicitly captured variables.
3246 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003247 }
3248 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003249 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003250 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003251 // Check implicitly captured variables in the task-based directives to
3252 // check if they must be firstprivatized.
3253 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003254 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003255 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003256 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003257
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003258 void visitSubCaptures(CapturedStmt *S) {
3259 for (const CapturedStmt::Capture &Cap : S->captures()) {
3260 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3261 continue;
3262 VarDecl *VD = Cap.getCapturedVar();
3263 // Do not try to map the variable if it or its sub-component was mapped
3264 // already.
3265 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3266 Stack->checkMappableExprComponentListsForDecl(
3267 VD, /*CurrentRegionOnly=*/true,
3268 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3269 OpenMPClauseKind) { return true; }))
3270 continue;
3271 DeclRefExpr *DRE = buildDeclRefExpr(
3272 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3273 Cap.getLocation(), /*RefersToCapture=*/true);
3274 Visit(DRE);
3275 }
3276 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003277 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003278 ArrayRef<Expr *> getImplicitFirstprivate() const {
3279 return ImplicitFirstprivate;
3280 }
cchene06f3e02019-11-15 13:02:06 -05003281 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3282 return ImplicitMap[Kind];
3283 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003284 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003285 return VarsWithInheritedDSA;
3286 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003287
Alexey Bataev7ff55242014-06-19 09:13:45 +00003288 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003289 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3290 // Process declare target link variables for the target directives.
3291 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3292 for (DeclRefExpr *E : Stack->getLinkGlobals())
3293 Visit(E);
3294 }
3295 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003296};
Alexey Bataeved09d242014-05-28 05:53:51 +00003297} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003298
Alexey Bataevbae9a792014-06-27 10:37:06 +00003299void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003300 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003301 case OMPD_parallel:
3302 case OMPD_parallel_for:
3303 case OMPD_parallel_for_simd:
3304 case OMPD_parallel_sections:
cchen47d60942019-12-05 13:43:48 -05003305 case OMPD_parallel_master:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003306 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003307 case OMPD_teams_distribute:
3308 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003309 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003310 QualType KmpInt32PtrTy =
3311 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003312 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003313 std::make_pair(".global_tid.", KmpInt32PtrTy),
3314 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3315 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003316 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003317 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3318 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003319 break;
3320 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003321 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003322 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003323 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003324 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003325 case OMPD_target_teams_distribute:
3326 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003327 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3328 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3329 QualType KmpInt32PtrTy =
3330 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3331 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003332 FunctionProtoType::ExtProtoInfo EPI;
3333 EPI.Variadic = true;
3334 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3335 Sema::CapturedParamNameType Params[] = {
3336 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003337 std::make_pair(".part_id.", KmpInt32PtrTy),
3338 std::make_pair(".privates.", VoidPtrTy),
3339 std::make_pair(
3340 ".copy_fn.",
3341 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003342 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3343 std::make_pair(StringRef(), QualType()) // __context with shared vars
3344 };
3345 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003346 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003347 // Mark this captured region as inlined, because we don't use outlined
3348 // function directly.
3349 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3350 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003351 Context, {}, AttributeCommonInfo::AS_Keyword,
3352 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003353 Sema::CapturedParamNameType ParamsTarget[] = {
3354 std::make_pair(StringRef(), QualType()) // __context with shared vars
3355 };
3356 // Start a captured region for 'target' with no implicit parameters.
3357 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003358 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003359 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003360 std::make_pair(".global_tid.", KmpInt32PtrTy),
3361 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3362 std::make_pair(StringRef(), QualType()) // __context with shared vars
3363 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003364 // Start a captured region for 'teams' or 'parallel'. Both regions have
3365 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003366 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003367 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003368 break;
3369 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003370 case OMPD_target:
3371 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003372 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3373 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3374 QualType KmpInt32PtrTy =
3375 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3376 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003377 FunctionProtoType::ExtProtoInfo EPI;
3378 EPI.Variadic = true;
3379 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3380 Sema::CapturedParamNameType Params[] = {
3381 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003382 std::make_pair(".part_id.", KmpInt32PtrTy),
3383 std::make_pair(".privates.", VoidPtrTy),
3384 std::make_pair(
3385 ".copy_fn.",
3386 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003387 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3388 std::make_pair(StringRef(), QualType()) // __context with shared vars
3389 };
3390 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003391 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003392 // Mark this captured region as inlined, because we don't use outlined
3393 // function directly.
3394 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3395 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003396 Context, {}, AttributeCommonInfo::AS_Keyword,
3397 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003398 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003399 std::make_pair(StringRef(), QualType()),
3400 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003401 break;
3402 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003403 case OMPD_simd:
3404 case OMPD_for:
3405 case OMPD_for_simd:
3406 case OMPD_sections:
3407 case OMPD_section:
3408 case OMPD_single:
3409 case OMPD_master:
3410 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003411 case OMPD_taskgroup:
3412 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003413 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003414 case OMPD_ordered:
3415 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003416 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003417 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003418 std::make_pair(StringRef(), QualType()) // __context with shared vars
3419 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003420 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3421 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003422 break;
3423 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003424 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003425 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3426 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3427 QualType KmpInt32PtrTy =
3428 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3429 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003430 FunctionProtoType::ExtProtoInfo EPI;
3431 EPI.Variadic = true;
3432 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003433 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003434 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003435 std::make_pair(".part_id.", KmpInt32PtrTy),
3436 std::make_pair(".privates.", VoidPtrTy),
3437 std::make_pair(
3438 ".copy_fn.",
3439 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003440 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003441 std::make_pair(StringRef(), QualType()) // __context with shared vars
3442 };
3443 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3444 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003445 // Mark this captured region as inlined, because we don't use outlined
3446 // function directly.
3447 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3448 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003449 Context, {}, AttributeCommonInfo::AS_Keyword,
3450 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003451 break;
3452 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003453 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003454 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003455 case OMPD_master_taskloop:
3456 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003457 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003458 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3459 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003460 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003461 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3462 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003463 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003464 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3465 .withConst();
3466 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3467 QualType KmpInt32PtrTy =
3468 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3469 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003470 FunctionProtoType::ExtProtoInfo EPI;
3471 EPI.Variadic = true;
3472 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003473 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003474 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003475 std::make_pair(".part_id.", KmpInt32PtrTy),
3476 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003477 std::make_pair(
3478 ".copy_fn.",
3479 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3480 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3481 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003482 std::make_pair(".ub.", KmpUInt64Ty),
3483 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003484 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003485 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003486 std::make_pair(StringRef(), QualType()) // __context with shared vars
3487 };
3488 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3489 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003490 // Mark this captured region as inlined, because we don't use outlined
3491 // function directly.
3492 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3493 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003494 Context, {}, AttributeCommonInfo::AS_Keyword,
3495 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003496 break;
3497 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04003498 case OMPD_parallel_master_taskloop:
3499 case OMPD_parallel_master_taskloop_simd: {
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003500 QualType KmpInt32Ty =
3501 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3502 .withConst();
3503 QualType KmpUInt64Ty =
3504 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3505 .withConst();
3506 QualType KmpInt64Ty =
3507 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3508 .withConst();
3509 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3510 QualType KmpInt32PtrTy =
3511 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3512 Sema::CapturedParamNameType ParamsParallel[] = {
3513 std::make_pair(".global_tid.", KmpInt32PtrTy),
3514 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3515 std::make_pair(StringRef(), QualType()) // __context with shared vars
3516 };
3517 // Start a captured region for 'parallel'.
3518 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3519 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3520 QualType Args[] = {VoidPtrTy};
3521 FunctionProtoType::ExtProtoInfo EPI;
3522 EPI.Variadic = true;
3523 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3524 Sema::CapturedParamNameType Params[] = {
3525 std::make_pair(".global_tid.", KmpInt32Ty),
3526 std::make_pair(".part_id.", KmpInt32PtrTy),
3527 std::make_pair(".privates.", VoidPtrTy),
3528 std::make_pair(
3529 ".copy_fn.",
3530 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3531 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3532 std::make_pair(".lb.", KmpUInt64Ty),
3533 std::make_pair(".ub.", KmpUInt64Ty),
3534 std::make_pair(".st.", KmpInt64Ty),
3535 std::make_pair(".liter.", KmpInt32Ty),
3536 std::make_pair(".reductions.", VoidPtrTy),
3537 std::make_pair(StringRef(), QualType()) // __context with shared vars
3538 };
3539 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3540 Params, /*OpenMPCaptureLevel=*/2);
3541 // Mark this captured region as inlined, because we don't use outlined
3542 // function directly.
3543 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3544 AlwaysInlineAttr::CreateImplicit(
3545 Context, {}, AttributeCommonInfo::AS_Keyword,
3546 AlwaysInlineAttr::Keyword_forceinline));
3547 break;
3548 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003549 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003550 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003551 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003552 QualType KmpInt32PtrTy =
3553 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3554 Sema::CapturedParamNameType Params[] = {
3555 std::make_pair(".global_tid.", KmpInt32PtrTy),
3556 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003557 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3558 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003559 std::make_pair(StringRef(), QualType()) // __context with shared vars
3560 };
3561 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3562 Params);
3563 break;
3564 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003565 case OMPD_target_teams_distribute_parallel_for:
3566 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003567 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003568 QualType KmpInt32PtrTy =
3569 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003570 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003571
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003572 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003573 FunctionProtoType::ExtProtoInfo EPI;
3574 EPI.Variadic = true;
3575 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3576 Sema::CapturedParamNameType Params[] = {
3577 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003578 std::make_pair(".part_id.", KmpInt32PtrTy),
3579 std::make_pair(".privates.", VoidPtrTy),
3580 std::make_pair(
3581 ".copy_fn.",
3582 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003583 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3584 std::make_pair(StringRef(), QualType()) // __context with shared vars
3585 };
3586 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003587 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003588 // Mark this captured region as inlined, because we don't use outlined
3589 // function directly.
3590 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3591 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003592 Context, {}, AttributeCommonInfo::AS_Keyword,
3593 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003594 Sema::CapturedParamNameType ParamsTarget[] = {
3595 std::make_pair(StringRef(), QualType()) // __context with shared vars
3596 };
3597 // Start a captured region for 'target' with no implicit parameters.
3598 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003599 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003600
3601 Sema::CapturedParamNameType ParamsTeams[] = {
3602 std::make_pair(".global_tid.", KmpInt32PtrTy),
3603 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3604 std::make_pair(StringRef(), QualType()) // __context with shared vars
3605 };
3606 // Start a captured region for 'target' with no implicit parameters.
3607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003608 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003609
3610 Sema::CapturedParamNameType ParamsParallel[] = {
3611 std::make_pair(".global_tid.", KmpInt32PtrTy),
3612 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003613 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3614 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003615 std::make_pair(StringRef(), QualType()) // __context with shared vars
3616 };
3617 // Start a captured region for 'teams' or 'parallel'. Both regions have
3618 // the same implicit parameters.
3619 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003620 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003621 break;
3622 }
3623
Alexey Bataev46506272017-12-05 17:41:34 +00003624 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003625 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003626 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003627 QualType KmpInt32PtrTy =
3628 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3629
3630 Sema::CapturedParamNameType ParamsTeams[] = {
3631 std::make_pair(".global_tid.", KmpInt32PtrTy),
3632 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3633 std::make_pair(StringRef(), QualType()) // __context with shared vars
3634 };
3635 // Start a captured region for 'target' with no implicit parameters.
3636 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003637 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003638
3639 Sema::CapturedParamNameType ParamsParallel[] = {
3640 std::make_pair(".global_tid.", KmpInt32PtrTy),
3641 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003642 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3643 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003644 std::make_pair(StringRef(), QualType()) // __context with shared vars
3645 };
3646 // Start a captured region for 'teams' or 'parallel'. Both regions have
3647 // the same implicit parameters.
3648 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003649 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003650 break;
3651 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003652 case OMPD_target_update:
3653 case OMPD_target_enter_data:
3654 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003655 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3656 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3657 QualType KmpInt32PtrTy =
3658 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3659 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003660 FunctionProtoType::ExtProtoInfo EPI;
3661 EPI.Variadic = true;
3662 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3663 Sema::CapturedParamNameType Params[] = {
3664 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003665 std::make_pair(".part_id.", KmpInt32PtrTy),
3666 std::make_pair(".privates.", VoidPtrTy),
3667 std::make_pair(
3668 ".copy_fn.",
3669 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003670 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3671 std::make_pair(StringRef(), QualType()) // __context with shared vars
3672 };
3673 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3674 Params);
3675 // Mark this captured region as inlined, because we don't use outlined
3676 // function directly.
3677 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3678 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003679 Context, {}, AttributeCommonInfo::AS_Keyword,
3680 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003681 break;
3682 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003683 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003684 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003685 case OMPD_taskyield:
3686 case OMPD_barrier:
3687 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003688 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003689 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003690 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003691 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003692 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003693 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003694 case OMPD_declare_target:
3695 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003696 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003697 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003698 llvm_unreachable("OpenMP Directive is not allowed");
3699 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003700 llvm_unreachable("Unknown OpenMP directive");
3701 }
3702}
3703
Alexey Bataev0e100032019-10-14 16:44:01 +00003704int Sema::getNumberOfConstructScopes(unsigned Level) const {
3705 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3706}
3707
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003708int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3709 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3710 getOpenMPCaptureRegions(CaptureRegions, DKind);
3711 return CaptureRegions.size();
3712}
3713
Alexey Bataev3392d762016-02-16 11:18:12 +00003714static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003715 Expr *CaptureExpr, bool WithInit,
3716 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003717 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003718 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003719 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003720 QualType Ty = Init->getType();
3721 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003722 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003723 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003724 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003725 Ty = C.getPointerType(Ty);
3726 ExprResult Res =
3727 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3728 if (!Res.isUsable())
3729 return nullptr;
3730 Init = Res.get();
3731 }
Alexey Bataev61205072016-03-02 04:57:40 +00003732 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003733 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003734 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003735 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003736 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003737 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003738 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003739 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003740 return CED;
3741}
3742
Alexey Bataev61205072016-03-02 04:57:40 +00003743static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3744 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003745 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003746 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003747 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003748 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003749 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3750 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003751 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003752 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003753}
3754
Alexey Bataev5a3af132016-03-29 08:58:54 +00003755static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003756 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003757 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003758 OMPCapturedExprDecl *CD = buildCaptureDecl(
3759 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3760 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003761 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3762 CaptureExpr->getExprLoc());
3763 }
3764 ExprResult Res = Ref;
3765 if (!S.getLangOpts().CPlusPlus &&
3766 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003767 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003768 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003769 if (!Res.isUsable())
3770 return ExprError();
3771 }
3772 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003773}
3774
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003775namespace {
3776// OpenMP directives parsed in this section are represented as a
3777// CapturedStatement with an associated statement. If a syntax error
3778// is detected during the parsing of the associated statement, the
3779// compiler must abort processing and close the CapturedStatement.
3780//
3781// Combined directives such as 'target parallel' have more than one
3782// nested CapturedStatements. This RAII ensures that we unwind out
3783// of all the nested CapturedStatements when an error is found.
3784class CaptureRegionUnwinderRAII {
3785private:
3786 Sema &S;
3787 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003788 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003789
3790public:
3791 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3792 OpenMPDirectiveKind DKind)
3793 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3794 ~CaptureRegionUnwinderRAII() {
3795 if (ErrorFound) {
3796 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3797 while (--ThisCaptureLevel >= 0)
3798 S.ActOnCapturedRegionError();
3799 }
3800 }
3801};
3802} // namespace
3803
Alexey Bataevb600ae32019-07-01 17:46:52 +00003804void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3805 // Capture variables captured by reference in lambdas for target-based
3806 // directives.
3807 if (!CurContext->isDependentContext() &&
3808 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3809 isOpenMPTargetDataManagementDirective(
3810 DSAStack->getCurrentDirective()))) {
3811 QualType Type = V->getType();
3812 if (const auto *RD = Type.getCanonicalType()
3813 .getNonReferenceType()
3814 ->getAsCXXRecordDecl()) {
3815 bool SavedForceCaptureByReferenceInTargetExecutable =
3816 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3817 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3818 /*V=*/true);
3819 if (RD->isLambda()) {
3820 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3821 FieldDecl *ThisCapture;
3822 RD->getCaptureFields(Captures, ThisCapture);
3823 for (const LambdaCapture &LC : RD->captures()) {
3824 if (LC.getCaptureKind() == LCK_ByRef) {
3825 VarDecl *VD = LC.getCapturedVar();
3826 DeclContext *VDC = VD->getDeclContext();
3827 if (!VDC->Encloses(CurContext))
3828 continue;
3829 MarkVariableReferenced(LC.getLocation(), VD);
3830 } else if (LC.getCaptureKind() == LCK_This) {
3831 QualType ThisTy = getCurrentThisType();
3832 if (!ThisTy.isNull() &&
3833 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3834 CheckCXXThisCapture(LC.getLocation());
3835 }
3836 }
3837 }
3838 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3839 SavedForceCaptureByReferenceInTargetExecutable);
3840 }
3841 }
3842}
3843
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003844StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3845 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003846 bool ErrorFound = false;
3847 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3848 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003849 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003850 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003851 return StmtError();
3852 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003853
Alexey Bataev2ba67042017-11-28 21:11:44 +00003854 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3855 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003856 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003857 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003858 SmallVector<const OMPLinearClause *, 4> LCs;
3859 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003860 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003861 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003862 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3863 Clause->getClauseKind() == OMPC_in_reduction) {
3864 // Capture taskgroup task_reduction descriptors inside the tasking regions
3865 // with the corresponding in_reduction items.
3866 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003867 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003868 if (E)
3869 MarkDeclarationsReferencedInExpr(E);
3870 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003871 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003872 Clause->getClauseKind() == OMPC_copyprivate ||
3873 (getLangOpts().OpenMPUseTLS &&
3874 getASTContext().getTargetInfo().isTLSSupported() &&
3875 Clause->getClauseKind() == OMPC_copyin)) {
3876 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003877 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003878 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003879 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003880 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003881 }
3882 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003883 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003884 } else if (CaptureRegions.size() > 1 ||
3885 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003886 if (auto *C = OMPClauseWithPreInit::get(Clause))
3887 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003888 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003889 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003890 MarkDeclarationsReferencedInExpr(E);
3891 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003892 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003893 if (Clause->getClauseKind() == OMPC_schedule)
3894 SC = cast<OMPScheduleClause>(Clause);
3895 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003896 OC = cast<OMPOrderedClause>(Clause);
3897 else if (Clause->getClauseKind() == OMPC_linear)
3898 LCs.push_back(cast<OMPLinearClause>(Clause));
3899 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003900 // OpenMP, 2.7.1 Loop Construct, Restrictions
3901 // The nonmonotonic modifier cannot be specified if an ordered clause is
3902 // specified.
3903 if (SC &&
3904 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3905 SC->getSecondScheduleModifier() ==
3906 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3907 OC) {
3908 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3909 ? SC->getFirstScheduleModifierLoc()
3910 : SC->getSecondScheduleModifierLoc(),
3911 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003912 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003913 ErrorFound = true;
3914 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003915 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003916 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003917 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003918 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003919 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003920 ErrorFound = true;
3921 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003922 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3923 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3924 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003925 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003926 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3927 ErrorFound = true;
3928 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003929 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003930 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003931 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003932 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003933 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003934 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003935 // Mark all variables in private list clauses as used in inner region.
3936 // Required for proper codegen of combined directives.
3937 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003938 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003939 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003940 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3941 // Find the particular capture region for the clause if the
3942 // directive is a combined one with multiple capture regions.
3943 // If the directive is not a combined one, the capture region
3944 // associated with the clause is OMPD_unknown and is generated
3945 // only once.
3946 if (CaptureRegion == ThisCaptureRegion ||
3947 CaptureRegion == OMPD_unknown) {
3948 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003949 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003950 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3951 }
3952 }
3953 }
3954 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003955 if (++CompletedRegions == CaptureRegions.size())
3956 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003957 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003958 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003959 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003960}
3961
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003962static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3963 OpenMPDirectiveKind CancelRegion,
3964 SourceLocation StartLoc) {
3965 // CancelRegion is only needed for cancel and cancellation_point.
3966 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3967 return false;
3968
3969 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3970 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3971 return false;
3972
3973 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3974 << getOpenMPDirectiveName(CancelRegion);
3975 return true;
3976}
3977
Alexey Bataeve3727102018-04-18 15:57:46 +00003978static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003979 OpenMPDirectiveKind CurrentRegion,
3980 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003981 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003982 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003983 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003984 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3985 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003986 bool NestingProhibited = false;
3987 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003988 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003989 enum {
3990 NoRecommend,
3991 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003992 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003993 ShouldBeInTargetRegion,
3994 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003995 } Recommend = NoRecommend;
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05003996 if (isOpenMPSimdDirective(ParentRegion) &&
3997 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
3998 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
3999 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004000 // OpenMP [2.16, Nesting of Regions]
4001 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004002 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00004003 // An ordered construct with the simd clause is the only OpenMP
4004 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00004005 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00004006 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4007 // message.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004008 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4009 // The only OpenMP constructs that can be encountered during execution of
4010 // a simd region are the atomic construct, the loop construct, the simd
4011 // construct and the ordered construct with the simd clause.
Kelvin Lifd8b5742016-07-01 14:30:25 +00004012 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4013 ? diag::err_omp_prohibited_region_simd
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004014 : diag::warn_omp_nesting_simd)
4015 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
Kelvin Lifd8b5742016-07-01 14:30:25 +00004016 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00004017 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004018 if (ParentRegion == OMPD_atomic) {
4019 // OpenMP [2.16, Nesting of Regions]
4020 // OpenMP constructs may not be nested inside an atomic region.
4021 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4022 return true;
4023 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004024 if (CurrentRegion == OMPD_section) {
4025 // OpenMP [2.7.2, sections Construct, Restrictions]
4026 // Orphaned section directives are prohibited. That is, the section
4027 // directives must appear within the sections construct and must not be
4028 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004029 if (ParentRegion != OMPD_sections &&
4030 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004031 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4032 << (ParentRegion != OMPD_unknown)
4033 << getOpenMPDirectiveName(ParentRegion);
4034 return true;
4035 }
4036 return false;
4037 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00004038 // Allow some constructs (except teams and cancellation constructs) to be
4039 // orphaned (they could be used in functions, called from OpenMP regions
4040 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00004041 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00004042 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4043 CurrentRegion != OMPD_cancellation_point &&
4044 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004045 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00004046 if (CurrentRegion == OMPD_cancellation_point ||
4047 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004048 // OpenMP [2.16, Nesting of Regions]
4049 // A cancellation point construct for which construct-type-clause is
4050 // taskgroup must be nested inside a task construct. A cancellation
4051 // point construct for which construct-type-clause is not taskgroup must
4052 // be closely nested inside an OpenMP construct that matches the type
4053 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00004054 // A cancel construct for which construct-type-clause is taskgroup must be
4055 // nested inside a task construct. A cancel construct for which
4056 // construct-type-clause is not taskgroup must be closely nested inside an
4057 // OpenMP construct that matches the type specified in
4058 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004059 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004060 !((CancelRegion == OMPD_parallel &&
4061 (ParentRegion == OMPD_parallel ||
4062 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00004063 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004064 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004065 ParentRegion == OMPD_target_parallel_for ||
4066 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004067 ParentRegion == OMPD_teams_distribute_parallel_for ||
4068 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004069 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
4070 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00004071 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4072 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00004073 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004074 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00004075 // OpenMP [2.16, Nesting of Regions]
4076 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004077 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00004078 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004079 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004080 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4081 // OpenMP [2.16, Nesting of Regions]
4082 // A critical region may not be nested (closely or otherwise) inside a
4083 // critical region with the same name. Note that this restriction is not
4084 // sufficient to prevent deadlock.
4085 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00004086 bool DeadLock = Stack->hasDirective(
4087 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4088 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00004089 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00004090 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4091 PreviousCriticalLoc = Loc;
4092 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004093 }
4094 return false;
David Majnemer9d168222016-08-05 17:44:54 +00004095 },
4096 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004097 if (DeadLock) {
4098 SemaRef.Diag(StartLoc,
4099 diag::err_omp_prohibited_region_critical_same_name)
4100 << CurrentName.getName();
4101 if (PreviousCriticalLoc.isValid())
4102 SemaRef.Diag(PreviousCriticalLoc,
4103 diag::note_omp_previous_critical_region);
4104 return true;
4105 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004106 } else if (CurrentRegion == OMPD_barrier) {
4107 // OpenMP [2.16, Nesting of Regions]
4108 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004109 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004110 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4111 isOpenMPTaskingDirective(ParentRegion) ||
4112 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004113 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004114 ParentRegion == OMPD_critical ||
4115 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00004116 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00004117 !isOpenMPParallelDirective(CurrentRegion) &&
4118 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004119 // OpenMP [2.16, Nesting of Regions]
4120 // A worksharing region may not be closely nested inside a worksharing,
4121 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004122 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4123 isOpenMPTaskingDirective(ParentRegion) ||
4124 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004125 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004126 ParentRegion == OMPD_critical ||
4127 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004128 Recommend = ShouldBeInParallelRegion;
4129 } else if (CurrentRegion == OMPD_ordered) {
4130 // OpenMP [2.16, Nesting of Regions]
4131 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00004132 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004133 // An ordered region must be closely nested inside a loop region (or
4134 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004135 // OpenMP [2.8.1,simd Construct, Restrictions]
4136 // An ordered construct with the simd clause is the only OpenMP construct
4137 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004138 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004139 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004140 !(isOpenMPSimdDirective(ParentRegion) ||
4141 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004142 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00004143 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004144 // OpenMP [2.16, Nesting of Regions]
4145 // If specified, a teams construct must be contained within a target
4146 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00004147 NestingProhibited =
4148 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4149 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4150 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00004151 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004152 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004153 }
Kelvin Libf594a52016-12-17 05:48:59 +00004154 if (!NestingProhibited &&
4155 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4156 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4157 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004158 // OpenMP [2.16, Nesting of Regions]
4159 // distribute, parallel, parallel sections, parallel workshare, and the
4160 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4161 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004162 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4163 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00004164 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004165 }
David Majnemer9d168222016-08-05 17:44:54 +00004166 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00004167 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004168 // OpenMP 4.5 [2.17 Nesting of Regions]
4169 // The region associated with the distribute construct must be strictly
4170 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00004171 NestingProhibited =
4172 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004173 Recommend = ShouldBeInTeamsRegion;
4174 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004175 if (!NestingProhibited &&
4176 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4177 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4178 // OpenMP 4.5 [2.17 Nesting of Regions]
4179 // If a target, target update, target data, target enter data, or
4180 // target exit data construct is encountered during execution of a
4181 // target region, the behavior is unspecified.
4182 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004183 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00004184 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004185 if (isOpenMPTargetExecutionDirective(K)) {
4186 OffendingRegion = K;
4187 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004188 }
4189 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004190 },
4191 false /* don't skip top directive */);
4192 CloseNesting = false;
4193 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004194 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00004195 if (OrphanSeen) {
4196 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4197 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4198 } else {
4199 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4200 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4201 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4202 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004203 return true;
4204 }
4205 }
4206 return false;
4207}
4208
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004209struct Kind2Unsigned {
4210 using argument_type = OpenMPDirectiveKind;
4211 unsigned operator()(argument_type DK) { return unsigned(DK); }
4212};
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004213static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4214 ArrayRef<OMPClause *> Clauses,
4215 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4216 bool ErrorFound = false;
4217 unsigned NamedModifiersNumber = 0;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004218 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4219 FoundNameModifiers.resize(unsigned(OMPD_unknown) + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004220 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004221 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004222 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4223 // At most one if clause without a directive-name-modifier can appear on
4224 // the directive.
4225 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4226 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004227 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004228 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4229 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4230 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004231 } else if (CurNM != OMPD_unknown) {
4232 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004233 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004234 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004235 FoundNameModifiers[CurNM] = IC;
4236 if (CurNM == OMPD_unknown)
4237 continue;
4238 // Check if the specified name modifier is allowed for the current
4239 // directive.
4240 // At most one if clause with the particular directive-name-modifier can
4241 // appear on the directive.
4242 bool MatchFound = false;
4243 for (auto NM : AllowedNameModifiers) {
4244 if (CurNM == NM) {
4245 MatchFound = true;
4246 break;
4247 }
4248 }
4249 if (!MatchFound) {
4250 S.Diag(IC->getNameModifierLoc(),
4251 diag::err_omp_wrong_if_directive_name_modifier)
4252 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4253 ErrorFound = true;
4254 }
4255 }
4256 }
4257 // If any if clause on the directive includes a directive-name-modifier then
4258 // all if clauses on the directive must include a directive-name-modifier.
4259 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4260 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004261 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004262 diag::err_omp_no_more_if_clause);
4263 } else {
4264 std::string Values;
4265 std::string Sep(", ");
4266 unsigned AllowedCnt = 0;
4267 unsigned TotalAllowedNum =
4268 AllowedNameModifiers.size() - NamedModifiersNumber;
4269 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4270 ++Cnt) {
4271 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4272 if (!FoundNameModifiers[NM]) {
4273 Values += "'";
4274 Values += getOpenMPDirectiveName(NM);
4275 Values += "'";
4276 if (AllowedCnt + 2 == TotalAllowedNum)
4277 Values += " or ";
4278 else if (AllowedCnt + 1 != TotalAllowedNum)
4279 Values += Sep;
4280 ++AllowedCnt;
4281 }
4282 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004283 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004284 diag::err_omp_unnamed_if_clause)
4285 << (TotalAllowedNum > 1) << Values;
4286 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004287 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004288 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4289 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004290 ErrorFound = true;
4291 }
4292 return ErrorFound;
4293}
4294
Alexey Bataev0860db92019-12-19 10:01:10 -05004295static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4296 SourceLocation &ELoc,
4297 SourceRange &ERange,
4298 bool AllowArraySection) {
Alexey Bataeve106f252019-04-01 14:25:31 +00004299 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4300 RefExpr->containsUnexpandedParameterPack())
4301 return std::make_pair(nullptr, true);
4302
4303 // OpenMP [3.1, C/C++]
4304 // A list item is a variable name.
4305 // OpenMP [2.9.3.3, Restrictions, p.1]
4306 // A variable that is part of another variable (as an array or
4307 // structure element) cannot appear in a private clause.
4308 RefExpr = RefExpr->IgnoreParens();
4309 enum {
4310 NoArrayExpr = -1,
4311 ArraySubscript = 0,
4312 OMPArraySection = 1
4313 } IsArrayExpr = NoArrayExpr;
4314 if (AllowArraySection) {
4315 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4316 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4317 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4318 Base = TempASE->getBase()->IgnoreParenImpCasts();
4319 RefExpr = Base;
4320 IsArrayExpr = ArraySubscript;
4321 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4322 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4323 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4324 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4325 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4326 Base = TempASE->getBase()->IgnoreParenImpCasts();
4327 RefExpr = Base;
4328 IsArrayExpr = OMPArraySection;
4329 }
4330 }
4331 ELoc = RefExpr->getExprLoc();
4332 ERange = RefExpr->getSourceRange();
4333 RefExpr = RefExpr->IgnoreParenImpCasts();
4334 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4335 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4336 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4337 (S.getCurrentThisType().isNull() || !ME ||
4338 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4339 !isa<FieldDecl>(ME->getMemberDecl()))) {
4340 if (IsArrayExpr != NoArrayExpr) {
4341 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4342 << ERange;
4343 } else {
4344 S.Diag(ELoc,
4345 AllowArraySection
4346 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4347 : diag::err_omp_expected_var_name_member_expr)
4348 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4349 }
4350 return std::make_pair(nullptr, false);
4351 }
4352 return std::make_pair(
4353 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4354}
4355
4356static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004357 ArrayRef<OMPClause *> Clauses) {
4358 assert(!S.CurContext->isDependentContext() &&
4359 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004360 auto AllocateRange =
4361 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004362 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4363 DeclToCopy;
4364 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4365 return isOpenMPPrivate(C->getClauseKind());
4366 });
4367 for (OMPClause *Cl : PrivateRange) {
4368 MutableArrayRef<Expr *>::iterator I, It, Et;
4369 if (Cl->getClauseKind() == OMPC_private) {
4370 auto *PC = cast<OMPPrivateClause>(Cl);
4371 I = PC->private_copies().begin();
4372 It = PC->varlist_begin();
4373 Et = PC->varlist_end();
4374 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4375 auto *PC = cast<OMPFirstprivateClause>(Cl);
4376 I = PC->private_copies().begin();
4377 It = PC->varlist_begin();
4378 Et = PC->varlist_end();
4379 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4380 auto *PC = cast<OMPLastprivateClause>(Cl);
4381 I = PC->private_copies().begin();
4382 It = PC->varlist_begin();
4383 Et = PC->varlist_end();
4384 } else if (Cl->getClauseKind() == OMPC_linear) {
4385 auto *PC = cast<OMPLinearClause>(Cl);
4386 I = PC->privates().begin();
4387 It = PC->varlist_begin();
4388 Et = PC->varlist_end();
4389 } else if (Cl->getClauseKind() == OMPC_reduction) {
4390 auto *PC = cast<OMPReductionClause>(Cl);
4391 I = PC->privates().begin();
4392 It = PC->varlist_begin();
4393 Et = PC->varlist_end();
4394 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4395 auto *PC = cast<OMPTaskReductionClause>(Cl);
4396 I = PC->privates().begin();
4397 It = PC->varlist_begin();
4398 Et = PC->varlist_end();
4399 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4400 auto *PC = cast<OMPInReductionClause>(Cl);
4401 I = PC->privates().begin();
4402 It = PC->varlist_begin();
4403 Et = PC->varlist_end();
4404 } else {
4405 llvm_unreachable("Expected private clause.");
4406 }
4407 for (Expr *E : llvm::make_range(It, Et)) {
4408 if (!*I) {
4409 ++I;
4410 continue;
4411 }
4412 SourceLocation ELoc;
4413 SourceRange ERange;
4414 Expr *SimpleRefExpr = E;
4415 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4416 /*AllowArraySection=*/true);
4417 DeclToCopy.try_emplace(Res.first,
4418 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4419 ++I;
4420 }
4421 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004422 for (OMPClause *C : AllocateRange) {
4423 auto *AC = cast<OMPAllocateClause>(C);
4424 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4425 getAllocatorKind(S, Stack, AC->getAllocator());
4426 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4427 // For task, taskloop or target directives, allocation requests to memory
4428 // allocators with the trait access set to thread result in unspecified
4429 // behavior.
4430 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4431 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4432 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4433 S.Diag(AC->getAllocator()->getExprLoc(),
4434 diag::warn_omp_allocate_thread_on_task_target_directive)
4435 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004436 }
4437 for (Expr *E : AC->varlists()) {
4438 SourceLocation ELoc;
4439 SourceRange ERange;
4440 Expr *SimpleRefExpr = E;
4441 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4442 ValueDecl *VD = Res.first;
4443 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4444 if (!isOpenMPPrivate(Data.CKind)) {
4445 S.Diag(E->getExprLoc(),
4446 diag::err_omp_expected_private_copy_for_allocate);
4447 continue;
4448 }
4449 VarDecl *PrivateVD = DeclToCopy[VD];
4450 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4451 AllocatorKind, AC->getAllocator()))
4452 continue;
4453 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4454 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004455 }
4456 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004457}
4458
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004459StmtResult Sema::ActOnOpenMPExecutableDirective(
4460 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4461 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4462 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004463 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004464 // First check CancelRegion which is then used in checkNestingOfRegions.
4465 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4466 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004467 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004468 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004469
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004470 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004471 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004472 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004473 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004474 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004475 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4476
4477 // Check default data sharing attributes for referenced variables.
4478 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004479 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4480 Stmt *S = AStmt;
4481 while (--ThisCaptureLevel >= 0)
4482 S = cast<CapturedStmt>(S)->getCapturedStmt();
4483 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004484 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4485 !isOpenMPTaskingDirective(Kind)) {
4486 // Visit subcaptures to generate implicit clauses for captured vars.
4487 auto *CS = cast<CapturedStmt>(AStmt);
4488 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4489 getOpenMPCaptureRegions(CaptureRegions, Kind);
4490 // Ignore outer tasking regions for target directives.
4491 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4492 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4493 DSAChecker.visitSubCaptures(CS);
4494 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004495 if (DSAChecker.isErrorFound())
4496 return StmtError();
4497 // Generate list of implicitly defined firstprivate variables.
4498 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004499
Alexey Bataev88202be2017-07-27 13:20:36 +00004500 SmallVector<Expr *, 4> ImplicitFirstprivates(
4501 DSAChecker.getImplicitFirstprivate().begin(),
4502 DSAChecker.getImplicitFirstprivate().end());
cchene06f3e02019-11-15 13:02:06 -05004503 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4504 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4505 ArrayRef<Expr *> ImplicitMap =
4506 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4507 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4508 }
Alexey Bataev88202be2017-07-27 13:20:36 +00004509 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004510 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004511 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004512 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004513 if (E)
4514 ImplicitFirstprivates.emplace_back(E);
4515 }
4516 }
4517 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004518 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004519 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4520 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004521 ClausesWithImplicit.push_back(Implicit);
4522 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004523 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004524 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004525 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004526 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004527 }
cchene06f3e02019-11-15 13:02:06 -05004528 int ClauseKindCnt = -1;
4529 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4530 ++ClauseKindCnt;
4531 if (ImplicitMap.empty())
4532 continue;
Michael Kruse4304e9d2019-02-19 16:38:20 +00004533 CXXScopeSpec MapperIdScopeSpec;
4534 DeclarationNameInfo MapperId;
cchene06f3e02019-11-15 13:02:06 -05004535 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004536 if (OMPClause *Implicit = ActOnOpenMPMapClause(
cchene06f3e02019-11-15 13:02:06 -05004537 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4538 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4539 ImplicitMap, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004540 ClausesWithImplicit.emplace_back(Implicit);
4541 ErrorFound |=
cchene06f3e02019-11-15 13:02:06 -05004542 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004543 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004544 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004545 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004546 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004547 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004548
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004549 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004550 switch (Kind) {
4551 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004552 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4553 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004554 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004555 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004556 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004557 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4558 VarsWithInheritedDSA);
Alexey Bataevd08c0562019-11-19 12:07:54 -05004559 if (LangOpts.OpenMP >= 50)
4560 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004561 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004562 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004563 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4564 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004565 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004566 case OMPD_for_simd:
4567 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4568 EndLoc, VarsWithInheritedDSA);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05004569 if (LangOpts.OpenMP >= 50)
4570 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004571 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004572 case OMPD_sections:
4573 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4574 EndLoc);
4575 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004576 case OMPD_section:
4577 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004578 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004579 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4580 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004581 case OMPD_single:
4582 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4583 EndLoc);
4584 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004585 case OMPD_master:
4586 assert(ClausesWithImplicit.empty() &&
4587 "No clauses are allowed for 'omp master' directive");
4588 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4589 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004590 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004591 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4592 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004593 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004594 case OMPD_parallel_for:
4595 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4596 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004597 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004598 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004599 case OMPD_parallel_for_simd:
4600 Res = ActOnOpenMPParallelForSimdDirective(
4601 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004602 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevf59614d2019-11-21 10:00:56 -05004603 if (LangOpts.OpenMP >= 50)
4604 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004605 break;
cchen47d60942019-12-05 13:43:48 -05004606 case OMPD_parallel_master:
4607 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
4608 StartLoc, EndLoc);
4609 AllowedNameModifiers.push_back(OMPD_parallel);
4610 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004611 case OMPD_parallel_sections:
4612 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4613 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004614 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004615 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004616 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004617 Res =
4618 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004619 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004620 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004621 case OMPD_taskyield:
4622 assert(ClausesWithImplicit.empty() &&
4623 "No clauses are allowed for 'omp taskyield' directive");
4624 assert(AStmt == nullptr &&
4625 "No associated statement allowed for 'omp taskyield' directive");
4626 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4627 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004628 case OMPD_barrier:
4629 assert(ClausesWithImplicit.empty() &&
4630 "No clauses are allowed for 'omp barrier' directive");
4631 assert(AStmt == nullptr &&
4632 "No associated statement allowed for 'omp barrier' directive");
4633 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4634 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004635 case OMPD_taskwait:
4636 assert(ClausesWithImplicit.empty() &&
4637 "No clauses are allowed for 'omp taskwait' directive");
4638 assert(AStmt == nullptr &&
4639 "No associated statement allowed for 'omp taskwait' directive");
4640 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4641 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004642 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004643 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4644 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004645 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004646 case OMPD_flush:
4647 assert(AStmt == nullptr &&
4648 "No associated statement allowed for 'omp flush' directive");
4649 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4650 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004651 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004652 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4653 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004654 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004655 case OMPD_atomic:
4656 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4657 EndLoc);
4658 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004659 case OMPD_teams:
4660 Res =
4661 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4662 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004663 case OMPD_target:
4664 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4665 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004666 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004667 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004668 case OMPD_target_parallel:
4669 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4670 StartLoc, EndLoc);
4671 AllowedNameModifiers.push_back(OMPD_target);
4672 AllowedNameModifiers.push_back(OMPD_parallel);
4673 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004674 case OMPD_target_parallel_for:
4675 Res = ActOnOpenMPTargetParallelForDirective(
4676 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4677 AllowedNameModifiers.push_back(OMPD_target);
4678 AllowedNameModifiers.push_back(OMPD_parallel);
4679 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004680 case OMPD_cancellation_point:
4681 assert(ClausesWithImplicit.empty() &&
4682 "No clauses are allowed for 'omp cancellation point' directive");
4683 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4684 "cancellation point' directive");
4685 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4686 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004687 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004688 assert(AStmt == nullptr &&
4689 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004690 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4691 CancelRegion);
4692 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004693 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004694 case OMPD_target_data:
4695 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4696 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004697 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004698 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004699 case OMPD_target_enter_data:
4700 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004701 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004702 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4703 break;
Samuel Antao72590762016-01-19 20:04:50 +00004704 case OMPD_target_exit_data:
4705 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004706 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004707 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4708 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004709 case OMPD_taskloop:
4710 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4711 EndLoc, VarsWithInheritedDSA);
4712 AllowedNameModifiers.push_back(OMPD_taskloop);
4713 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004714 case OMPD_taskloop_simd:
4715 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4716 EndLoc, VarsWithInheritedDSA);
4717 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev61205822019-12-04 09:50:21 -05004718 if (LangOpts.OpenMP >= 50)
4719 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004720 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004721 case OMPD_master_taskloop:
4722 Res = ActOnOpenMPMasterTaskLoopDirective(
4723 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4724 AllowedNameModifiers.push_back(OMPD_taskloop);
4725 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004726 case OMPD_master_taskloop_simd:
4727 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4728 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4729 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev853961f2019-12-05 09:50:18 -05004730 if (LangOpts.OpenMP >= 50)
4731 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004732 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004733 case OMPD_parallel_master_taskloop:
4734 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4735 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4736 AllowedNameModifiers.push_back(OMPD_taskloop);
4737 AllowedNameModifiers.push_back(OMPD_parallel);
4738 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004739 case OMPD_parallel_master_taskloop_simd:
4740 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4741 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4742 AllowedNameModifiers.push_back(OMPD_taskloop);
4743 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5c517a62019-12-05 11:31:45 -05004744 if (LangOpts.OpenMP >= 50)
4745 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev14a388f2019-10-25 10:27:13 -04004746 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004747 case OMPD_distribute:
4748 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4749 EndLoc, VarsWithInheritedDSA);
4750 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004751 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004752 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4753 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004754 AllowedNameModifiers.push_back(OMPD_target_update);
4755 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004756 case OMPD_distribute_parallel_for:
4757 Res = ActOnOpenMPDistributeParallelForDirective(
4758 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4759 AllowedNameModifiers.push_back(OMPD_parallel);
4760 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004761 case OMPD_distribute_parallel_for_simd:
4762 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4763 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4764 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev52812f22019-12-05 13:22:15 -05004765 if (LangOpts.OpenMP >= 50)
4766 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4a39add2016-07-05 05:00:15 +00004767 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004768 case OMPD_distribute_simd:
4769 Res = ActOnOpenMPDistributeSimdDirective(
4770 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev779a1802019-12-06 12:21:31 -05004771 if (LangOpts.OpenMP >= 50)
4772 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li787f3fc2016-07-06 04:45:38 +00004773 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004774 case OMPD_target_parallel_for_simd:
4775 Res = ActOnOpenMPTargetParallelForSimdDirective(
4776 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4777 AllowedNameModifiers.push_back(OMPD_target);
4778 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevda17a532019-12-10 11:37:03 -05004779 if (LangOpts.OpenMP >= 50)
4780 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lia579b912016-07-14 02:54:56 +00004781 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004782 case OMPD_target_simd:
4783 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4784 EndLoc, VarsWithInheritedDSA);
4785 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataevef94cd12019-12-10 12:44:45 -05004786 if (LangOpts.OpenMP >= 50)
4787 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li986330c2016-07-20 22:57:10 +00004788 break;
Kelvin Li02532872016-08-05 14:37:37 +00004789 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004790 Res = ActOnOpenMPTeamsDistributeDirective(
4791 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004792 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004793 case OMPD_teams_distribute_simd:
4794 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4795 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev7b774b72019-12-11 11:20:47 -05004796 if (LangOpts.OpenMP >= 50)
4797 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4e325f72016-10-25 12:50:55 +00004798 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004799 case OMPD_teams_distribute_parallel_for_simd:
4800 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4801 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4802 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev0b978942019-12-11 15:26:38 -05004803 if (LangOpts.OpenMP >= 50)
4804 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li579e41c2016-11-30 23:51:03 +00004805 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004806 case OMPD_teams_distribute_parallel_for:
4807 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4808 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4809 AllowedNameModifiers.push_back(OMPD_parallel);
4810 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004811 case OMPD_target_teams:
4812 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4813 EndLoc);
4814 AllowedNameModifiers.push_back(OMPD_target);
4815 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004816 case OMPD_target_teams_distribute:
4817 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4818 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4819 AllowedNameModifiers.push_back(OMPD_target);
4820 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004821 case OMPD_target_teams_distribute_parallel_for:
4822 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4823 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4824 AllowedNameModifiers.push_back(OMPD_target);
4825 AllowedNameModifiers.push_back(OMPD_parallel);
4826 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004827 case OMPD_target_teams_distribute_parallel_for_simd:
4828 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4829 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4830 AllowedNameModifiers.push_back(OMPD_target);
4831 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevfd0c91b2019-12-16 10:27:39 -05004832 if (LangOpts.OpenMP >= 50)
4833 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li1851df52017-01-03 05:23:48 +00004834 break;
Kelvin Lida681182017-01-10 18:08:18 +00004835 case OMPD_target_teams_distribute_simd:
4836 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4837 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4838 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev411e81a2019-12-16 11:16:46 -05004839 if (LangOpts.OpenMP >= 50)
4840 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lida681182017-01-10 18:08:18 +00004841 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004842 case OMPD_declare_target:
4843 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004844 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004845 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004846 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004847 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004848 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004849 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004850 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004851 llvm_unreachable("OpenMP Directive is not allowed");
4852 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004853 llvm_unreachable("Unknown OpenMP directive");
4854 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004855
Roman Lebedevb5700602019-03-20 16:32:36 +00004856 ErrorFound = Res.isInvalid() || ErrorFound;
4857
Alexey Bataev412254a2019-05-09 18:44:53 +00004858 // Check variables in the clauses if default(none) was specified.
4859 if (DSAStack->getDefaultDSA() == DSA_none) {
4860 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4861 for (OMPClause *C : Clauses) {
4862 switch (C->getClauseKind()) {
4863 case OMPC_num_threads:
4864 case OMPC_dist_schedule:
4865 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004866 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004867 break;
4868 continue;
4869 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004870 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004871 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4872 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004873 if (isOpenMPParallelDirective(Kind) &&
4874 isOpenMPTaskLoopDirective(Kind) &&
4875 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4876 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004877 continue;
4878 case OMPC_schedule:
4879 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004880 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004881 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004882 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004883 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004884 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004885 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004886 break;
4887 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004888 case OMPC_ordered:
4889 case OMPC_device:
4890 case OMPC_num_teams:
4891 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004892 case OMPC_hint:
4893 case OMPC_collapse:
4894 case OMPC_safelen:
4895 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004896 case OMPC_default:
4897 case OMPC_proc_bind:
4898 case OMPC_private:
4899 case OMPC_firstprivate:
4900 case OMPC_lastprivate:
4901 case OMPC_shared:
4902 case OMPC_reduction:
4903 case OMPC_task_reduction:
4904 case OMPC_in_reduction:
4905 case OMPC_linear:
4906 case OMPC_aligned:
4907 case OMPC_copyin:
4908 case OMPC_copyprivate:
4909 case OMPC_nowait:
4910 case OMPC_untied:
4911 case OMPC_mergeable:
4912 case OMPC_allocate:
4913 case OMPC_read:
4914 case OMPC_write:
4915 case OMPC_update:
4916 case OMPC_capture:
4917 case OMPC_seq_cst:
4918 case OMPC_depend:
4919 case OMPC_threads:
4920 case OMPC_simd:
4921 case OMPC_map:
4922 case OMPC_nogroup:
4923 case OMPC_defaultmap:
4924 case OMPC_to:
4925 case OMPC_from:
4926 case OMPC_use_device_ptr:
4927 case OMPC_is_device_ptr:
Alexey Bataevb6e70842019-12-16 15:54:17 -05004928 case OMPC_nontemporal:
Alexey Bataev412254a2019-05-09 18:44:53 +00004929 continue;
4930 case OMPC_allocator:
4931 case OMPC_flush:
4932 case OMPC_threadprivate:
4933 case OMPC_uniform:
4934 case OMPC_unknown:
4935 case OMPC_unified_address:
4936 case OMPC_unified_shared_memory:
4937 case OMPC_reverse_offload:
4938 case OMPC_dynamic_allocators:
4939 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004940 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004941 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004942 llvm_unreachable("Unexpected clause");
4943 }
4944 for (Stmt *CC : C->children()) {
4945 if (CC)
4946 DSAChecker.Visit(CC);
4947 }
4948 }
4949 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4950 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4951 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004952 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004953 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4954 continue;
4955 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05004956 if (DSAStack->getDefaultDSA() == DSA_none) {
4957 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4958 << P.first << P.second->getSourceRange();
4959 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4960 } else if (getLangOpts().OpenMP >= 50) {
4961 Diag(P.second->getExprLoc(),
4962 diag::err_omp_defaultmap_no_attr_for_variable)
4963 << P.first << P.second->getSourceRange();
4964 Diag(DSAStack->getDefaultDSALocation(),
4965 diag::note_omp_defaultmap_attr_none);
4966 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00004967 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004968
4969 if (!AllowedNameModifiers.empty())
4970 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4971 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004972
Alexey Bataeved09d242014-05-28 05:53:51 +00004973 if (ErrorFound)
4974 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004975
4976 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4977 Res.getAs<OMPExecutableDirective>()
4978 ->getStructuredBlock()
4979 ->setIsOMPStructuredBlock(true);
4980 }
4981
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004982 if (!CurContext->isDependentContext() &&
4983 isOpenMPTargetExecutionDirective(Kind) &&
4984 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4985 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4986 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4987 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4988 // Register target to DSA Stack.
4989 DSAStack->addTargetDirLocation(StartLoc);
4990 }
4991
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004992 return Res;
4993}
4994
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004995Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4996 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004997 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004998 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4999 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005000 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00005001 assert(Linears.size() == LinModifiers.size());
5002 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00005003 if (!DG || DG.get().isNull())
5004 return DeclGroupPtrTy();
5005
Alexey Bataevd158cf62019-09-13 20:18:17 +00005006 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005007 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005008 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5009 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005010 return DG;
5011 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005012 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00005013 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5014 ADecl = FTD->getTemplatedDecl();
5015
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005016 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5017 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005018 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005019 return DeclGroupPtrTy();
5020 }
5021
Alexey Bataev2af33e32016-04-07 12:45:37 +00005022 // OpenMP [2.8.2, declare simd construct, Description]
5023 // The parameter of the simdlen clause must be a constant positive integer
5024 // expression.
5025 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005026 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00005027 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005028 // OpenMP [2.8.2, declare simd construct, Description]
5029 // The special this pointer can be used as if was one of the arguments to the
5030 // function in any of the linear, aligned, or uniform clauses.
5031 // The uniform clause declares one or more arguments to have an invariant
5032 // value for all concurrent invocations of the function in the execution of a
5033 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00005034 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5035 const Expr *UniformedLinearThis = nullptr;
5036 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005037 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005038 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5039 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005040 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5041 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00005042 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00005043 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005044 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005045 }
5046 if (isa<CXXThisExpr>(E)) {
5047 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005048 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005049 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005050 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5051 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00005052 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00005053 // OpenMP [2.8.2, declare simd construct, Description]
5054 // The aligned clause declares that the object to which each list item points
5055 // is aligned to the number of bytes expressed in the optional parameter of
5056 // the aligned clause.
5057 // The special this pointer can be used as if was one of the arguments to the
5058 // function in any of the linear, aligned, or uniform clauses.
5059 // The type of list items appearing in the aligned clause must be array,
5060 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00005061 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5062 const Expr *AlignedThis = nullptr;
5063 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005064 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005065 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5066 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5067 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005068 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5069 FD->getParamDecl(PVD->getFunctionScopeIndex())
5070 ->getCanonicalDecl() == CanonPVD) {
5071 // OpenMP [2.8.1, simd construct, Restrictions]
5072 // A list-item cannot appear in more than one aligned clause.
5073 if (AlignedArgs.count(CanonPVD) > 0) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005074 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5075 << 1 << getOpenMPClauseName(OMPC_aligned)
5076 << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005077 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5078 diag::note_omp_explicit_dsa)
5079 << getOpenMPClauseName(OMPC_aligned);
5080 continue;
5081 }
5082 AlignedArgs[CanonPVD] = E;
5083 QualType QTy = PVD->getType()
5084 .getNonReferenceType()
5085 .getUnqualifiedType()
5086 .getCanonicalType();
5087 const Type *Ty = QTy.getTypePtrOrNull();
5088 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5089 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5090 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5091 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5092 }
5093 continue;
5094 }
5095 }
5096 if (isa<CXXThisExpr>(E)) {
5097 if (AlignedThis) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005098 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5099 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005100 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5101 << getOpenMPClauseName(OMPC_aligned);
5102 }
5103 AlignedThis = E;
5104 continue;
5105 }
5106 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5107 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5108 }
5109 // The optional parameter of the aligned clause, alignment, must be a constant
5110 // positive integer expression. If no optional parameter is specified,
5111 // implementation-defined default alignments for SIMD instructions on the
5112 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005113 SmallVector<const Expr *, 4> NewAligns;
5114 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005115 ExprResult Align;
5116 if (E)
5117 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5118 NewAligns.push_back(Align.get());
5119 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005120 // OpenMP [2.8.2, declare simd construct, Description]
5121 // The linear clause declares one or more list items to be private to a SIMD
5122 // lane and to have a linear relationship with respect to the iteration space
5123 // of a loop.
5124 // The special this pointer can be used as if was one of the arguments to the
5125 // function in any of the linear, aligned, or uniform clauses.
5126 // When a linear-step expression is specified in a linear clause it must be
5127 // either a constant integer expression or an integer-typed parameter that is
5128 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005129 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005130 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5131 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005132 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005133 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5134 ++MI;
5135 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005136 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5137 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5138 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005139 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5140 FD->getParamDecl(PVD->getFunctionScopeIndex())
5141 ->getCanonicalDecl() == CanonPVD) {
5142 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5143 // A list-item cannot appear in more than one linear clause.
5144 if (LinearArgs.count(CanonPVD) > 0) {
5145 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5146 << getOpenMPClauseName(OMPC_linear)
5147 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5148 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5149 diag::note_omp_explicit_dsa)
5150 << getOpenMPClauseName(OMPC_linear);
5151 continue;
5152 }
5153 // Each argument can appear in at most one uniform or linear clause.
5154 if (UniformedArgs.count(CanonPVD) > 0) {
5155 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5156 << getOpenMPClauseName(OMPC_linear)
5157 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5158 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5159 diag::note_omp_explicit_dsa)
5160 << getOpenMPClauseName(OMPC_uniform);
5161 continue;
5162 }
5163 LinearArgs[CanonPVD] = E;
5164 if (E->isValueDependent() || E->isTypeDependent() ||
5165 E->isInstantiationDependent() ||
5166 E->containsUnexpandedParameterPack())
5167 continue;
5168 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5169 PVD->getOriginalType());
5170 continue;
5171 }
5172 }
5173 if (isa<CXXThisExpr>(E)) {
5174 if (UniformedLinearThis) {
5175 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5176 << getOpenMPClauseName(OMPC_linear)
5177 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5178 << E->getSourceRange();
5179 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5180 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5181 : OMPC_linear);
5182 continue;
5183 }
5184 UniformedLinearThis = E;
5185 if (E->isValueDependent() || E->isTypeDependent() ||
5186 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5187 continue;
5188 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5189 E->getType());
5190 continue;
5191 }
5192 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5193 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5194 }
5195 Expr *Step = nullptr;
5196 Expr *NewStep = nullptr;
5197 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005198 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005199 // Skip the same step expression, it was checked already.
5200 if (Step == E || !E) {
5201 NewSteps.push_back(E ? NewStep : nullptr);
5202 continue;
5203 }
5204 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005205 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5206 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5207 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005208 if (UniformedArgs.count(CanonPVD) == 0) {
5209 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5210 << Step->getSourceRange();
5211 } else if (E->isValueDependent() || E->isTypeDependent() ||
5212 E->isInstantiationDependent() ||
5213 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005214 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005215 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005216 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005217 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5218 << Step->getSourceRange();
5219 }
5220 continue;
5221 }
5222 NewStep = Step;
5223 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5224 !Step->isInstantiationDependent() &&
5225 !Step->containsUnexpandedParameterPack()) {
5226 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5227 .get();
5228 if (NewStep)
5229 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5230 }
5231 NewSteps.push_back(NewStep);
5232 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005233 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5234 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005235 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005236 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5237 const_cast<Expr **>(Linears.data()), Linears.size(),
5238 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5239 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005240 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005241 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005242}
5243
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005244static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5245 QualType NewType) {
5246 assert(NewType->isFunctionProtoType() &&
5247 "Expected function type with prototype.");
5248 assert(FD->getType()->isFunctionNoProtoType() &&
5249 "Expected function with type with no prototype.");
5250 assert(FDWithProto->getType()->isFunctionProtoType() &&
5251 "Expected function with prototype.");
5252 // Synthesize parameters with the same types.
5253 FD->setType(NewType);
5254 SmallVector<ParmVarDecl *, 16> Params;
5255 for (const ParmVarDecl *P : FDWithProto->parameters()) {
5256 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5257 SourceLocation(), nullptr, P->getType(),
5258 /*TInfo=*/nullptr, SC_None, nullptr);
5259 Param->setScopeInfo(0, Params.size());
5260 Param->setImplicit();
5261 Params.push_back(Param);
5262 }
5263
5264 FD->setParams(Params);
5265}
5266
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005267Optional<std::pair<FunctionDecl *, Expr *>>
5268Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5269 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005270 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005271 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005272
5273 const int VariantId = 1;
5274 // Must be applied only to single decl.
5275 if (!DG.get().isSingleDecl()) {
5276 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5277 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005278 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005279 }
5280 Decl *ADecl = DG.get().getSingleDecl();
5281 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5282 ADecl = FTD->getTemplatedDecl();
5283
5284 // Decl must be a function.
5285 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5286 if (!FD) {
5287 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5288 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005289 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005290 }
5291
5292 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5293 return FD->hasAttrs() &&
5294 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5295 FD->hasAttr<TargetAttr>());
5296 };
5297 // OpenMP is not compatible with CPU-specific attributes.
5298 if (HasMultiVersionAttributes(FD)) {
5299 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5300 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005301 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005302 }
5303
5304 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005305 if (FD->isUsed(false))
5306 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005307 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005308
5309 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005310 const FunctionDecl *Definition;
5311 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5312 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005313 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5314 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005315
5316 // The VariantRef must point to function.
5317 if (!VariantRef) {
5318 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005319 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005320 }
5321
5322 // Do not check templates, wait until instantiation.
5323 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5324 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005325 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5326 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005327
5328 // Convert VariantRef expression to the type of the original function to
5329 // resolve possible conflicts.
5330 ExprResult VariantRefCast;
5331 if (LangOpts.CPlusPlus) {
5332 QualType FnPtrType;
5333 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5334 if (Method && !Method->isStatic()) {
5335 const Type *ClassType =
5336 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5337 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5338 ExprResult ER;
5339 {
5340 // Build adrr_of unary op to correctly handle type checks for member
5341 // functions.
5342 Sema::TentativeAnalysisScope Trap(*this);
5343 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5344 VariantRef);
5345 }
5346 if (!ER.isUsable()) {
5347 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5348 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005349 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005350 }
5351 VariantRef = ER.get();
5352 } else {
5353 FnPtrType = Context.getPointerType(FD->getType());
5354 }
5355 ImplicitConversionSequence ICS =
5356 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5357 /*SuppressUserConversions=*/false,
5358 /*AllowExplicit=*/false,
5359 /*InOverloadResolution=*/false,
5360 /*CStyle=*/false,
5361 /*AllowObjCWritebackConversion=*/false);
5362 if (ICS.isFailure()) {
5363 Diag(VariantRef->getExprLoc(),
5364 diag::err_omp_declare_variant_incompat_types)
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005365 << VariantRef->getType()
5366 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
5367 << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005368 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005369 }
5370 VariantRefCast = PerformImplicitConversion(
5371 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5372 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005373 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005374 // Drop previously built artificial addr_of unary op for member functions.
5375 if (Method && !Method->isStatic()) {
5376 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5377 if (auto *UO = dyn_cast<UnaryOperator>(
5378 PossibleAddrOfVariantRef->IgnoreImplicit()))
5379 VariantRefCast = UO->getSubExpr();
5380 }
5381 } else {
5382 VariantRefCast = VariantRef;
5383 }
5384
5385 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5386 if (!ER.isUsable() ||
5387 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5388 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5389 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005390 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005391 }
5392
5393 // The VariantRef must point to function.
5394 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5395 if (!DRE) {
5396 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5397 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005398 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005399 }
5400 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5401 if (!NewFD) {
5402 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5403 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005404 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005405 }
5406
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005407 // Check if function types are compatible in C.
5408 if (!LangOpts.CPlusPlus) {
5409 QualType NewType =
5410 Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
5411 if (NewType.isNull()) {
5412 Diag(VariantRef->getExprLoc(),
5413 diag::err_omp_declare_variant_incompat_types)
5414 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
5415 return None;
5416 }
5417 if (NewType->isFunctionProtoType()) {
5418 if (FD->getType()->isFunctionNoProtoType())
5419 setPrototype(*this, FD, NewFD, NewType);
5420 else if (NewFD->getType()->isFunctionNoProtoType())
5421 setPrototype(*this, NewFD, FD, NewType);
5422 }
5423 }
5424
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005425 // Check if variant function is not marked with declare variant directive.
5426 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5427 Diag(VariantRef->getExprLoc(),
5428 diag::warn_omp_declare_variant_marked_as_declare_variant)
5429 << VariantRef->getSourceRange();
5430 SourceRange SR =
5431 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5432 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005433 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005434 }
5435
Alexey Bataevd158cf62019-09-13 20:18:17 +00005436 enum DoesntSupport {
5437 VirtFuncs = 1,
5438 Constructors = 3,
5439 Destructors = 4,
5440 DeletedFuncs = 5,
5441 DefaultedFuncs = 6,
5442 ConstexprFuncs = 7,
5443 ConstevalFuncs = 8,
5444 };
5445 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5446 if (CXXFD->isVirtual()) {
5447 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5448 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005449 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005450 }
5451
5452 if (isa<CXXConstructorDecl>(FD)) {
5453 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5454 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005455 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005456 }
5457
5458 if (isa<CXXDestructorDecl>(FD)) {
5459 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5460 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005461 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005462 }
5463 }
5464
5465 if (FD->isDeleted()) {
5466 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5467 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005468 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005469 }
5470
5471 if (FD->isDefaulted()) {
5472 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5473 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005474 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005475 }
5476
5477 if (FD->isConstexpr()) {
5478 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5479 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005480 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005481 }
5482
5483 // Check general compatibility.
5484 if (areMultiversionVariantFunctionsCompatible(
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005485 FD, NewFD, PartialDiagnostic::NullDiagnostic(),
5486 PartialDiagnosticAt(SourceLocation(),
5487 PartialDiagnostic::NullDiagnostic()),
Alexey Bataevd158cf62019-09-13 20:18:17 +00005488 PartialDiagnosticAt(
5489 VariantRef->getExprLoc(),
5490 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5491 PartialDiagnosticAt(VariantRef->getExprLoc(),
5492 PDiag(diag::err_omp_declare_variant_diff)
5493 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005494 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5495 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005496 return None;
5497 return std::make_pair(FD, cast<Expr>(DRE));
5498}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005499
Alexey Bataev9ff34742019-09-25 19:43:37 +00005500void Sema::ActOnOpenMPDeclareVariantDirective(
5501 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005502 ArrayRef<OMPCtxSelectorData> Data) {
5503 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005504 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005505 SmallVector<Expr *, 4> CtxScores;
5506 SmallVector<unsigned, 4> CtxSets;
5507 SmallVector<unsigned, 4> Ctxs;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005508 SmallVector<StringRef, 4> ImplVendors, DeviceKinds;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005509 bool IsError = false;
5510 for (const OMPCtxSelectorData &D : Data) {
5511 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5512 OpenMPContextSelectorKind Ctx = D.Ctx;
5513 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5514 return;
5515 Expr *Score = nullptr;
5516 if (D.Score.isUsable()) {
5517 Score = D.Score.get();
5518 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5519 !Score->isInstantiationDependent() &&
5520 !Score->containsUnexpandedParameterPack()) {
5521 Score =
5522 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5523 .get();
5524 if (Score)
5525 Score = VerifyIntegerConstantExpression(Score).get();
5526 }
5527 } else {
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005528 // OpenMP 5.0, 2.3.3 Matching and Scoring Context Selectors.
5529 // The kind, arch, and isa selectors are given the values 2^l, 2^(l+1) and
5530 // 2^(l+2), respectively, where l is the number of traits in the construct
5531 // set.
5532 // TODO: implement correct logic for isa and arch traits.
5533 // TODO: take the construct context set into account when it is
5534 // implemented.
5535 int L = 0; // Currently set the number of traits in construct set to 0,
5536 // since the construct trait set in not supported yet.
5537 if (CtxSet == OMP_CTX_SET_device && Ctx == OMP_CTX_kind)
5538 Score = ActOnIntegerConstant(SourceLocation(), std::pow(2, L)).get();
5539 else
5540 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005541 }
Alexey Bataev5459a902019-11-22 11:42:08 -05005542 switch (Ctx) {
5543 case OMP_CTX_vendor:
5544 assert(CtxSet == OMP_CTX_SET_implementation &&
5545 "Expected implementation context selector set.");
5546 ImplVendors.append(D.Names.begin(), D.Names.end());
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005547 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005548 case OMP_CTX_kind:
5549 assert(CtxSet == OMP_CTX_SET_device &&
5550 "Expected device context selector set.");
5551 DeviceKinds.append(D.Names.begin(), D.Names.end());
Alexey Bataevfde11e92019-11-07 11:03:10 -05005552 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005553 case OMP_CTX_unknown:
5554 llvm_unreachable("Unknown context selector kind.");
Alexey Bataevfde11e92019-11-07 11:03:10 -05005555 }
5556 IsError = IsError || !Score;
5557 CtxSets.push_back(CtxSet);
5558 Ctxs.push_back(Ctx);
5559 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005560 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005561 if (!IsError) {
5562 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5563 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5564 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005565 ImplVendors.begin(), ImplVendors.size(), DeviceKinds.begin(),
5566 DeviceKinds.size(), SR);
Alexey Bataevfde11e92019-11-07 11:03:10 -05005567 FD->addAttr(NewAttr);
5568 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005569}
5570
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005571void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5572 FunctionDecl *Func,
5573 bool MightBeOdrUse) {
5574 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5575
5576 if (!Func->isDependentContext() && Func->hasAttrs()) {
5577 for (OMPDeclareVariantAttr *A :
5578 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5579 // TODO: add checks for active OpenMP context where possible.
5580 Expr *VariantRef = A->getVariantFuncRef();
Alexey Bataevf17a1d82019-12-02 14:15:38 -05005581 auto *DRE = cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005582 auto *F = cast<FunctionDecl>(DRE->getDecl());
5583 if (!F->isDefined() && F->isTemplateInstantiation())
5584 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5585 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5586 }
5587 }
5588}
5589
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005590StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5591 Stmt *AStmt,
5592 SourceLocation StartLoc,
5593 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005594 if (!AStmt)
5595 return StmtError();
5596
Alexey Bataeve3727102018-04-18 15:57:46 +00005597 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005598 // 1.2.2 OpenMP Language Terminology
5599 // Structured block - An executable statement with a single entry at the
5600 // top and a single exit at the bottom.
5601 // The point of exit cannot be a branch out of the structured block.
5602 // longjmp() and throw() must not violate the entry/exit criteria.
5603 CS->getCapturedDecl()->setNothrow();
5604
Reid Kleckner87a31802018-03-12 21:43:02 +00005605 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005606
Alexey Bataev25e5b442015-09-15 12:52:43 +00005607 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5608 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005609}
5610
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005611namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005612/// Iteration space of a single for loop.
5613struct LoopIterationSpace final {
5614 /// True if the condition operator is the strict compare operator (<, > or
5615 /// !=).
5616 bool IsStrictCompare = false;
5617 /// Condition of the loop.
5618 Expr *PreCond = nullptr;
5619 /// This expression calculates the number of iterations in the loop.
5620 /// It is always possible to calculate it before starting the loop.
5621 Expr *NumIterations = nullptr;
5622 /// The loop counter variable.
5623 Expr *CounterVar = nullptr;
5624 /// Private loop counter variable.
5625 Expr *PrivateCounterVar = nullptr;
5626 /// This is initializer for the initial value of #CounterVar.
5627 Expr *CounterInit = nullptr;
5628 /// This is step for the #CounterVar used to generate its update:
5629 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5630 Expr *CounterStep = nullptr;
5631 /// Should step be subtracted?
5632 bool Subtract = false;
5633 /// Source range of the loop init.
5634 SourceRange InitSrcRange;
5635 /// Source range of the loop condition.
5636 SourceRange CondSrcRange;
5637 /// Source range of the loop increment.
5638 SourceRange IncSrcRange;
5639 /// Minimum value that can have the loop control variable. Used to support
5640 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5641 /// since only such variables can be used in non-loop invariant expressions.
5642 Expr *MinValue = nullptr;
5643 /// Maximum value that can have the loop control variable. Used to support
5644 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5645 /// since only such variables can be used in non-loop invariant expressions.
5646 Expr *MaxValue = nullptr;
5647 /// true, if the lower bound depends on the outer loop control var.
5648 bool IsNonRectangularLB = false;
5649 /// true, if the upper bound depends on the outer loop control var.
5650 bool IsNonRectangularUB = false;
5651 /// Index of the loop this loop depends on and forms non-rectangular loop
5652 /// nest.
5653 unsigned LoopDependentIdx = 0;
5654 /// Final condition for the non-rectangular loop nest support. It is used to
5655 /// check that the number of iterations for this particular counter must be
5656 /// finished.
5657 Expr *FinalCondition = nullptr;
5658};
5659
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005660/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005661/// extracting iteration space of each loop in the loop nest, that will be used
5662/// for IR generation.
5663class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005664 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005665 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005666 /// Data-sharing stack.
5667 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005668 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005669 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005670 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005671 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005672 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005673 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005674 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005675 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005676 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005677 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005678 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005679 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005680 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005681 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005682 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005683 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005684 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005685 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005686 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005687 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005688 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005689 /// Var < UB
5690 /// Var <= UB
5691 /// UB > Var
5692 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005693 /// This will have no value when the condition is !=
5694 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005695 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005696 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005697 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005698 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005699 /// The outer loop counter this loop depends on (if any).
5700 const ValueDecl *DepDecl = nullptr;
5701 /// Contains number of loop (starts from 1) on which loop counter init
5702 /// expression of this loop depends on.
5703 Optional<unsigned> InitDependOnLC;
5704 /// Contains number of loop (starts from 1) on which loop counter condition
5705 /// expression of this loop depends on.
5706 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005707 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005708 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005709 /// Original condition required for checking of the exit condition for
5710 /// non-rectangular loop.
5711 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005712
5713public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005714 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5715 SourceLocation DefaultLoc)
5716 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5717 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005718 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005719 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005720 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005721 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005722 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005723 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005724 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005725 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005726 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005727 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005728 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005729 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005730 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005731 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005732 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005733 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005734 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005735 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005736 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005737 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005738 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005739 /// True, if the compare operator is strict (<, > or !=).
5740 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005741 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005742 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005743 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005744 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005745 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005746 Expr *
5747 buildPreCond(Scope *S, Expr *Cond,
5748 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005749 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005750 DeclRefExpr *
5751 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5752 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005753 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005754 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005755 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005756 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005757 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005758 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005759 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005760 /// Build loop data with counter value for depend clauses in ordered
5761 /// directives.
5762 Expr *
5763 buildOrderedLoopData(Scope *S, Expr *Counter,
5764 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5765 SourceLocation Loc, Expr *Inc = nullptr,
5766 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005767 /// Builds the minimum value for the loop counter.
5768 std::pair<Expr *, Expr *> buildMinMaxValues(
5769 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5770 /// Builds final condition for the non-rectangular loops.
5771 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005772 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005773 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005774 /// Returns true if the initializer forms non-rectangular loop.
5775 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5776 /// Returns true if the condition forms non-rectangular loop.
5777 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5778 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5779 unsigned getLoopDependentIdx() const {
5780 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5781 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005782
5783private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005784 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005785 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005786 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005787 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005788 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5789 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005790 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005791 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5792 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005793 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005794 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005795};
5796
Alexey Bataeve3727102018-04-18 15:57:46 +00005797bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005798 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005799 assert(!LB && !UB && !Step);
5800 return false;
5801 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005802 return LCDecl->getType()->isDependentType() ||
5803 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5804 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005805}
5806
Alexey Bataeve3727102018-04-18 15:57:46 +00005807bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005808 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005809 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005810 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005811 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005812 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005813 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005814 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005815 LCDecl = getCanonicalDecl(NewLCDecl);
5816 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005817 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5818 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005819 if ((Ctor->isCopyOrMoveConstructor() ||
5820 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5821 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005822 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005823 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005824 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005825 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005826 return false;
5827}
5828
Alexey Bataev316ccf62019-01-29 18:51:58 +00005829bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5830 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005831 bool StrictOp, SourceRange SR,
5832 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005833 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005834 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5835 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005836 if (!NewUB)
5837 return true;
5838 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005839 if (LessOp)
5840 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005841 TestIsStrictOp = StrictOp;
5842 ConditionSrcRange = SR;
5843 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005844 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005845 return false;
5846}
5847
Alexey Bataeve3727102018-04-18 15:57:46 +00005848bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005849 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005850 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005851 if (!NewStep)
5852 return true;
5853 if (!NewStep->isValueDependent()) {
5854 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005855 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005856 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5857 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005858 if (Val.isInvalid())
5859 return true;
5860 NewStep = Val.get();
5861
5862 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5863 // If test-expr is of form var relational-op b and relational-op is < or
5864 // <= then incr-expr must cause var to increase on each iteration of the
5865 // loop. If test-expr is of form var relational-op b and relational-op is
5866 // > or >= then incr-expr must cause var to decrease on each iteration of
5867 // the loop.
5868 // If test-expr is of form b relational-op var and relational-op is < or
5869 // <= then incr-expr must cause var to decrease on each iteration of the
5870 // loop. If test-expr is of form b relational-op var and relational-op is
5871 // > or >= then incr-expr must cause var to increase on each iteration of
5872 // the loop.
5873 llvm::APSInt Result;
5874 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5875 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5876 bool IsConstNeg =
5877 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005878 bool IsConstPos =
5879 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005880 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005881
5882 // != with increment is treated as <; != with decrement is treated as >
5883 if (!TestIsLessOp.hasValue())
5884 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005885 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005886 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005887 (IsConstNeg || (IsUnsigned && Subtract)) :
5888 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005889 SemaRef.Diag(NewStep->getExprLoc(),
5890 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005891 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005892 SemaRef.Diag(ConditionLoc,
5893 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005894 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005895 return true;
5896 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005897 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005898 NewStep =
5899 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5900 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005901 Subtract = !Subtract;
5902 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005903 }
5904
5905 Step = NewStep;
5906 SubtractStep = Subtract;
5907 return false;
5908}
5909
Alexey Bataev622af1d2019-04-24 19:58:30 +00005910namespace {
5911/// Checker for the non-rectangular loops. Checks if the initializer or
5912/// condition expression references loop counter variable.
5913class LoopCounterRefChecker final
5914 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5915 Sema &SemaRef;
5916 DSAStackTy &Stack;
5917 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005918 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005919 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005920 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005921 unsigned BaseLoopId = 0;
5922 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5923 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5924 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5925 << (IsInitializer ? 0 : 1);
5926 return false;
5927 }
5928 const auto &&Data = Stack.isLoopControlVariable(VD);
5929 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5930 // The type of the loop iterator on which we depend may not have a random
5931 // access iterator type.
5932 if (Data.first && VD->getType()->isRecordType()) {
5933 SmallString<128> Name;
5934 llvm::raw_svector_ostream OS(Name);
5935 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5936 /*Qualified=*/true);
5937 SemaRef.Diag(E->getExprLoc(),
5938 diag::err_omp_wrong_dependency_iterator_type)
5939 << OS.str();
5940 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5941 return false;
5942 }
5943 if (Data.first &&
5944 (DepDecl || (PrevDepDecl &&
5945 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5946 if (!DepDecl && PrevDepDecl)
5947 DepDecl = PrevDepDecl;
5948 SmallString<128> Name;
5949 llvm::raw_svector_ostream OS(Name);
5950 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5951 /*Qualified=*/true);
5952 SemaRef.Diag(E->getExprLoc(),
5953 diag::err_omp_invariant_or_linear_dependency)
5954 << OS.str();
5955 return false;
5956 }
5957 if (Data.first) {
5958 DepDecl = VD;
5959 BaseLoopId = Data.first;
5960 }
5961 return Data.first;
5962 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005963
5964public:
5965 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5966 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005967 if (isa<VarDecl>(VD))
5968 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005969 return false;
5970 }
5971 bool VisitMemberExpr(const MemberExpr *E) {
5972 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5973 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005974 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5975 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005976 }
5977 return false;
5978 }
5979 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005980 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005981 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005982 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005983 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005984 }
5985 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005986 const ValueDecl *CurLCDecl, bool IsInitializer,
5987 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005988 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005989 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5990 unsigned getBaseLoopId() const {
5991 assert(CurLCDecl && "Expected loop dependency.");
5992 return BaseLoopId;
5993 }
5994 const ValueDecl *getDepDecl() const {
5995 assert(CurLCDecl && "Expected loop dependency.");
5996 return DepDecl;
5997 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005998};
5999} // namespace
6000
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006001Optional<unsigned>
6002OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6003 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00006004 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006005 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6006 DepDecl);
6007 if (LoopStmtChecker.Visit(S)) {
6008 DepDecl = LoopStmtChecker.getDepDecl();
6009 return LoopStmtChecker.getBaseLoopId();
6010 }
6011 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006012}
6013
Alexey Bataeve3727102018-04-18 15:57:46 +00006014bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006015 // Check init-expr for canonical loop form and save loop counter
6016 // variable - #Var and its initialization value - #LB.
6017 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6018 // var = lb
6019 // integer-type var = lb
6020 // random-access-iterator-type var = lb
6021 // pointer-type var = lb
6022 //
6023 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00006024 if (EmitDiags) {
6025 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6026 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006027 return true;
6028 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006029 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6030 if (!ExprTemp->cleanupsHaveSideEffects())
6031 S = ExprTemp->getSubExpr();
6032
Alexander Musmana5f070a2014-10-01 06:03:56 +00006033 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006034 if (Expr *E = dyn_cast<Expr>(S))
6035 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006036 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006037 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006038 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006039 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6040 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6041 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006042 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6043 EmitDiags);
6044 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006045 }
6046 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6047 if (ME->isArrow() &&
6048 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006049 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6050 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006051 }
6052 }
David Majnemer9d168222016-08-05 17:44:54 +00006053 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006054 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00006055 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00006056 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006057 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00006058 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006059 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006060 diag::ext_omp_loop_not_canonical_init)
6061 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00006062 return setLCDeclAndLB(
6063 Var,
6064 buildDeclRefExpr(SemaRef, Var,
6065 Var->getType().getNonReferenceType(),
6066 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00006067 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006068 }
6069 }
6070 }
David Majnemer9d168222016-08-05 17:44:54 +00006071 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006072 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006073 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00006074 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006075 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6076 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006077 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6078 EmitDiags);
6079 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006080 }
6081 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6082 if (ME->isArrow() &&
6083 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006084 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6085 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006086 }
6087 }
6088 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006089
Alexey Bataeve3727102018-04-18 15:57:46 +00006090 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006091 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00006092 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006093 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00006094 << S->getSourceRange();
6095 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006096 return true;
6097}
6098
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006099/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006100/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00006101static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006102 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00006103 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006104 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00006105 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006106 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00006107 if ((Ctor->isCopyOrMoveConstructor() ||
6108 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6109 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006110 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00006111 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6112 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006113 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006114 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006115 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006116 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6117 return getCanonicalDecl(ME->getMemberDecl());
6118 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006119}
6120
Alexey Bataeve3727102018-04-18 15:57:46 +00006121bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006122 // Check test-expr for canonical form, save upper-bound UB, flags for
6123 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00006124 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006125 // var relational-op b
6126 // b relational-op var
6127 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006128 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006129 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006130 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6131 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006132 return true;
6133 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006134 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006135 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006136 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006137 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006138 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006139 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6140 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006141 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6142 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6143 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006144 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6145 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006146 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6147 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6148 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006149 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6150 return setUB(
6151 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6152 /*LessOp=*/llvm::None,
6153 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006154 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006155 if (CE->getNumArgs() == 2) {
6156 auto Op = CE->getOperator();
6157 switch (Op) {
6158 case OO_Greater:
6159 case OO_GreaterEqual:
6160 case OO_Less:
6161 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006162 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6163 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006164 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6165 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006166 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6167 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006168 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6169 CE->getOperatorLoc());
6170 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006171 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006172 if (IneqCondIsCanonical)
6173 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6174 : CE->getArg(0),
6175 /*LessOp=*/llvm::None,
6176 /*StrictOp=*/true, CE->getSourceRange(),
6177 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006178 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006179 default:
6180 break;
6181 }
6182 }
6183 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006184 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006185 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006186 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006187 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006188 return true;
6189}
6190
Alexey Bataeve3727102018-04-18 15:57:46 +00006191bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006192 // RHS of canonical loop form increment can be:
6193 // var + incr
6194 // incr + var
6195 // var - incr
6196 //
6197 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006198 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006199 if (BO->isAdditiveOp()) {
6200 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006201 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6202 return setStep(BO->getRHS(), !IsAdd);
6203 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6204 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006205 }
David Majnemer9d168222016-08-05 17:44:54 +00006206 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006207 bool IsAdd = CE->getOperator() == OO_Plus;
6208 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006209 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6210 return setStep(CE->getArg(1), !IsAdd);
6211 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6212 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006213 }
6214 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006215 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006216 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006217 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006218 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006219 return true;
6220}
6221
Alexey Bataeve3727102018-04-18 15:57:46 +00006222bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006223 // Check incr-expr for canonical loop form and return true if it
6224 // does not conform.
6225 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6226 // ++var
6227 // var++
6228 // --var
6229 // var--
6230 // var += incr
6231 // var -= incr
6232 // var = var + incr
6233 // var = incr + var
6234 // var = var - incr
6235 //
6236 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006237 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006238 return true;
6239 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006240 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6241 if (!ExprTemp->cleanupsHaveSideEffects())
6242 S = ExprTemp->getSubExpr();
6243
Alexander Musmana5f070a2014-10-01 06:03:56 +00006244 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006245 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006246 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006247 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006248 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6249 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006250 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006251 (UO->isDecrementOp() ? -1 : 1))
6252 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006253 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006254 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006255 switch (BO->getOpcode()) {
6256 case BO_AddAssign:
6257 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006258 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6259 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006260 break;
6261 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006262 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6263 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006264 break;
6265 default:
6266 break;
6267 }
David Majnemer9d168222016-08-05 17:44:54 +00006268 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006269 switch (CE->getOperator()) {
6270 case OO_PlusPlus:
6271 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006272 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6273 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006274 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006275 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006276 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6277 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006278 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006279 break;
6280 case OO_PlusEqual:
6281 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006282 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6283 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006284 break;
6285 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006286 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6287 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006288 break;
6289 default:
6290 break;
6291 }
6292 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006293 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006294 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006295 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006296 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006297 return true;
6298}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006299
Alexey Bataev5a3af132016-03-29 08:58:54 +00006300static ExprResult
6301tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006302 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006303 if (SemaRef.CurContext->isDependentContext())
6304 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006305 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6306 return SemaRef.PerformImplicitConversion(
6307 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6308 /*AllowExplicit=*/true);
6309 auto I = Captures.find(Capture);
6310 if (I != Captures.end())
6311 return buildCapture(SemaRef, Capture, I->second);
6312 DeclRefExpr *Ref = nullptr;
6313 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6314 Captures[Capture] = Ref;
6315 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006316}
6317
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006318/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006319Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006320 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006321 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006322 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006323 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006324 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006325 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006326 Expr *LBVal = LB;
6327 Expr *UBVal = UB;
6328 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6329 // max(LB(MinVal), LB(MaxVal))
6330 if (InitDependOnLC) {
6331 const LoopIterationSpace &IS =
6332 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6333 InitDependOnLC.getValueOr(
6334 CondDependOnLC.getValueOr(0))];
6335 if (!IS.MinValue || !IS.MaxValue)
6336 return nullptr;
6337 // OuterVar = Min
6338 ExprResult MinValue =
6339 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6340 if (!MinValue.isUsable())
6341 return nullptr;
6342
6343 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6344 IS.CounterVar, MinValue.get());
6345 if (!LBMinVal.isUsable())
6346 return nullptr;
6347 // OuterVar = Min, LBVal
6348 LBMinVal =
6349 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6350 if (!LBMinVal.isUsable())
6351 return nullptr;
6352 // (OuterVar = Min, LBVal)
6353 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6354 if (!LBMinVal.isUsable())
6355 return nullptr;
6356
6357 // OuterVar = Max
6358 ExprResult MaxValue =
6359 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6360 if (!MaxValue.isUsable())
6361 return nullptr;
6362
6363 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6364 IS.CounterVar, MaxValue.get());
6365 if (!LBMaxVal.isUsable())
6366 return nullptr;
6367 // OuterVar = Max, LBVal
6368 LBMaxVal =
6369 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6370 if (!LBMaxVal.isUsable())
6371 return nullptr;
6372 // (OuterVar = Max, LBVal)
6373 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6374 if (!LBMaxVal.isUsable())
6375 return nullptr;
6376
6377 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6378 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6379 if (!LBMin || !LBMax)
6380 return nullptr;
6381 // LB(MinVal) < LB(MaxVal)
6382 ExprResult MinLessMaxRes =
6383 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6384 if (!MinLessMaxRes.isUsable())
6385 return nullptr;
6386 Expr *MinLessMax =
6387 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6388 if (!MinLessMax)
6389 return nullptr;
6390 if (TestIsLessOp.getValue()) {
6391 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6392 // LB(MaxVal))
6393 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6394 MinLessMax, LBMin, LBMax);
6395 if (!MinLB.isUsable())
6396 return nullptr;
6397 LBVal = MinLB.get();
6398 } else {
6399 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6400 // LB(MaxVal))
6401 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6402 MinLessMax, LBMax, LBMin);
6403 if (!MaxLB.isUsable())
6404 return nullptr;
6405 LBVal = MaxLB.get();
6406 }
6407 }
6408 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6409 // min(UB(MinVal), UB(MaxVal))
6410 if (CondDependOnLC) {
6411 const LoopIterationSpace &IS =
6412 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6413 InitDependOnLC.getValueOr(
6414 CondDependOnLC.getValueOr(0))];
6415 if (!IS.MinValue || !IS.MaxValue)
6416 return nullptr;
6417 // OuterVar = Min
6418 ExprResult MinValue =
6419 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6420 if (!MinValue.isUsable())
6421 return nullptr;
6422
6423 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6424 IS.CounterVar, MinValue.get());
6425 if (!UBMinVal.isUsable())
6426 return nullptr;
6427 // OuterVar = Min, UBVal
6428 UBMinVal =
6429 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6430 if (!UBMinVal.isUsable())
6431 return nullptr;
6432 // (OuterVar = Min, UBVal)
6433 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6434 if (!UBMinVal.isUsable())
6435 return nullptr;
6436
6437 // OuterVar = Max
6438 ExprResult MaxValue =
6439 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6440 if (!MaxValue.isUsable())
6441 return nullptr;
6442
6443 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6444 IS.CounterVar, MaxValue.get());
6445 if (!UBMaxVal.isUsable())
6446 return nullptr;
6447 // OuterVar = Max, UBVal
6448 UBMaxVal =
6449 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6450 if (!UBMaxVal.isUsable())
6451 return nullptr;
6452 // (OuterVar = Max, UBVal)
6453 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6454 if (!UBMaxVal.isUsable())
6455 return nullptr;
6456
6457 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6458 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6459 if (!UBMin || !UBMax)
6460 return nullptr;
6461 // UB(MinVal) > UB(MaxVal)
6462 ExprResult MinGreaterMaxRes =
6463 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6464 if (!MinGreaterMaxRes.isUsable())
6465 return nullptr;
6466 Expr *MinGreaterMax =
6467 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6468 if (!MinGreaterMax)
6469 return nullptr;
6470 if (TestIsLessOp.getValue()) {
6471 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6472 // UB(MaxVal))
6473 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6474 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6475 if (!MaxUB.isUsable())
6476 return nullptr;
6477 UBVal = MaxUB.get();
6478 } else {
6479 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6480 // UB(MaxVal))
6481 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6482 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6483 if (!MinUB.isUsable())
6484 return nullptr;
6485 UBVal = MinUB.get();
6486 }
6487 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006488 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006489 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6490 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006491 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6492 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006493 if (!Upper || !Lower)
6494 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006495
6496 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6497
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006498 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006499 // BuildBinOp already emitted error, this one is to point user to upper
6500 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006501 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006502 << Upper->getSourceRange() << Lower->getSourceRange();
6503 return nullptr;
6504 }
6505 }
6506
6507 if (!Diff.isUsable())
6508 return nullptr;
6509
6510 // Upper - Lower [- 1]
6511 if (TestIsStrictOp)
6512 Diff = SemaRef.BuildBinOp(
6513 S, DefaultLoc, BO_Sub, Diff.get(),
6514 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6515 if (!Diff.isUsable())
6516 return nullptr;
6517
6518 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006519 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006520 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006521 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006522 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006523 if (!Diff.isUsable())
6524 return nullptr;
6525
6526 // Parentheses (for dumping/debugging purposes only).
6527 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6528 if (!Diff.isUsable())
6529 return nullptr;
6530
6531 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006532 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006533 if (!Diff.isUsable())
6534 return nullptr;
6535
Alexander Musman174b3ca2014-10-06 11:16:29 +00006536 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006537 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006538 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006539 bool UseVarType = VarType->hasIntegerRepresentation() &&
6540 C.getTypeSize(Type) > C.getTypeSize(VarType);
6541 if (!Type->isIntegerType() || UseVarType) {
6542 unsigned NewSize =
6543 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6544 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6545 : Type->hasSignedIntegerRepresentation();
6546 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006547 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6548 Diff = SemaRef.PerformImplicitConversion(
6549 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6550 if (!Diff.isUsable())
6551 return nullptr;
6552 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006553 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006554 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006555 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6556 if (NewSize != C.getTypeSize(Type)) {
6557 if (NewSize < C.getTypeSize(Type)) {
6558 assert(NewSize == 64 && "incorrect loop var size");
6559 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6560 << InitSrcRange << ConditionSrcRange;
6561 }
6562 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006563 NewSize, Type->hasSignedIntegerRepresentation() ||
6564 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006565 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6566 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6567 Sema::AA_Converting, true);
6568 if (!Diff.isUsable())
6569 return nullptr;
6570 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006571 }
6572 }
6573
Alexander Musmana5f070a2014-10-01 06:03:56 +00006574 return Diff.get();
6575}
6576
Alexey Bataevf8be4762019-08-14 19:30:06 +00006577std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6578 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6579 // Do not build for iterators, they cannot be used in non-rectangular loop
6580 // nests.
6581 if (LCDecl->getType()->isRecordType())
6582 return std::make_pair(nullptr, nullptr);
6583 // If we subtract, the min is in the condition, otherwise the min is in the
6584 // init value.
6585 Expr *MinExpr = nullptr;
6586 Expr *MaxExpr = nullptr;
6587 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6588 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6589 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6590 : CondDependOnLC.hasValue();
6591 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6592 : InitDependOnLC.hasValue();
6593 Expr *Lower =
6594 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6595 Expr *Upper =
6596 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6597 if (!Upper || !Lower)
6598 return std::make_pair(nullptr, nullptr);
6599
6600 if (TestIsLessOp.getValue())
6601 MinExpr = Lower;
6602 else
6603 MaxExpr = Upper;
6604
6605 // Build minimum/maximum value based on number of iterations.
6606 ExprResult Diff;
6607 QualType VarType = LCDecl->getType().getNonReferenceType();
6608
6609 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6610 if (!Diff.isUsable())
6611 return std::make_pair(nullptr, nullptr);
6612
6613 // Upper - Lower [- 1]
6614 if (TestIsStrictOp)
6615 Diff = SemaRef.BuildBinOp(
6616 S, DefaultLoc, BO_Sub, Diff.get(),
6617 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6618 if (!Diff.isUsable())
6619 return std::make_pair(nullptr, nullptr);
6620
6621 // Upper - Lower [- 1] + Step
6622 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6623 if (!NewStep.isUsable())
6624 return std::make_pair(nullptr, nullptr);
6625
6626 // Parentheses (for dumping/debugging purposes only).
6627 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6628 if (!Diff.isUsable())
6629 return std::make_pair(nullptr, nullptr);
6630
6631 // (Upper - Lower [- 1]) / Step
6632 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6633 if (!Diff.isUsable())
6634 return std::make_pair(nullptr, nullptr);
6635
6636 // ((Upper - Lower [- 1]) / Step) * Step
6637 // Parentheses (for dumping/debugging purposes only).
6638 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6639 if (!Diff.isUsable())
6640 return std::make_pair(nullptr, nullptr);
6641
6642 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6643 if (!Diff.isUsable())
6644 return std::make_pair(nullptr, nullptr);
6645
6646 // Convert to the original type or ptrdiff_t, if original type is pointer.
6647 if (!VarType->isAnyPointerType() &&
6648 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6649 Diff = SemaRef.PerformImplicitConversion(
6650 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6651 } else if (VarType->isAnyPointerType() &&
6652 !SemaRef.Context.hasSameType(
6653 Diff.get()->getType(),
6654 SemaRef.Context.getUnsignedPointerDiffType())) {
6655 Diff = SemaRef.PerformImplicitConversion(
6656 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6657 Sema::AA_Converting, /*AllowExplicit=*/true);
6658 }
6659 if (!Diff.isUsable())
6660 return std::make_pair(nullptr, nullptr);
6661
6662 // Parentheses (for dumping/debugging purposes only).
6663 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6664 if (!Diff.isUsable())
6665 return std::make_pair(nullptr, nullptr);
6666
6667 if (TestIsLessOp.getValue()) {
6668 // MinExpr = Lower;
6669 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6670 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6671 if (!Diff.isUsable())
6672 return std::make_pair(nullptr, nullptr);
6673 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6674 if (!Diff.isUsable())
6675 return std::make_pair(nullptr, nullptr);
6676 MaxExpr = Diff.get();
6677 } else {
6678 // MaxExpr = Upper;
6679 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6680 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6681 if (!Diff.isUsable())
6682 return std::make_pair(nullptr, nullptr);
6683 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6684 if (!Diff.isUsable())
6685 return std::make_pair(nullptr, nullptr);
6686 MinExpr = Diff.get();
6687 }
6688
6689 return std::make_pair(MinExpr, MaxExpr);
6690}
6691
6692Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6693 if (InitDependOnLC || CondDependOnLC)
6694 return Condition;
6695 return nullptr;
6696}
6697
Alexey Bataeve3727102018-04-18 15:57:46 +00006698Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006699 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006700 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006701 // Do not build a precondition when the condition/initialization is dependent
6702 // to prevent pessimistic early loop exit.
6703 // TODO: this can be improved by calculating min/max values but not sure that
6704 // it will be very effective.
6705 if (CondDependOnLC || InitDependOnLC)
6706 return SemaRef.PerformImplicitConversion(
6707 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6708 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6709 /*AllowExplicit=*/true).get();
6710
Alexey Bataev62dbb972015-04-22 11:59:37 +00006711 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006712 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006713
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006714 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6715 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006716 if (!NewLB.isUsable() || !NewUB.isUsable())
6717 return nullptr;
6718
Alexey Bataeve3727102018-04-18 15:57:46 +00006719 ExprResult CondExpr =
6720 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006721 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006722 (TestIsStrictOp ? BO_LT : BO_LE) :
6723 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006724 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006725 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006726 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6727 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006728 CondExpr = SemaRef.PerformImplicitConversion(
6729 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6730 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006731 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006732
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006733 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006734 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6735}
6736
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006737/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006738DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006739 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6740 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006741 auto *VD = dyn_cast<VarDecl>(LCDecl);
6742 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006743 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6744 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006745 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006746 const DSAStackTy::DSAVarData Data =
6747 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006748 // If the loop control decl is explicitly marked as private, do not mark it
6749 // as captured again.
6750 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6751 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006752 return Ref;
6753 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006754 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006755}
6756
Alexey Bataeve3727102018-04-18 15:57:46 +00006757Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006758 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006759 QualType Type = LCDecl->getType().getNonReferenceType();
6760 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006761 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6762 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6763 isa<VarDecl>(LCDecl)
6764 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6765 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006766 if (PrivateVar->isInvalidDecl())
6767 return nullptr;
6768 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6769 }
6770 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006771}
6772
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006773/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006774Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006775
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006776/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006777Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006778
Alexey Bataevf138fda2018-08-13 19:04:24 +00006779Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6780 Scope *S, Expr *Counter,
6781 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6782 Expr *Inc, OverloadedOperatorKind OOK) {
6783 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6784 if (!Cnt)
6785 return nullptr;
6786 if (Inc) {
6787 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6788 "Expected only + or - operations for depend clauses.");
6789 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6790 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6791 if (!Cnt)
6792 return nullptr;
6793 }
6794 ExprResult Diff;
6795 QualType VarType = LCDecl->getType().getNonReferenceType();
6796 if (VarType->isIntegerType() || VarType->isPointerType() ||
6797 SemaRef.getLangOpts().CPlusPlus) {
6798 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006799 Expr *Upper = TestIsLessOp.getValue()
6800 ? Cnt
6801 : tryBuildCapture(SemaRef, UB, Captures).get();
6802 Expr *Lower = TestIsLessOp.getValue()
6803 ? tryBuildCapture(SemaRef, LB, Captures).get()
6804 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006805 if (!Upper || !Lower)
6806 return nullptr;
6807
6808 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6809
6810 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6811 // BuildBinOp already emitted error, this one is to point user to upper
6812 // and lower bound, and to tell what is passed to 'operator-'.
6813 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6814 << Upper->getSourceRange() << Lower->getSourceRange();
6815 return nullptr;
6816 }
6817 }
6818
6819 if (!Diff.isUsable())
6820 return nullptr;
6821
6822 // Parentheses (for dumping/debugging purposes only).
6823 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6824 if (!Diff.isUsable())
6825 return nullptr;
6826
6827 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6828 if (!NewStep.isUsable())
6829 return nullptr;
6830 // (Upper - Lower) / Step
6831 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6832 if (!Diff.isUsable())
6833 return nullptr;
6834
6835 return Diff.get();
6836}
Alexey Bataev23b69422014-06-18 07:08:49 +00006837} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006838
Alexey Bataev9c821032015-04-30 04:23:23 +00006839void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6840 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6841 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006842 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6843 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006844 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006845 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006846 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006847 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6848 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006849 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006850 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006851 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006852 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006853 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006854 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006855 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6856 /*WithInit=*/false);
6857 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006858 }
6859 }
6860 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006861 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6862 if (LD != D->getCanonicalDecl()) {
6863 DSAStack->resetPossibleLoopCounter();
6864 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6865 MarkDeclarationsReferencedInExpr(
6866 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6867 Var->getType().getNonLValueExprType(Context),
6868 ForLoc, /*RefersToCapture=*/true));
6869 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006870 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6871 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6872 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6873 // associated for-loop of a simd construct with just one associated
6874 // for-loop may be listed in a linear clause with a constant-linear-step
6875 // that is the increment of the associated for-loop. The loop iteration
6876 // variable(s) in the associated for-loop(s) of a for or parallel for
6877 // construct may be listed in a private or lastprivate clause.
6878 DSAStackTy::DSAVarData DVar =
6879 DSAStack->getTopDSA(D, /*FromParent=*/false);
6880 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6881 // is declared in the loop and it is predetermined as a private.
6882 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6883 OpenMPClauseKind PredeterminedCKind =
6884 isOpenMPSimdDirective(DKind)
6885 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6886 : OMPC_private;
6887 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6888 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6889 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6890 DVar.CKind != OMPC_private))) ||
6891 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006892 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006893 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006894 isOpenMPDistributeDirective(DKind)) &&
6895 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6896 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6897 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6898 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6899 << getOpenMPClauseName(DVar.CKind)
6900 << getOpenMPDirectiveName(DKind)
6901 << getOpenMPClauseName(PredeterminedCKind);
6902 if (DVar.RefExpr == nullptr)
6903 DVar.CKind = PredeterminedCKind;
6904 reportOriginalDsa(*this, DSAStack, D, DVar,
6905 /*IsLoopIterVar=*/true);
6906 } else if (LoopDeclRefExpr) {
6907 // Make the loop iteration variable private (for worksharing
6908 // constructs), linear (for simd directives with the only one
6909 // associated loop) or lastprivate (for simd directives with several
6910 // collapsed or ordered loops).
6911 if (DVar.CKind == OMPC_unknown)
6912 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6913 PrivateRef);
6914 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006915 }
6916 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006917 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006918 }
6919}
6920
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006921/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006922/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006923static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006924 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6925 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006926 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6927 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006928 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006929 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006930 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006931 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006932 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006933 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006934 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006935 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6936 // Ranged for is supported only in OpenMP 5.0.
6937 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006938 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006939 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006940 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006941 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006942 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006943 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6944 SemaRef.Diag(DSA.getConstructLoc(),
6945 diag::note_omp_collapse_ordered_expr)
6946 << 2 << CollapseLoopCountExpr->getSourceRange()
6947 << OrderedLoopCountExpr->getSourceRange();
6948 else if (CollapseLoopCountExpr)
6949 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6950 diag::note_omp_collapse_ordered_expr)
6951 << 0 << CollapseLoopCountExpr->getSourceRange();
6952 else
6953 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6954 diag::note_omp_collapse_ordered_expr)
6955 << 1 << OrderedLoopCountExpr->getSourceRange();
6956 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006957 return true;
6958 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006959 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6960 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006961
Alexey Bataevbef93a92019-10-07 18:54:57 +00006962 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6963 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006964
6965 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006966 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00006967 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006968 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006969
6970 bool HasErrors = false;
6971
6972 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006973 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006974 // OpenMP [2.6, Canonical Loop Form]
6975 // Var is one of the following:
6976 // A variable of signed or unsigned integer type.
6977 // For C++, a variable of a random access iterator type.
6978 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006979 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006980 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6981 !VarType->isPointerType() &&
6982 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006983 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006984 << SemaRef.getLangOpts().CPlusPlus;
6985 HasErrors = true;
6986 }
6987
6988 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6989 // a Construct
6990 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6991 // parallel for construct is (are) private.
6992 // The loop iteration variable in the associated for-loop of a simd
6993 // construct with just one associated for-loop is linear with a
6994 // constant-linear-step that is the increment of the associated for-loop.
6995 // Exclude loop var from the list of variables with implicitly defined data
6996 // sharing attributes.
6997 VarsWithImplicitDSA.erase(LCDecl);
6998
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006999 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
7000
7001 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007002 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007003
7004 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007005 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007006 }
7007
Alexey Bataeve3727102018-04-18 15:57:46 +00007008 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007009 return HasErrors;
7010
Alexander Musmana5f070a2014-10-01 06:03:56 +00007011 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007012 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
7013 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007014 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
7015 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
7016 (isOpenMPWorksharingDirective(DKind) ||
7017 isOpenMPTaskLoopDirective(DKind) ||
7018 isOpenMPDistributeDirective(DKind)),
7019 Captures);
7020 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
7021 ISC.buildCounterVar(Captures, DSA);
7022 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
7023 ISC.buildPrivateCounterVar();
7024 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
7025 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
7026 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
7027 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
7028 ISC.getConditionSrcRange();
7029 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
7030 ISC.getIncrementSrcRange();
7031 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
7032 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
7033 ISC.isStrictTestOp();
7034 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
7035 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
7036 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
7037 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
7038 ISC.buildFinalCondition(DSA.getCurScope());
7039 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
7040 ISC.doesInitDependOnLC();
7041 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
7042 ISC.doesCondDependOnLC();
7043 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
7044 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007045
Alexey Bataevf8be4762019-08-14 19:30:06 +00007046 HasErrors |=
7047 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
7048 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
7049 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
7050 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
7051 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
7052 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007053 if (!HasErrors && DSA.isOrderedRegion()) {
7054 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7055 if (CurrentNestedLoopCount <
7056 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7057 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007058 CurrentNestedLoopCount,
7059 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007060 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007061 CurrentNestedLoopCount,
7062 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007063 }
7064 }
7065 for (auto &Pair : DSA.getDoacrossDependClauses()) {
7066 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7067 // Erroneous case - clause has some problems.
7068 continue;
7069 }
7070 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7071 Pair.second.size() <= CurrentNestedLoopCount) {
7072 // Erroneous case - clause has some problems.
7073 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7074 continue;
7075 }
7076 Expr *CntValue;
7077 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7078 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007079 DSA.getCurScope(),
7080 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007081 Pair.first->getDependencyLoc());
7082 else
7083 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007084 DSA.getCurScope(),
7085 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007086 Pair.first->getDependencyLoc(),
7087 Pair.second[CurrentNestedLoopCount].first,
7088 Pair.second[CurrentNestedLoopCount].second);
7089 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7090 }
7091 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007092
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007093 return HasErrors;
7094}
7095
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007096/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00007097static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00007098buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007099 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007100 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007101 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007102 ExprResult NewStart = IsNonRectangularLB
7103 ? Start.get()
7104 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00007105 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007106 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00007107 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00007108 VarRef.get()->getType())) {
7109 NewStart = SemaRef.PerformImplicitConversion(
7110 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7111 /*AllowExplicit=*/true);
7112 if (!NewStart.isUsable())
7113 return ExprError();
7114 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007115
Alexey Bataeve3727102018-04-18 15:57:46 +00007116 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007117 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7118 return Init;
7119}
7120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007121/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00007122static ExprResult buildCounterUpdate(
7123 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7124 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007125 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007126 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007127 // Add parentheses (for debugging purposes only).
7128 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7129 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7130 !Step.isUsable())
7131 return ExprError();
7132
Alexey Bataev5a3af132016-03-29 08:58:54 +00007133 ExprResult NewStep = Step;
7134 if (Captures)
7135 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007136 if (NewStep.isInvalid())
7137 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007138 ExprResult Update =
7139 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007140 if (!Update.isUsable())
7141 return ExprError();
7142
Alexey Bataevc0214e02016-02-16 12:13:49 +00007143 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7144 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007145 if (!Start.isUsable())
7146 return ExprError();
7147 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7148 if (!NewStart.isUsable())
7149 return ExprError();
7150 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007151 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007152 if (NewStart.isInvalid())
7153 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007154
Alexey Bataevc0214e02016-02-16 12:13:49 +00007155 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7156 ExprResult SavedUpdate = Update;
7157 ExprResult UpdateVal;
7158 if (VarRef.get()->getType()->isOverloadableType() ||
7159 NewStart.get()->getType()->isOverloadableType() ||
7160 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007161 Sema::TentativeAnalysisScope Trap(SemaRef);
7162
Alexey Bataevc0214e02016-02-16 12:13:49 +00007163 Update =
7164 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7165 if (Update.isUsable()) {
7166 UpdateVal =
7167 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7168 VarRef.get(), SavedUpdate.get());
7169 if (UpdateVal.isUsable()) {
7170 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7171 UpdateVal.get());
7172 }
7173 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007174 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007175
Alexey Bataevc0214e02016-02-16 12:13:49 +00007176 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7177 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7178 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7179 NewStart.get(), SavedUpdate.get());
7180 if (!Update.isUsable())
7181 return ExprError();
7182
Alexey Bataev11481f52016-02-17 10:29:05 +00007183 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7184 VarRef.get()->getType())) {
7185 Update = SemaRef.PerformImplicitConversion(
7186 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7187 if (!Update.isUsable())
7188 return ExprError();
7189 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007190
7191 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7192 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007193 return Update;
7194}
7195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007196/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007197/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007198static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007199 if (E == nullptr)
7200 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007201 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007202 QualType OldType = E->getType();
7203 unsigned HasBits = C.getTypeSize(OldType);
7204 if (HasBits >= Bits)
7205 return ExprResult(E);
7206 // OK to convert to signed, because new type has more bits than old.
7207 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7208 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7209 true);
7210}
7211
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007212/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007213/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007214static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007215 if (E == nullptr)
7216 return false;
7217 llvm::APSInt Result;
7218 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7219 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7220 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007221}
7222
Alexey Bataev5a3af132016-03-29 08:58:54 +00007223/// Build preinits statement for the given declarations.
7224static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007225 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007226 if (!PreInits.empty()) {
7227 return new (Context) DeclStmt(
7228 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7229 SourceLocation(), SourceLocation());
7230 }
7231 return nullptr;
7232}
7233
7234/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007235static Stmt *
7236buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007237 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007238 if (!Captures.empty()) {
7239 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007240 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007241 PreInits.push_back(Pair.second->getDecl());
7242 return buildPreInits(Context, PreInits);
7243 }
7244 return nullptr;
7245}
7246
7247/// Build postupdate expression for the given list of postupdates expressions.
7248static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7249 Expr *PostUpdate = nullptr;
7250 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007251 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007252 Expr *ConvE = S.BuildCStyleCastExpr(
7253 E->getExprLoc(),
7254 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7255 E->getExprLoc(), E)
7256 .get();
7257 PostUpdate = PostUpdate
7258 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7259 PostUpdate, ConvE)
7260 .get()
7261 : ConvE;
7262 }
7263 }
7264 return PostUpdate;
7265}
7266
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007267/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007268/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7269/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007270static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007271checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007272 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7273 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007274 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007275 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007276 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007277 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007278 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007279 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007280 if (!CollapseLoopCountExpr->isValueDependent() &&
7281 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007282 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007283 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007284 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007285 return 1;
7286 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007287 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007288 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007289 if (OrderedLoopCountExpr) {
7290 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007291 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007292 if (!OrderedLoopCountExpr->isValueDependent() &&
7293 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7294 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007295 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007296 if (Result.getLimitedValue() < NestedLoopCount) {
7297 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7298 diag::err_omp_wrong_ordered_loop_count)
7299 << OrderedLoopCountExpr->getSourceRange();
7300 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7301 diag::note_collapse_loop_count)
7302 << CollapseLoopCountExpr->getSourceRange();
7303 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007304 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007305 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007306 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007307 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007308 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007309 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007310 // This is helper routine for loop directives (e.g., 'for', 'simd',
7311 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007312 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007313 SmallVector<LoopIterationSpace, 4> IterSpaces(
7314 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007315 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007316 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007317 if (checkOpenMPIterationSpace(
7318 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7319 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007320 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007321 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007322 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007323 // OpenMP [2.8.1, simd construct, Restrictions]
7324 // All loops associated with the construct must be perfectly nested; that
7325 // is, there must be no intervening code nor any OpenMP directive between
7326 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007327 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7328 CurStmt = For->getBody();
7329 } else {
7330 assert(isa<CXXForRangeStmt>(CurStmt) &&
7331 "Expected canonical for or range-based for loops.");
7332 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7333 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007334 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7335 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007336 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007337 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7338 if (checkOpenMPIterationSpace(
7339 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7340 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007341 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007342 return 0;
7343 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7344 // Handle initialization of captured loop iterator variables.
7345 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7346 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7347 Captures[DRE] = DRE;
7348 }
7349 }
7350 // Move on to the next nested for loop, or to the loop body.
7351 // OpenMP [2.8.1, simd construct, Restrictions]
7352 // All loops associated with the construct must be perfectly nested; that
7353 // is, there must be no intervening code nor any OpenMP directive between
7354 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007355 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7356 CurStmt = For->getBody();
7357 } else {
7358 assert(isa<CXXForRangeStmt>(CurStmt) &&
7359 "Expected canonical for or range-based for loops.");
7360 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7361 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007362 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7363 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007364 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007365
Alexander Musmana5f070a2014-10-01 06:03:56 +00007366 Built.clear(/* size */ NestedLoopCount);
7367
7368 if (SemaRef.CurContext->isDependentContext())
7369 return NestedLoopCount;
7370
7371 // An example of what is generated for the following code:
7372 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007373 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007374 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007375 // for (k = 0; k < NK; ++k)
7376 // for (j = J0; j < NJ; j+=2) {
7377 // <loop body>
7378 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007379 //
7380 // We generate the code below.
7381 // Note: the loop body may be outlined in CodeGen.
7382 // Note: some counters may be C++ classes, operator- is used to find number of
7383 // iterations and operator+= to calculate counter value.
7384 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7385 // or i64 is currently supported).
7386 //
7387 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7388 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7389 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7390 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7391 // // similar updates for vars in clauses (e.g. 'linear')
7392 // <loop body (using local i and j)>
7393 // }
7394 // i = NI; // assign final values of counters
7395 // j = NJ;
7396 //
7397
7398 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7399 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007400 // Precondition tests if there is at least one iteration (all conditions are
7401 // true).
7402 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007403 Expr *N0 = IterSpaces[0].NumIterations;
7404 ExprResult LastIteration32 =
7405 widenIterationCount(/*Bits=*/32,
7406 SemaRef
7407 .PerformImplicitConversion(
7408 N0->IgnoreImpCasts(), N0->getType(),
7409 Sema::AA_Converting, /*AllowExplicit=*/true)
7410 .get(),
7411 SemaRef);
7412 ExprResult LastIteration64 = widenIterationCount(
7413 /*Bits=*/64,
7414 SemaRef
7415 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7416 Sema::AA_Converting,
7417 /*AllowExplicit=*/true)
7418 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007419 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007420
7421 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7422 return NestedLoopCount;
7423
Alexey Bataeve3727102018-04-18 15:57:46 +00007424 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007425 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7426
7427 Scope *CurScope = DSA.getCurScope();
7428 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007429 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007430 PreCond =
7431 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7432 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007433 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007434 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007435 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007436 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7437 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007438 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007439 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007440 SemaRef
7441 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7442 Sema::AA_Converting,
7443 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007444 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007445 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007446 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007447 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007448 SemaRef
7449 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7450 Sema::AA_Converting,
7451 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007452 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007453 }
7454
7455 // Choose either the 32-bit or 64-bit version.
7456 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007457 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7458 (LastIteration32.isUsable() &&
7459 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7460 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7461 fitsInto(
7462 /*Bits=*/32,
7463 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7464 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007465 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007466 QualType VType = LastIteration.get()->getType();
7467 QualType RealVType = VType;
7468 QualType StrideVType = VType;
7469 if (isOpenMPTaskLoopDirective(DKind)) {
7470 VType =
7471 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7472 StrideVType =
7473 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7474 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007475
7476 if (!LastIteration.isUsable())
7477 return 0;
7478
7479 // Save the number of iterations.
7480 ExprResult NumIterations = LastIteration;
7481 {
7482 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007483 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7484 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007485 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7486 if (!LastIteration.isUsable())
7487 return 0;
7488 }
7489
7490 // Calculate the last iteration number beforehand instead of doing this on
7491 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7492 llvm::APSInt Result;
7493 bool IsConstant =
7494 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7495 ExprResult CalcLastIteration;
7496 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007497 ExprResult SaveRef =
7498 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007499 LastIteration = SaveRef;
7500
7501 // Prepare SaveRef + 1.
7502 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007503 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007504 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7505 if (!NumIterations.isUsable())
7506 return 0;
7507 }
7508
7509 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7510
David Majnemer9d168222016-08-05 17:44:54 +00007511 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007512 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007513 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7514 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007515 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007516 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7517 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007518 SemaRef.AddInitializerToDecl(LBDecl,
7519 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7520 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007521
7522 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007523 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7524 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007525 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007526 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007527
7528 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7529 // This will be used to implement clause 'lastprivate'.
7530 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007531 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7532 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007533 SemaRef.AddInitializerToDecl(ILDecl,
7534 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7535 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007536
7537 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007538 VarDecl *STDecl =
7539 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7540 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007541 SemaRef.AddInitializerToDecl(STDecl,
7542 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7543 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007544
7545 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007546 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007547 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7548 UB.get(), LastIteration.get());
7549 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007550 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7551 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007552 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7553 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007554 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007555
7556 // If we have a combined directive that combines 'distribute', 'for' or
7557 // 'simd' we need to be able to access the bounds of the schedule of the
7558 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7559 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7560 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007561 // Lower bound variable, initialized with zero.
7562 VarDecl *CombLBDecl =
7563 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7564 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7565 SemaRef.AddInitializerToDecl(
7566 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7567 /*DirectInit*/ false);
7568
7569 // Upper bound variable, initialized with last iteration number.
7570 VarDecl *CombUBDecl =
7571 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7572 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7573 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7574 /*DirectInit*/ false);
7575
7576 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7577 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7578 ExprResult CombCondOp =
7579 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7580 LastIteration.get(), CombUB.get());
7581 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7582 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007583 CombEUB =
7584 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007585
Alexey Bataeve3727102018-04-18 15:57:46 +00007586 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007587 // We expect to have at least 2 more parameters than the 'parallel'
7588 // directive does - the lower and upper bounds of the previous schedule.
7589 assert(CD->getNumParams() >= 4 &&
7590 "Unexpected number of parameters in loop combined directive");
7591
7592 // Set the proper type for the bounds given what we learned from the
7593 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007594 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7595 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007596
7597 // Previous lower and upper bounds are obtained from the region
7598 // parameters.
7599 PrevLB =
7600 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7601 PrevUB =
7602 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7603 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007604 }
7605
7606 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007607 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007608 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007609 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007610 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7611 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007612 Expr *RHS =
7613 (isOpenMPWorksharingDirective(DKind) ||
7614 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7615 ? LB.get()
7616 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007617 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007618 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007619
7620 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7621 Expr *CombRHS =
7622 (isOpenMPWorksharingDirective(DKind) ||
7623 isOpenMPTaskLoopDirective(DKind) ||
7624 isOpenMPDistributeDirective(DKind))
7625 ? CombLB.get()
7626 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7627 CombInit =
7628 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007629 CombInit =
7630 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007631 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007632 }
7633
Alexey Bataev316ccf62019-01-29 18:51:58 +00007634 bool UseStrictCompare =
7635 RealVType->hasUnsignedIntegerRepresentation() &&
7636 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7637 return LIS.IsStrictCompare;
7638 });
7639 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7640 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007641 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007642 Expr *BoundUB = UB.get();
7643 if (UseStrictCompare) {
7644 BoundUB =
7645 SemaRef
7646 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7647 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7648 .get();
7649 BoundUB =
7650 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7651 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007652 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007653 (isOpenMPWorksharingDirective(DKind) ||
7654 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007655 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7656 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7657 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007658 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7659 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007660 ExprResult CombDistCond;
7661 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007662 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7663 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007664 }
7665
Carlo Bertolliffafe102017-04-20 00:39:39 +00007666 ExprResult CombCond;
7667 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007668 Expr *BoundCombUB = CombUB.get();
7669 if (UseStrictCompare) {
7670 BoundCombUB =
7671 SemaRef
7672 .BuildBinOp(
7673 CurScope, CondLoc, BO_Add, BoundCombUB,
7674 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7675 .get();
7676 BoundCombUB =
7677 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7678 .get();
7679 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007680 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007681 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7682 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007683 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007684 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007685 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007686 ExprResult Inc =
7687 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7688 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7689 if (!Inc.isUsable())
7690 return 0;
7691 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007692 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007693 if (!Inc.isUsable())
7694 return 0;
7695
7696 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7697 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007698 // In combined construct, add combined version that use CombLB and CombUB
7699 // base variables for the update
7700 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007701 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7702 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007703 // LB + ST
7704 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7705 if (!NextLB.isUsable())
7706 return 0;
7707 // LB = LB + ST
7708 NextLB =
7709 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007710 NextLB =
7711 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007712 if (!NextLB.isUsable())
7713 return 0;
7714 // UB + ST
7715 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7716 if (!NextUB.isUsable())
7717 return 0;
7718 // UB = UB + ST
7719 NextUB =
7720 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007721 NextUB =
7722 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007723 if (!NextUB.isUsable())
7724 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007725 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7726 CombNextLB =
7727 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7728 if (!NextLB.isUsable())
7729 return 0;
7730 // LB = LB + ST
7731 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7732 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007733 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7734 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007735 if (!CombNextLB.isUsable())
7736 return 0;
7737 // UB + ST
7738 CombNextUB =
7739 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7740 if (!CombNextUB.isUsable())
7741 return 0;
7742 // UB = UB + ST
7743 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7744 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007745 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7746 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007747 if (!CombNextUB.isUsable())
7748 return 0;
7749 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007750 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007751
Carlo Bertolliffafe102017-04-20 00:39:39 +00007752 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007753 // directive with for as IV = IV + ST; ensure upper bound expression based
7754 // on PrevUB instead of NumIterations - used to implement 'for' when found
7755 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007756 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007757 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007758 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007759 DistCond = SemaRef.BuildBinOp(
7760 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007761 assert(DistCond.isUsable() && "distribute cond expr was not built");
7762
7763 DistInc =
7764 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7765 assert(DistInc.isUsable() && "distribute inc expr was not built");
7766 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7767 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007768 DistInc =
7769 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007770 assert(DistInc.isUsable() && "distribute inc expr was not built");
7771
7772 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7773 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007774 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007775 ExprResult IsUBGreater =
7776 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7777 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7778 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7779 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7780 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007781 PrevEUB =
7782 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007783
Alexey Bataev316ccf62019-01-29 18:51:58 +00007784 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7785 // parallel for is in combination with a distribute directive with
7786 // schedule(static, 1)
7787 Expr *BoundPrevUB = PrevUB.get();
7788 if (UseStrictCompare) {
7789 BoundPrevUB =
7790 SemaRef
7791 .BuildBinOp(
7792 CurScope, CondLoc, BO_Add, BoundPrevUB,
7793 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7794 .get();
7795 BoundPrevUB =
7796 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7797 .get();
7798 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007799 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007800 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7801 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007802 }
7803
Alexander Musmana5f070a2014-10-01 06:03:56 +00007804 // Build updates and final values of the loop counters.
7805 bool HasErrors = false;
7806 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007807 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007808 Built.Updates.resize(NestedLoopCount);
7809 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007810 Built.DependentCounters.resize(NestedLoopCount);
7811 Built.DependentInits.resize(NestedLoopCount);
7812 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007813 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007814 // We implement the following algorithm for obtaining the
7815 // original loop iteration variable values based on the
7816 // value of the collapsed loop iteration variable IV.
7817 //
7818 // Let n+1 be the number of collapsed loops in the nest.
7819 // Iteration variables (I0, I1, .... In)
7820 // Iteration counts (N0, N1, ... Nn)
7821 //
7822 // Acc = IV;
7823 //
7824 // To compute Ik for loop k, 0 <= k <= n, generate:
7825 // Prod = N(k+1) * N(k+2) * ... * Nn;
7826 // Ik = Acc / Prod;
7827 // Acc -= Ik * Prod;
7828 //
7829 ExprResult Acc = IV;
7830 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007831 LoopIterationSpace &IS = IterSpaces[Cnt];
7832 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007833 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007834
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007835 // Compute prod
7836 ExprResult Prod =
7837 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7838 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7839 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7840 IterSpaces[K].NumIterations);
7841
7842 // Iter = Acc / Prod
7843 // If there is at least one more inner loop to avoid
7844 // multiplication by 1.
7845 if (Cnt + 1 < NestedLoopCount)
7846 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7847 Acc.get(), Prod.get());
7848 else
7849 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007850 if (!Iter.isUsable()) {
7851 HasErrors = true;
7852 break;
7853 }
7854
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007855 // Update Acc:
7856 // Acc -= Iter * Prod
7857 // Check if there is at least one more inner loop to avoid
7858 // multiplication by 1.
7859 if (Cnt + 1 < NestedLoopCount)
7860 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7861 Iter.get(), Prod.get());
7862 else
7863 Prod = Iter;
7864 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7865 Acc.get(), Prod.get());
7866
Alexey Bataev39f915b82015-05-08 10:41:21 +00007867 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007868 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007869 DeclRefExpr *CounterVar = buildDeclRefExpr(
7870 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7871 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007872 ExprResult Init =
7873 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7874 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007875 if (!Init.isUsable()) {
7876 HasErrors = true;
7877 break;
7878 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007879 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007880 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007881 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007882 if (!Update.isUsable()) {
7883 HasErrors = true;
7884 break;
7885 }
7886
7887 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007888 ExprResult Final =
7889 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7890 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7891 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007892 if (!Final.isUsable()) {
7893 HasErrors = true;
7894 break;
7895 }
7896
Alexander Musmana5f070a2014-10-01 06:03:56 +00007897 if (!Update.isUsable() || !Final.isUsable()) {
7898 HasErrors = true;
7899 break;
7900 }
7901 // Save results
7902 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007903 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007904 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007905 Built.Updates[Cnt] = Update.get();
7906 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007907 Built.DependentCounters[Cnt] = nullptr;
7908 Built.DependentInits[Cnt] = nullptr;
7909 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007910 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007911 Built.DependentCounters[Cnt] =
7912 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7913 Built.DependentInits[Cnt] =
7914 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7915 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7916 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007917 }
7918 }
7919
7920 if (HasErrors)
7921 return 0;
7922
7923 // Save results
7924 Built.IterationVarRef = IV.get();
7925 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007926 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007927 Built.CalcLastIteration = SemaRef
7928 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007929 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007930 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007931 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007932 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007933 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007934 Built.Init = Init.get();
7935 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007936 Built.LB = LB.get();
7937 Built.UB = UB.get();
7938 Built.IL = IL.get();
7939 Built.ST = ST.get();
7940 Built.EUB = EUB.get();
7941 Built.NLB = NextLB.get();
7942 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007943 Built.PrevLB = PrevLB.get();
7944 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007945 Built.DistInc = DistInc.get();
7946 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007947 Built.DistCombinedFields.LB = CombLB.get();
7948 Built.DistCombinedFields.UB = CombUB.get();
7949 Built.DistCombinedFields.EUB = CombEUB.get();
7950 Built.DistCombinedFields.Init = CombInit.get();
7951 Built.DistCombinedFields.Cond = CombCond.get();
7952 Built.DistCombinedFields.NLB = CombNextLB.get();
7953 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007954 Built.DistCombinedFields.DistCond = CombDistCond.get();
7955 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007956
Alexey Bataevabfc0692014-06-25 06:52:00 +00007957 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007958}
7959
Alexey Bataev10e775f2015-07-30 11:36:16 +00007960static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007961 auto CollapseClauses =
7962 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7963 if (CollapseClauses.begin() != CollapseClauses.end())
7964 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007965 return nullptr;
7966}
7967
Alexey Bataev10e775f2015-07-30 11:36:16 +00007968static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007969 auto OrderedClauses =
7970 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7971 if (OrderedClauses.begin() != OrderedClauses.end())
7972 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007973 return nullptr;
7974}
7975
Kelvin Lic5609492016-07-15 04:39:07 +00007976static bool checkSimdlenSafelenSpecified(Sema &S,
7977 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007978 const OMPSafelenClause *Safelen = nullptr;
7979 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007980
Alexey Bataeve3727102018-04-18 15:57:46 +00007981 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007982 if (Clause->getClauseKind() == OMPC_safelen)
7983 Safelen = cast<OMPSafelenClause>(Clause);
7984 else if (Clause->getClauseKind() == OMPC_simdlen)
7985 Simdlen = cast<OMPSimdlenClause>(Clause);
7986 if (Safelen && Simdlen)
7987 break;
7988 }
7989
7990 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007991 const Expr *SimdlenLength = Simdlen->getSimdlen();
7992 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007993 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7994 SimdlenLength->isInstantiationDependent() ||
7995 SimdlenLength->containsUnexpandedParameterPack())
7996 return false;
7997 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7998 SafelenLength->isInstantiationDependent() ||
7999 SafelenLength->containsUnexpandedParameterPack())
8000 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008001 Expr::EvalResult SimdlenResult, SafelenResult;
8002 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
8003 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
8004 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
8005 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00008006 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
8007 // If both simdlen and safelen clauses are specified, the value of the
8008 // simdlen parameter must be less than or equal to the value of the safelen
8009 // parameter.
8010 if (SimdlenRes > SafelenRes) {
8011 S.Diag(SimdlenLength->getExprLoc(),
8012 diag::err_omp_wrong_simdlen_safelen_values)
8013 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
8014 return true;
8015 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00008016 }
8017 return false;
8018}
8019
Alexey Bataeve3727102018-04-18 15:57:46 +00008020StmtResult
8021Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8022 SourceLocation StartLoc, SourceLocation EndLoc,
8023 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008024 if (!AStmt)
8025 return StmtError();
8026
8027 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008028 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008029 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8030 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008031 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008032 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8033 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008034 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008035 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008036
Alexander Musmana5f070a2014-10-01 06:03:56 +00008037 assert((CurContext->isDependentContext() || B.builtAll()) &&
8038 "omp simd loop exprs were not built");
8039
Alexander Musman3276a272015-03-21 10:12:56 +00008040 if (!CurContext->isDependentContext()) {
8041 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008042 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008043 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00008044 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008045 B.NumIterations, *this, CurScope,
8046 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00008047 return StmtError();
8048 }
8049 }
8050
Kelvin Lic5609492016-07-15 04:39:07 +00008051 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008052 return StmtError();
8053
Reid Kleckner87a31802018-03-12 21:43:02 +00008054 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008055 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8056 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008057}
8058
Alexey Bataeve3727102018-04-18 15:57:46 +00008059StmtResult
8060Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8061 SourceLocation StartLoc, SourceLocation EndLoc,
8062 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008063 if (!AStmt)
8064 return StmtError();
8065
8066 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008067 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008068 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8069 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008070 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008071 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8072 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008073 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00008074 return StmtError();
8075
Alexander Musmana5f070a2014-10-01 06:03:56 +00008076 assert((CurContext->isDependentContext() || B.builtAll()) &&
8077 "omp for loop exprs were not built");
8078
Alexey Bataev54acd402015-08-04 11:18:19 +00008079 if (!CurContext->isDependentContext()) {
8080 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008081 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008082 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008083 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008084 B.NumIterations, *this, CurScope,
8085 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008086 return StmtError();
8087 }
8088 }
8089
Reid Kleckner87a31802018-03-12 21:43:02 +00008090 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008091 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008092 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00008093}
8094
Alexander Musmanf82886e2014-09-18 05:12:34 +00008095StmtResult Sema::ActOnOpenMPForSimdDirective(
8096 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008097 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008098 if (!AStmt)
8099 return StmtError();
8100
8101 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008102 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008103 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8104 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00008105 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008106 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008107 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8108 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008109 if (NestedLoopCount == 0)
8110 return StmtError();
8111
Alexander Musmanc6388682014-12-15 07:07:06 +00008112 assert((CurContext->isDependentContext() || B.builtAll()) &&
8113 "omp for simd loop exprs were not built");
8114
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008115 if (!CurContext->isDependentContext()) {
8116 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008117 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008118 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008119 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008120 B.NumIterations, *this, CurScope,
8121 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008122 return StmtError();
8123 }
8124 }
8125
Kelvin Lic5609492016-07-15 04:39:07 +00008126 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008127 return StmtError();
8128
Reid Kleckner87a31802018-03-12 21:43:02 +00008129 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008130 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8131 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008132}
8133
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008134StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8135 Stmt *AStmt,
8136 SourceLocation StartLoc,
8137 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008138 if (!AStmt)
8139 return StmtError();
8140
8141 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008142 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008143 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008144 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008145 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008146 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008147 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008148 return StmtError();
8149 // All associated statements must be '#pragma omp section' except for
8150 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008151 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008152 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8153 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008154 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008155 diag::err_omp_sections_substmt_not_section);
8156 return StmtError();
8157 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008158 cast<OMPSectionDirective>(SectionStmt)
8159 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008160 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008161 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008162 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008163 return StmtError();
8164 }
8165
Reid Kleckner87a31802018-03-12 21:43:02 +00008166 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008167
Alexey Bataev25e5b442015-09-15 12:52:43 +00008168 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8169 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008170}
8171
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008172StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8173 SourceLocation StartLoc,
8174 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008175 if (!AStmt)
8176 return StmtError();
8177
8178 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008179
Reid Kleckner87a31802018-03-12 21:43:02 +00008180 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008181 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008182
Alexey Bataev25e5b442015-09-15 12:52:43 +00008183 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8184 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008185}
8186
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008187StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8188 Stmt *AStmt,
8189 SourceLocation StartLoc,
8190 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008191 if (!AStmt)
8192 return StmtError();
8193
8194 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008195
Reid Kleckner87a31802018-03-12 21:43:02 +00008196 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008197
Alexey Bataev3255bf32015-01-19 05:20:46 +00008198 // OpenMP [2.7.3, single Construct, Restrictions]
8199 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008200 const OMPClause *Nowait = nullptr;
8201 const OMPClause *Copyprivate = nullptr;
8202 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008203 if (Clause->getClauseKind() == OMPC_nowait)
8204 Nowait = Clause;
8205 else if (Clause->getClauseKind() == OMPC_copyprivate)
8206 Copyprivate = Clause;
8207 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008208 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008209 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008210 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008211 return StmtError();
8212 }
8213 }
8214
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008215 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8216}
8217
Alexander Musman80c22892014-07-17 08:54:58 +00008218StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8219 SourceLocation StartLoc,
8220 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008221 if (!AStmt)
8222 return StmtError();
8223
8224 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008225
Reid Kleckner87a31802018-03-12 21:43:02 +00008226 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008227
8228 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8229}
8230
Alexey Bataev28c75412015-12-15 08:19:24 +00008231StmtResult Sema::ActOnOpenMPCriticalDirective(
8232 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8233 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008234 if (!AStmt)
8235 return StmtError();
8236
8237 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008238
Alexey Bataev28c75412015-12-15 08:19:24 +00008239 bool ErrorFound = false;
8240 llvm::APSInt Hint;
8241 SourceLocation HintLoc;
8242 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008243 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008244 if (C->getClauseKind() == OMPC_hint) {
8245 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008246 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008247 ErrorFound = true;
8248 }
8249 Expr *E = cast<OMPHintClause>(C)->getHint();
8250 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008251 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008252 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008253 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008254 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008255 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008256 }
8257 }
8258 }
8259 if (ErrorFound)
8260 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008261 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008262 if (Pair.first && DirName.getName() && !DependentHint) {
8263 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8264 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008265 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008266 Diag(HintLoc, diag::note_omp_critical_hint_here)
8267 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008268 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008269 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008270 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008271 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008272 << 1
8273 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8274 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008275 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008276 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008277 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008278 }
8279 }
8280
Reid Kleckner87a31802018-03-12 21:43:02 +00008281 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008282
Alexey Bataev28c75412015-12-15 08:19:24 +00008283 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8284 Clauses, AStmt);
8285 if (!Pair.first && DirName.getName() && !DependentHint)
8286 DSAStack->addCriticalWithHint(Dir, Hint);
8287 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008288}
8289
Alexey Bataev4acb8592014-07-07 13:01:15 +00008290StmtResult Sema::ActOnOpenMPParallelForDirective(
8291 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008292 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008293 if (!AStmt)
8294 return StmtError();
8295
Alexey Bataeve3727102018-04-18 15:57:46 +00008296 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008297 // 1.2.2 OpenMP Language Terminology
8298 // Structured block - An executable statement with a single entry at the
8299 // top and a single exit at the bottom.
8300 // The point of exit cannot be a branch out of the structured block.
8301 // longjmp() and throw() must not violate the entry/exit criteria.
8302 CS->getCapturedDecl()->setNothrow();
8303
Alexander Musmanc6388682014-12-15 07:07:06 +00008304 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008305 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8306 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008307 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008308 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008309 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8310 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008311 if (NestedLoopCount == 0)
8312 return StmtError();
8313
Alexander Musmana5f070a2014-10-01 06:03:56 +00008314 assert((CurContext->isDependentContext() || B.builtAll()) &&
8315 "omp parallel for loop exprs were not built");
8316
Alexey Bataev54acd402015-08-04 11:18:19 +00008317 if (!CurContext->isDependentContext()) {
8318 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008319 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008320 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008321 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008322 B.NumIterations, *this, CurScope,
8323 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008324 return StmtError();
8325 }
8326 }
8327
Reid Kleckner87a31802018-03-12 21:43:02 +00008328 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008329 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008330 NestedLoopCount, Clauses, AStmt, B,
8331 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008332}
8333
Alexander Musmane4e893b2014-09-23 09:33:00 +00008334StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8335 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008336 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008337 if (!AStmt)
8338 return StmtError();
8339
Alexey Bataeve3727102018-04-18 15:57:46 +00008340 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008341 // 1.2.2 OpenMP Language Terminology
8342 // Structured block - An executable statement with a single entry at the
8343 // top and a single exit at the bottom.
8344 // The point of exit cannot be a branch out of the structured block.
8345 // longjmp() and throw() must not violate the entry/exit criteria.
8346 CS->getCapturedDecl()->setNothrow();
8347
Alexander Musmanc6388682014-12-15 07:07:06 +00008348 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008349 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8350 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008351 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008352 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008353 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8354 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008355 if (NestedLoopCount == 0)
8356 return StmtError();
8357
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008358 if (!CurContext->isDependentContext()) {
8359 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008360 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008361 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008362 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008363 B.NumIterations, *this, CurScope,
8364 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008365 return StmtError();
8366 }
8367 }
8368
Kelvin Lic5609492016-07-15 04:39:07 +00008369 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008370 return StmtError();
8371
Reid Kleckner87a31802018-03-12 21:43:02 +00008372 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008373 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008374 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008375}
8376
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008377StmtResult
cchen47d60942019-12-05 13:43:48 -05008378Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
8379 Stmt *AStmt, SourceLocation StartLoc,
8380 SourceLocation EndLoc) {
8381 if (!AStmt)
8382 return StmtError();
8383
8384 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8385 auto *CS = cast<CapturedStmt>(AStmt);
8386 // 1.2.2 OpenMP Language Terminology
8387 // Structured block - An executable statement with a single entry at the
8388 // top and a single exit at the bottom.
8389 // The point of exit cannot be a branch out of the structured block.
8390 // longjmp() and throw() must not violate the entry/exit criteria.
8391 CS->getCapturedDecl()->setNothrow();
8392
8393 setFunctionHasBranchProtectedScope();
8394
8395 return OMPParallelMasterDirective::Create(Context, StartLoc, EndLoc, Clauses,
8396 AStmt);
8397}
8398
8399StmtResult
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008400Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8401 Stmt *AStmt, SourceLocation StartLoc,
8402 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008403 if (!AStmt)
8404 return StmtError();
8405
8406 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008407 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008408 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008409 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008410 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008411 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008412 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008413 return StmtError();
8414 // All associated statements must be '#pragma omp section' except for
8415 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008416 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008417 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8418 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008419 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008420 diag::err_omp_parallel_sections_substmt_not_section);
8421 return StmtError();
8422 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008423 cast<OMPSectionDirective>(SectionStmt)
8424 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008425 }
8426 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008427 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008428 diag::err_omp_parallel_sections_not_compound_stmt);
8429 return StmtError();
8430 }
8431
Reid Kleckner87a31802018-03-12 21:43:02 +00008432 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008433
Alexey Bataev25e5b442015-09-15 12:52:43 +00008434 return OMPParallelSectionsDirective::Create(
8435 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008436}
8437
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008438StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8439 Stmt *AStmt, SourceLocation StartLoc,
8440 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008441 if (!AStmt)
8442 return StmtError();
8443
David Majnemer9d168222016-08-05 17:44:54 +00008444 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008445 // 1.2.2 OpenMP Language Terminology
8446 // Structured block - An executable statement with a single entry at the
8447 // top and a single exit at the bottom.
8448 // The point of exit cannot be a branch out of the structured block.
8449 // longjmp() and throw() must not violate the entry/exit criteria.
8450 CS->getCapturedDecl()->setNothrow();
8451
Reid Kleckner87a31802018-03-12 21:43:02 +00008452 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008453
Alexey Bataev25e5b442015-09-15 12:52:43 +00008454 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8455 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008456}
8457
Alexey Bataev68446b72014-07-18 07:47:19 +00008458StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8459 SourceLocation EndLoc) {
8460 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8461}
8462
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008463StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8464 SourceLocation EndLoc) {
8465 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8466}
8467
Alexey Bataev2df347a2014-07-18 10:17:07 +00008468StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8469 SourceLocation EndLoc) {
8470 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8471}
8472
Alexey Bataev169d96a2017-07-18 20:17:46 +00008473StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8474 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008475 SourceLocation StartLoc,
8476 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008477 if (!AStmt)
8478 return StmtError();
8479
8480 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008481
Reid Kleckner87a31802018-03-12 21:43:02 +00008482 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008483
Alexey Bataev169d96a2017-07-18 20:17:46 +00008484 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008485 AStmt,
8486 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008487}
8488
Alexey Bataev6125da92014-07-21 11:26:11 +00008489StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8490 SourceLocation StartLoc,
8491 SourceLocation EndLoc) {
8492 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8493 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8494}
8495
Alexey Bataev346265e2015-09-25 10:37:12 +00008496StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8497 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008498 SourceLocation StartLoc,
8499 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008500 const OMPClause *DependFound = nullptr;
8501 const OMPClause *DependSourceClause = nullptr;
8502 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008503 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008504 const OMPThreadsClause *TC = nullptr;
8505 const OMPSIMDClause *SC = nullptr;
8506 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008507 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8508 DependFound = C;
8509 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8510 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008511 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008512 << getOpenMPDirectiveName(OMPD_ordered)
8513 << getOpenMPClauseName(OMPC_depend) << 2;
8514 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008515 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008516 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008517 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008518 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008519 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008520 << 0;
8521 ErrorFound = true;
8522 }
8523 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8524 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008525 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008526 << 1;
8527 ErrorFound = true;
8528 }
8529 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008530 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008531 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008532 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008533 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008534 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008535 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008536 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008537 if (!ErrorFound && !SC &&
8538 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008539 // OpenMP [2.8.1,simd Construct, Restrictions]
8540 // An ordered construct with the simd clause is the only OpenMP construct
8541 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008542 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8543 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008544 ErrorFound = true;
8545 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008546 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008547 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8548 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008549 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008550 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008551 diag::err_omp_ordered_directive_without_param);
8552 ErrorFound = true;
8553 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008554 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008555 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008556 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8557 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008558 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008559 ErrorFound = true;
8560 }
8561 }
8562 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008563 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008564
8565 if (AStmt) {
8566 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8567
Reid Kleckner87a31802018-03-12 21:43:02 +00008568 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008569 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008570
8571 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008572}
8573
Alexey Bataev1d160b12015-03-13 12:27:31 +00008574namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008575/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008576/// construct.
8577class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008578 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008579 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008580 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008581 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008582 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008583 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008584 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008585 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008586 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008587 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008588 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008589 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008590 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008591 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008592 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008593 /// expression.
8594 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008595 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008596 /// part.
8597 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008598 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008599 NoError
8600 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008601 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008602 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008603 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008604 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008605 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008606 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008607 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008608 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008609 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008610 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8611 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8612 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008613 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008614 /// important for non-associative operations.
8615 bool IsXLHSInRHSPart;
8616 BinaryOperatorKind Op;
8617 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008618 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008619 /// if it is a prefix unary operation.
8620 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008621
8622public:
8623 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008624 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008625 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008626 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008627 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008628 /// expression. If DiagId and NoteId == 0, then only check is performed
8629 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008630 /// \param DiagId Diagnostic which should be emitted if error is found.
8631 /// \param NoteId Diagnostic note for the main error message.
8632 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008633 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008634 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008635 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008636 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008637 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008638 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008639 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8640 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8641 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008642 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008643 /// false otherwise.
8644 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8645
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008646 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008647 /// if it is a prefix unary operation.
8648 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8649
Alexey Bataev1d160b12015-03-13 12:27:31 +00008650private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008651 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8652 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008653};
8654} // namespace
8655
8656bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8657 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8658 ExprAnalysisErrorCode ErrorFound = NoError;
8659 SourceLocation ErrorLoc, NoteLoc;
8660 SourceRange ErrorRange, NoteRange;
8661 // Allowed constructs are:
8662 // x = x binop expr;
8663 // x = expr binop x;
8664 if (AtomicBinOp->getOpcode() == BO_Assign) {
8665 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008666 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008667 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8668 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8669 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8670 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008671 Op = AtomicInnerBinOp->getOpcode();
8672 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008673 Expr *LHS = AtomicInnerBinOp->getLHS();
8674 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008675 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8676 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8677 /*Canonical=*/true);
8678 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8679 /*Canonical=*/true);
8680 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8681 /*Canonical=*/true);
8682 if (XId == LHSId) {
8683 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008684 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008685 } else if (XId == RHSId) {
8686 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008687 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008688 } else {
8689 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8690 ErrorRange = AtomicInnerBinOp->getSourceRange();
8691 NoteLoc = X->getExprLoc();
8692 NoteRange = X->getSourceRange();
8693 ErrorFound = NotAnUpdateExpression;
8694 }
8695 } else {
8696 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8697 ErrorRange = AtomicInnerBinOp->getSourceRange();
8698 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8699 NoteRange = SourceRange(NoteLoc, NoteLoc);
8700 ErrorFound = NotABinaryOperator;
8701 }
8702 } else {
8703 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8704 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8705 ErrorFound = NotABinaryExpression;
8706 }
8707 } else {
8708 ErrorLoc = AtomicBinOp->getExprLoc();
8709 ErrorRange = AtomicBinOp->getSourceRange();
8710 NoteLoc = AtomicBinOp->getOperatorLoc();
8711 NoteRange = SourceRange(NoteLoc, NoteLoc);
8712 ErrorFound = NotAnAssignmentOp;
8713 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008714 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008715 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8716 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8717 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008718 }
8719 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008720 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008721 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008722}
8723
8724bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8725 unsigned NoteId) {
8726 ExprAnalysisErrorCode ErrorFound = NoError;
8727 SourceLocation ErrorLoc, NoteLoc;
8728 SourceRange ErrorRange, NoteRange;
8729 // Allowed constructs are:
8730 // x++;
8731 // x--;
8732 // ++x;
8733 // --x;
8734 // x binop= expr;
8735 // x = x binop expr;
8736 // x = expr binop x;
8737 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8738 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8739 if (AtomicBody->getType()->isScalarType() ||
8740 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008741 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008742 AtomicBody->IgnoreParenImpCasts())) {
8743 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008744 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008745 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008746 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008747 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008748 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008749 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008750 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8751 AtomicBody->IgnoreParenImpCasts())) {
8752 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008753 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008754 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008755 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008756 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008757 // Check for Unary Operation
8758 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008759 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008760 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8761 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008762 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008763 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8764 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008765 } else {
8766 ErrorFound = NotAnUnaryIncDecExpression;
8767 ErrorLoc = AtomicUnaryOp->getExprLoc();
8768 ErrorRange = AtomicUnaryOp->getSourceRange();
8769 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8770 NoteRange = SourceRange(NoteLoc, NoteLoc);
8771 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008772 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008773 ErrorFound = NotABinaryOrUnaryExpression;
8774 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8775 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8776 }
8777 } else {
8778 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008779 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008780 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8781 }
8782 } else {
8783 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008784 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008785 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8786 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008787 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008788 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8789 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8790 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008791 }
8792 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008793 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008794 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008795 // Build an update expression of form 'OpaqueValueExpr(x) binop
8796 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8797 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8798 auto *OVEX = new (SemaRef.getASTContext())
8799 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8800 auto *OVEExpr = new (SemaRef.getASTContext())
8801 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008802 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008803 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8804 IsXLHSInRHSPart ? OVEExpr : OVEX);
8805 if (Update.isInvalid())
8806 return true;
8807 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8808 Sema::AA_Casting);
8809 if (Update.isInvalid())
8810 return true;
8811 UpdateExpr = Update.get();
8812 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008813 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008814}
8815
Alexey Bataev0162e452014-07-22 10:10:35 +00008816StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8817 Stmt *AStmt,
8818 SourceLocation StartLoc,
8819 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008820 if (!AStmt)
8821 return StmtError();
8822
David Majnemer9d168222016-08-05 17:44:54 +00008823 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008824 // 1.2.2 OpenMP Language Terminology
8825 // Structured block - An executable statement with a single entry at the
8826 // top and a single exit at the bottom.
8827 // The point of exit cannot be a branch out of the structured block.
8828 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008829 OpenMPClauseKind AtomicKind = OMPC_unknown;
8830 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008831 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008832 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008833 C->getClauseKind() == OMPC_update ||
8834 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008835 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008836 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008837 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008838 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8839 << getOpenMPClauseName(AtomicKind);
8840 } else {
8841 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008842 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008843 }
8844 }
8845 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008846
Alexey Bataeve3727102018-04-18 15:57:46 +00008847 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008848 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8849 Body = EWC->getSubExpr();
8850
Alexey Bataev62cec442014-11-18 10:14:22 +00008851 Expr *X = nullptr;
8852 Expr *V = nullptr;
8853 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008854 Expr *UE = nullptr;
8855 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008856 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008857 // OpenMP [2.12.6, atomic Construct]
8858 // In the next expressions:
8859 // * x and v (as applicable) are both l-value expressions with scalar type.
8860 // * During the execution of an atomic region, multiple syntactic
8861 // occurrences of x must designate the same storage location.
8862 // * Neither of v and expr (as applicable) may access the storage location
8863 // designated by x.
8864 // * Neither of x and expr (as applicable) may access the storage location
8865 // designated by v.
8866 // * expr is an expression with scalar type.
8867 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8868 // * binop, binop=, ++, and -- are not overloaded operators.
8869 // * The expression x binop expr must be numerically equivalent to x binop
8870 // (expr). This requirement is satisfied if the operators in expr have
8871 // precedence greater than binop, or by using parentheses around expr or
8872 // subexpressions of expr.
8873 // * The expression expr binop x must be numerically equivalent to (expr)
8874 // binop x. This requirement is satisfied if the operators in expr have
8875 // precedence equal to or greater than binop, or by using parentheses around
8876 // expr or subexpressions of expr.
8877 // * For forms that allow multiple occurrences of x, the number of times
8878 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008879 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008880 enum {
8881 NotAnExpression,
8882 NotAnAssignmentOp,
8883 NotAScalarType,
8884 NotAnLValue,
8885 NoError
8886 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008887 SourceLocation ErrorLoc, NoteLoc;
8888 SourceRange ErrorRange, NoteRange;
8889 // If clause is read:
8890 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008891 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8892 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008893 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8894 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8895 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8896 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8897 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8898 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8899 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008900 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008901 ErrorFound = NotAnLValue;
8902 ErrorLoc = AtomicBinOp->getExprLoc();
8903 ErrorRange = AtomicBinOp->getSourceRange();
8904 NoteLoc = NotLValueExpr->getExprLoc();
8905 NoteRange = NotLValueExpr->getSourceRange();
8906 }
8907 } else if (!X->isInstantiationDependent() ||
8908 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008909 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008910 (X->isInstantiationDependent() || X->getType()->isScalarType())
8911 ? V
8912 : X;
8913 ErrorFound = NotAScalarType;
8914 ErrorLoc = AtomicBinOp->getExprLoc();
8915 ErrorRange = AtomicBinOp->getSourceRange();
8916 NoteLoc = NotScalarExpr->getExprLoc();
8917 NoteRange = NotScalarExpr->getSourceRange();
8918 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008919 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008920 ErrorFound = NotAnAssignmentOp;
8921 ErrorLoc = AtomicBody->getExprLoc();
8922 ErrorRange = AtomicBody->getSourceRange();
8923 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8924 : AtomicBody->getExprLoc();
8925 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8926 : AtomicBody->getSourceRange();
8927 }
8928 } else {
8929 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008930 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008931 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008932 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008933 if (ErrorFound != NoError) {
8934 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8935 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008936 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8937 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008938 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008939 }
8940 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008941 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008942 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008943 enum {
8944 NotAnExpression,
8945 NotAnAssignmentOp,
8946 NotAScalarType,
8947 NotAnLValue,
8948 NoError
8949 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008950 SourceLocation ErrorLoc, NoteLoc;
8951 SourceRange ErrorRange, NoteRange;
8952 // If clause is write:
8953 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008954 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8955 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008956 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8957 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008958 X = AtomicBinOp->getLHS();
8959 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008960 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8961 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8962 if (!X->isLValue()) {
8963 ErrorFound = NotAnLValue;
8964 ErrorLoc = AtomicBinOp->getExprLoc();
8965 ErrorRange = AtomicBinOp->getSourceRange();
8966 NoteLoc = X->getExprLoc();
8967 NoteRange = X->getSourceRange();
8968 }
8969 } else if (!X->isInstantiationDependent() ||
8970 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008971 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008972 (X->isInstantiationDependent() || X->getType()->isScalarType())
8973 ? E
8974 : X;
8975 ErrorFound = NotAScalarType;
8976 ErrorLoc = AtomicBinOp->getExprLoc();
8977 ErrorRange = AtomicBinOp->getSourceRange();
8978 NoteLoc = NotScalarExpr->getExprLoc();
8979 NoteRange = NotScalarExpr->getSourceRange();
8980 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008981 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008982 ErrorFound = NotAnAssignmentOp;
8983 ErrorLoc = AtomicBody->getExprLoc();
8984 ErrorRange = AtomicBody->getSourceRange();
8985 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8986 : AtomicBody->getExprLoc();
8987 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8988 : AtomicBody->getSourceRange();
8989 }
8990 } else {
8991 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008992 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008993 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008994 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008995 if (ErrorFound != NoError) {
8996 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8997 << ErrorRange;
8998 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8999 << NoteRange;
9000 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00009001 }
9002 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00009003 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009004 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00009005 // If clause is update:
9006 // x++;
9007 // x--;
9008 // ++x;
9009 // --x;
9010 // x binop= expr;
9011 // x = x binop expr;
9012 // x = expr binop x;
9013 OpenMPAtomicUpdateChecker Checker(*this);
9014 if (Checker.checkStatement(
9015 Body, (AtomicKind == OMPC_update)
9016 ? diag::err_omp_atomic_update_not_expression_statement
9017 : diag::err_omp_atomic_not_expression_statement,
9018 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00009019 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00009020 if (!CurContext->isDependentContext()) {
9021 E = Checker.getExpr();
9022 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00009023 UE = Checker.getUpdateExpr();
9024 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00009025 }
Alexey Bataev459dec02014-07-24 06:46:57 +00009026 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009027 enum {
9028 NotAnAssignmentOp,
9029 NotACompoundStatement,
9030 NotTwoSubstatements,
9031 NotASpecificExpression,
9032 NoError
9033 } ErrorFound = NoError;
9034 SourceLocation ErrorLoc, NoteLoc;
9035 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009036 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009037 // If clause is a capture:
9038 // v = x++;
9039 // v = x--;
9040 // v = ++x;
9041 // v = --x;
9042 // v = x binop= expr;
9043 // v = x = x binop expr;
9044 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00009045 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00009046 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9047 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9048 V = AtomicBinOp->getLHS();
9049 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9050 OpenMPAtomicUpdateChecker Checker(*this);
9051 if (Checker.checkStatement(
9052 Body, diag::err_omp_atomic_capture_not_expression_statement,
9053 diag::note_omp_atomic_update))
9054 return StmtError();
9055 E = Checker.getExpr();
9056 X = Checker.getX();
9057 UE = Checker.getUpdateExpr();
9058 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9059 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00009060 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009061 ErrorLoc = AtomicBody->getExprLoc();
9062 ErrorRange = AtomicBody->getSourceRange();
9063 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9064 : AtomicBody->getExprLoc();
9065 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9066 : AtomicBody->getSourceRange();
9067 ErrorFound = NotAnAssignmentOp;
9068 }
9069 if (ErrorFound != NoError) {
9070 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9071 << ErrorRange;
9072 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9073 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009074 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009075 if (CurContext->isDependentContext())
9076 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009077 } else {
9078 // If clause is a capture:
9079 // { v = x; x = expr; }
9080 // { v = x; x++; }
9081 // { v = x; x--; }
9082 // { v = x; ++x; }
9083 // { v = x; --x; }
9084 // { v = x; x binop= expr; }
9085 // { v = x; x = x binop expr; }
9086 // { v = x; x = expr binop x; }
9087 // { x++; v = x; }
9088 // { x--; v = x; }
9089 // { ++x; v = x; }
9090 // { --x; v = x; }
9091 // { x binop= expr; v = x; }
9092 // { x = x binop expr; v = x; }
9093 // { x = expr binop x; v = x; }
9094 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9095 // Check that this is { expr1; expr2; }
9096 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009097 Stmt *First = CS->body_front();
9098 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009099 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9100 First = EWC->getSubExpr()->IgnoreParenImpCasts();
9101 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9102 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9103 // Need to find what subexpression is 'v' and what is 'x'.
9104 OpenMPAtomicUpdateChecker Checker(*this);
9105 bool IsUpdateExprFound = !Checker.checkStatement(Second);
9106 BinaryOperator *BinOp = nullptr;
9107 if (IsUpdateExprFound) {
9108 BinOp = dyn_cast<BinaryOperator>(First);
9109 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9110 }
9111 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9112 // { v = x; x++; }
9113 // { v = x; x--; }
9114 // { v = x; ++x; }
9115 // { v = x; --x; }
9116 // { v = x; x binop= expr; }
9117 // { v = x; x = x binop expr; }
9118 // { v = x; x = expr binop x; }
9119 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009120 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009121 llvm::FoldingSetNodeID XId, PossibleXId;
9122 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9123 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9124 IsUpdateExprFound = XId == PossibleXId;
9125 if (IsUpdateExprFound) {
9126 V = BinOp->getLHS();
9127 X = Checker.getX();
9128 E = Checker.getExpr();
9129 UE = Checker.getUpdateExpr();
9130 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009131 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009132 }
9133 }
9134 if (!IsUpdateExprFound) {
9135 IsUpdateExprFound = !Checker.checkStatement(First);
9136 BinOp = nullptr;
9137 if (IsUpdateExprFound) {
9138 BinOp = dyn_cast<BinaryOperator>(Second);
9139 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9140 }
9141 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9142 // { x++; v = x; }
9143 // { x--; v = x; }
9144 // { ++x; v = x; }
9145 // { --x; v = x; }
9146 // { x binop= expr; v = x; }
9147 // { x = x binop expr; v = x; }
9148 // { x = expr binop x; v = x; }
9149 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009150 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009151 llvm::FoldingSetNodeID XId, PossibleXId;
9152 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9153 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9154 IsUpdateExprFound = XId == PossibleXId;
9155 if (IsUpdateExprFound) {
9156 V = BinOp->getLHS();
9157 X = Checker.getX();
9158 E = Checker.getExpr();
9159 UE = Checker.getUpdateExpr();
9160 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009161 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009162 }
9163 }
9164 }
9165 if (!IsUpdateExprFound) {
9166 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009167 auto *FirstExpr = dyn_cast<Expr>(First);
9168 auto *SecondExpr = dyn_cast<Expr>(Second);
9169 if (!FirstExpr || !SecondExpr ||
9170 !(FirstExpr->isInstantiationDependent() ||
9171 SecondExpr->isInstantiationDependent())) {
9172 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9173 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009174 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009175 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009176 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009177 NoteRange = ErrorRange = FirstBinOp
9178 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009179 : SourceRange(ErrorLoc, ErrorLoc);
9180 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009181 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9182 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9183 ErrorFound = NotAnAssignmentOp;
9184 NoteLoc = ErrorLoc = SecondBinOp
9185 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009186 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009187 NoteRange = ErrorRange =
9188 SecondBinOp ? SecondBinOp->getSourceRange()
9189 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009190 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009191 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009192 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009193 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009194 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9195 llvm::FoldingSetNodeID X1Id, X2Id;
9196 PossibleXRHSInFirst->Profile(X1Id, Context,
9197 /*Canonical=*/true);
9198 PossibleXLHSInSecond->Profile(X2Id, Context,
9199 /*Canonical=*/true);
9200 IsUpdateExprFound = X1Id == X2Id;
9201 if (IsUpdateExprFound) {
9202 V = FirstBinOp->getLHS();
9203 X = SecondBinOp->getLHS();
9204 E = SecondBinOp->getRHS();
9205 UE = nullptr;
9206 IsXLHSInRHSPart = false;
9207 IsPostfixUpdate = true;
9208 } else {
9209 ErrorFound = NotASpecificExpression;
9210 ErrorLoc = FirstBinOp->getExprLoc();
9211 ErrorRange = FirstBinOp->getSourceRange();
9212 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9213 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9214 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009215 }
9216 }
9217 }
9218 }
9219 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009220 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009221 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009222 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009223 ErrorFound = NotTwoSubstatements;
9224 }
9225 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009226 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009227 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009228 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009229 ErrorFound = NotACompoundStatement;
9230 }
9231 if (ErrorFound != NoError) {
9232 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9233 << ErrorRange;
9234 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9235 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009236 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009237 if (CurContext->isDependentContext())
9238 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009239 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009240 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009241
Reid Kleckner87a31802018-03-12 21:43:02 +00009242 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009243
Alexey Bataev62cec442014-11-18 10:14:22 +00009244 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009245 X, V, E, UE, IsXLHSInRHSPart,
9246 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009247}
9248
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009249StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9250 Stmt *AStmt,
9251 SourceLocation StartLoc,
9252 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009253 if (!AStmt)
9254 return StmtError();
9255
Alexey Bataeve3727102018-04-18 15:57:46 +00009256 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009257 // 1.2.2 OpenMP Language Terminology
9258 // Structured block - An executable statement with a single entry at the
9259 // top and a single exit at the bottom.
9260 // The point of exit cannot be a branch out of the structured block.
9261 // longjmp() and throw() must not violate the entry/exit criteria.
9262 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009263 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9264 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9265 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9266 // 1.2.2 OpenMP Language Terminology
9267 // Structured block - An executable statement with a single entry at the
9268 // top and a single exit at the bottom.
9269 // The point of exit cannot be a branch out of the structured block.
9270 // longjmp() and throw() must not violate the entry/exit criteria.
9271 CS->getCapturedDecl()->setNothrow();
9272 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009273
Alexey Bataev13314bf2014-10-09 04:18:56 +00009274 // OpenMP [2.16, Nesting of Regions]
9275 // If specified, a teams construct must be contained within a target
9276 // construct. That target construct must contain no statements or directives
9277 // outside of the teams construct.
9278 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009279 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009280 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009281 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009282 auto I = CS->body_begin();
9283 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009284 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009285 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9286 OMPTeamsFound) {
9287
Alexey Bataev13314bf2014-10-09 04:18:56 +00009288 OMPTeamsFound = false;
9289 break;
9290 }
9291 ++I;
9292 }
9293 assert(I != CS->body_end() && "Not found statement");
9294 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009295 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009296 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009297 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009298 }
9299 if (!OMPTeamsFound) {
9300 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9301 Diag(DSAStack->getInnerTeamsRegionLoc(),
9302 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009303 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009304 << isa<OMPExecutableDirective>(S);
9305 return StmtError();
9306 }
9307 }
9308
Reid Kleckner87a31802018-03-12 21:43:02 +00009309 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009310
9311 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9312}
9313
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009314StmtResult
9315Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9316 Stmt *AStmt, SourceLocation StartLoc,
9317 SourceLocation EndLoc) {
9318 if (!AStmt)
9319 return StmtError();
9320
Alexey Bataeve3727102018-04-18 15:57:46 +00009321 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009322 // 1.2.2 OpenMP Language Terminology
9323 // Structured block - An executable statement with a single entry at the
9324 // top and a single exit at the bottom.
9325 // The point of exit cannot be a branch out of the structured block.
9326 // longjmp() and throw() must not violate the entry/exit criteria.
9327 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009328 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9329 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9330 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9331 // 1.2.2 OpenMP Language Terminology
9332 // Structured block - An executable statement with a single entry at the
9333 // top and a single exit at the bottom.
9334 // The point of exit cannot be a branch out of the structured block.
9335 // longjmp() and throw() must not violate the entry/exit criteria.
9336 CS->getCapturedDecl()->setNothrow();
9337 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009338
Reid Kleckner87a31802018-03-12 21:43:02 +00009339 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009340
9341 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9342 AStmt);
9343}
9344
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009345StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9346 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009347 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009348 if (!AStmt)
9349 return StmtError();
9350
Alexey Bataeve3727102018-04-18 15:57:46 +00009351 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009352 // 1.2.2 OpenMP Language Terminology
9353 // Structured block - An executable statement with a single entry at the
9354 // top and a single exit at the bottom.
9355 // The point of exit cannot be a branch out of the structured block.
9356 // longjmp() and throw() must not violate the entry/exit criteria.
9357 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009358 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9359 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9360 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9361 // 1.2.2 OpenMP Language Terminology
9362 // Structured block - An executable statement with a single entry at the
9363 // top and a single exit at the bottom.
9364 // The point of exit cannot be a branch out of the structured block.
9365 // longjmp() and throw() must not violate the entry/exit criteria.
9366 CS->getCapturedDecl()->setNothrow();
9367 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009368
9369 OMPLoopDirective::HelperExprs B;
9370 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9371 // define the nested loops number.
9372 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009373 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009374 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009375 VarsWithImplicitDSA, B);
9376 if (NestedLoopCount == 0)
9377 return StmtError();
9378
9379 assert((CurContext->isDependentContext() || B.builtAll()) &&
9380 "omp target parallel for loop exprs were not built");
9381
9382 if (!CurContext->isDependentContext()) {
9383 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009384 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009385 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009386 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009387 B.NumIterations, *this, CurScope,
9388 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009389 return StmtError();
9390 }
9391 }
9392
Reid Kleckner87a31802018-03-12 21:43:02 +00009393 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009394 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9395 NestedLoopCount, Clauses, AStmt,
9396 B, DSAStack->isCancelRegion());
9397}
9398
Alexey Bataev95b64a92017-05-30 16:00:04 +00009399/// Check for existence of a map clause in the list of clauses.
9400static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9401 const OpenMPClauseKind K) {
9402 return llvm::any_of(
9403 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9404}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009405
Alexey Bataev95b64a92017-05-30 16:00:04 +00009406template <typename... Params>
9407static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9408 const Params... ClauseTypes) {
9409 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009410}
9411
Michael Wong65f367f2015-07-21 13:44:28 +00009412StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9413 Stmt *AStmt,
9414 SourceLocation StartLoc,
9415 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009416 if (!AStmt)
9417 return StmtError();
9418
9419 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9420
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009421 // OpenMP [2.10.1, Restrictions, p. 97]
9422 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009423 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9424 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9425 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009426 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009427 return StmtError();
9428 }
9429
Reid Kleckner87a31802018-03-12 21:43:02 +00009430 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009431
9432 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9433 AStmt);
9434}
9435
Samuel Antaodf67fc42016-01-19 19:15:56 +00009436StmtResult
9437Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9438 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009439 SourceLocation EndLoc, Stmt *AStmt) {
9440 if (!AStmt)
9441 return StmtError();
9442
Alexey Bataeve3727102018-04-18 15:57:46 +00009443 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009444 // 1.2.2 OpenMP Language Terminology
9445 // Structured block - An executable statement with a single entry at the
9446 // top and a single exit at the bottom.
9447 // The point of exit cannot be a branch out of the structured block.
9448 // longjmp() and throw() must not violate the entry/exit criteria.
9449 CS->getCapturedDecl()->setNothrow();
9450 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9451 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9452 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9453 // 1.2.2 OpenMP Language Terminology
9454 // Structured block - An executable statement with a single entry at the
9455 // top and a single exit at the bottom.
9456 // The point of exit cannot be a branch out of the structured block.
9457 // longjmp() and throw() must not violate the entry/exit criteria.
9458 CS->getCapturedDecl()->setNothrow();
9459 }
9460
Samuel Antaodf67fc42016-01-19 19:15:56 +00009461 // OpenMP [2.10.2, Restrictions, p. 99]
9462 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009463 if (!hasClauses(Clauses, OMPC_map)) {
9464 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9465 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009466 return StmtError();
9467 }
9468
Alexey Bataev7828b252017-11-21 17:08:48 +00009469 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9470 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009471}
9472
Samuel Antao72590762016-01-19 20:04:50 +00009473StmtResult
9474Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9475 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009476 SourceLocation EndLoc, Stmt *AStmt) {
9477 if (!AStmt)
9478 return StmtError();
9479
Alexey Bataeve3727102018-04-18 15:57:46 +00009480 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009481 // 1.2.2 OpenMP Language Terminology
9482 // Structured block - An executable statement with a single entry at the
9483 // top and a single exit at the bottom.
9484 // The point of exit cannot be a branch out of the structured block.
9485 // longjmp() and throw() must not violate the entry/exit criteria.
9486 CS->getCapturedDecl()->setNothrow();
9487 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9488 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9489 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9490 // 1.2.2 OpenMP Language Terminology
9491 // Structured block - An executable statement with a single entry at the
9492 // top and a single exit at the bottom.
9493 // The point of exit cannot be a branch out of the structured block.
9494 // longjmp() and throw() must not violate the entry/exit criteria.
9495 CS->getCapturedDecl()->setNothrow();
9496 }
9497
Samuel Antao72590762016-01-19 20:04:50 +00009498 // OpenMP [2.10.3, Restrictions, p. 102]
9499 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009500 if (!hasClauses(Clauses, OMPC_map)) {
9501 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9502 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009503 return StmtError();
9504 }
9505
Alexey Bataev7828b252017-11-21 17:08:48 +00009506 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9507 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009508}
9509
Samuel Antao686c70c2016-05-26 17:30:50 +00009510StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9511 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009512 SourceLocation EndLoc,
9513 Stmt *AStmt) {
9514 if (!AStmt)
9515 return StmtError();
9516
Alexey Bataeve3727102018-04-18 15:57:46 +00009517 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009518 // 1.2.2 OpenMP Language Terminology
9519 // Structured block - An executable statement with a single entry at the
9520 // top and a single exit at the bottom.
9521 // The point of exit cannot be a branch out of the structured block.
9522 // longjmp() and throw() must not violate the entry/exit criteria.
9523 CS->getCapturedDecl()->setNothrow();
9524 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9525 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9526 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9527 // 1.2.2 OpenMP Language Terminology
9528 // Structured block - An executable statement with a single entry at the
9529 // top and a single exit at the bottom.
9530 // The point of exit cannot be a branch out of the structured block.
9531 // longjmp() and throw() must not violate the entry/exit criteria.
9532 CS->getCapturedDecl()->setNothrow();
9533 }
9534
Alexey Bataev95b64a92017-05-30 16:00:04 +00009535 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009536 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9537 return StmtError();
9538 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009539 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9540 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009541}
9542
Alexey Bataev13314bf2014-10-09 04:18:56 +00009543StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9544 Stmt *AStmt, SourceLocation StartLoc,
9545 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009546 if (!AStmt)
9547 return StmtError();
9548
Alexey Bataeve3727102018-04-18 15:57:46 +00009549 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009550 // 1.2.2 OpenMP Language Terminology
9551 // Structured block - An executable statement with a single entry at the
9552 // top and a single exit at the bottom.
9553 // The point of exit cannot be a branch out of the structured block.
9554 // longjmp() and throw() must not violate the entry/exit criteria.
9555 CS->getCapturedDecl()->setNothrow();
9556
Reid Kleckner87a31802018-03-12 21:43:02 +00009557 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009558
Alexey Bataevceabd412017-11-30 18:01:54 +00009559 DSAStack->setParentTeamsRegionLoc(StartLoc);
9560
Alexey Bataev13314bf2014-10-09 04:18:56 +00009561 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9562}
9563
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009564StmtResult
9565Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9566 SourceLocation EndLoc,
9567 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009568 if (DSAStack->isParentNowaitRegion()) {
9569 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9570 return StmtError();
9571 }
9572 if (DSAStack->isParentOrderedRegion()) {
9573 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9574 return StmtError();
9575 }
9576 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9577 CancelRegion);
9578}
9579
Alexey Bataev87933c72015-09-18 08:07:34 +00009580StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9581 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009582 SourceLocation EndLoc,
9583 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009584 if (DSAStack->isParentNowaitRegion()) {
9585 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9586 return StmtError();
9587 }
9588 if (DSAStack->isParentOrderedRegion()) {
9589 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9590 return StmtError();
9591 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009592 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009593 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9594 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009595}
9596
Alexey Bataev382967a2015-12-08 12:06:20 +00009597static bool checkGrainsizeNumTasksClauses(Sema &S,
9598 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009599 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009600 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009601 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009602 if (C->getClauseKind() == OMPC_grainsize ||
9603 C->getClauseKind() == OMPC_num_tasks) {
9604 if (!PrevClause)
9605 PrevClause = C;
9606 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009607 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009608 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9609 << getOpenMPClauseName(C->getClauseKind())
9610 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009611 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009612 diag::note_omp_previous_grainsize_num_tasks)
9613 << getOpenMPClauseName(PrevClause->getClauseKind());
9614 ErrorFound = true;
9615 }
9616 }
9617 }
9618 return ErrorFound;
9619}
9620
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009621static bool checkReductionClauseWithNogroup(Sema &S,
9622 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009623 const OMPClause *ReductionClause = nullptr;
9624 const OMPClause *NogroupClause = nullptr;
9625 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009626 if (C->getClauseKind() == OMPC_reduction) {
9627 ReductionClause = C;
9628 if (NogroupClause)
9629 break;
9630 continue;
9631 }
9632 if (C->getClauseKind() == OMPC_nogroup) {
9633 NogroupClause = C;
9634 if (ReductionClause)
9635 break;
9636 continue;
9637 }
9638 }
9639 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009640 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9641 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009642 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009643 return true;
9644 }
9645 return false;
9646}
9647
Alexey Bataev49f6e782015-12-01 04:18:41 +00009648StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9649 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009650 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009651 if (!AStmt)
9652 return StmtError();
9653
9654 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9655 OMPLoopDirective::HelperExprs B;
9656 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9657 // define the nested loops number.
9658 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009659 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009660 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009661 VarsWithImplicitDSA, B);
9662 if (NestedLoopCount == 0)
9663 return StmtError();
9664
9665 assert((CurContext->isDependentContext() || B.builtAll()) &&
9666 "omp for loop exprs were not built");
9667
Alexey Bataev382967a2015-12-08 12:06:20 +00009668 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9669 // The grainsize clause and num_tasks clause are mutually exclusive and may
9670 // not appear on the same taskloop directive.
9671 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9672 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009673 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9674 // If a reduction clause is present on the taskloop directive, the nogroup
9675 // clause must not be specified.
9676 if (checkReductionClauseWithNogroup(*this, Clauses))
9677 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009678
Reid Kleckner87a31802018-03-12 21:43:02 +00009679 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009680 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9681 NestedLoopCount, Clauses, AStmt, B);
9682}
9683
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009684StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9685 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009686 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009687 if (!AStmt)
9688 return StmtError();
9689
9690 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9691 OMPLoopDirective::HelperExprs B;
9692 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9693 // define the nested loops number.
9694 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009695 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009696 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9697 VarsWithImplicitDSA, B);
9698 if (NestedLoopCount == 0)
9699 return StmtError();
9700
9701 assert((CurContext->isDependentContext() || B.builtAll()) &&
9702 "omp for loop exprs were not built");
9703
Alexey Bataev5a3af132016-03-29 08:58:54 +00009704 if (!CurContext->isDependentContext()) {
9705 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009706 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009707 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009708 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009709 B.NumIterations, *this, CurScope,
9710 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009711 return StmtError();
9712 }
9713 }
9714
Alexey Bataev382967a2015-12-08 12:06:20 +00009715 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9716 // The grainsize clause and num_tasks clause are mutually exclusive and may
9717 // not appear on the same taskloop directive.
9718 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9719 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009720 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9721 // If a reduction clause is present on the taskloop directive, the nogroup
9722 // clause must not be specified.
9723 if (checkReductionClauseWithNogroup(*this, Clauses))
9724 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009725 if (checkSimdlenSafelenSpecified(*this, Clauses))
9726 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009727
Reid Kleckner87a31802018-03-12 21:43:02 +00009728 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009729 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9730 NestedLoopCount, Clauses, AStmt, B);
9731}
9732
Alexey Bataev60e51c42019-10-10 20:13:02 +00009733StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9734 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9735 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9736 if (!AStmt)
9737 return StmtError();
9738
9739 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9740 OMPLoopDirective::HelperExprs B;
9741 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9742 // define the nested loops number.
9743 unsigned NestedLoopCount =
9744 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9745 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9746 VarsWithImplicitDSA, B);
9747 if (NestedLoopCount == 0)
9748 return StmtError();
9749
9750 assert((CurContext->isDependentContext() || B.builtAll()) &&
9751 "omp for loop exprs were not built");
9752
9753 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9754 // The grainsize clause and num_tasks clause are mutually exclusive and may
9755 // not appear on the same taskloop directive.
9756 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9757 return StmtError();
9758 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9759 // If a reduction clause is present on the taskloop directive, the nogroup
9760 // clause must not be specified.
9761 if (checkReductionClauseWithNogroup(*this, Clauses))
9762 return StmtError();
9763
9764 setFunctionHasBranchProtectedScope();
9765 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9766 NestedLoopCount, Clauses, AStmt, B);
9767}
9768
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009769StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9770 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9771 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9772 if (!AStmt)
9773 return StmtError();
9774
9775 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9776 OMPLoopDirective::HelperExprs B;
9777 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9778 // define the nested loops number.
9779 unsigned NestedLoopCount =
9780 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9781 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9782 VarsWithImplicitDSA, B);
9783 if (NestedLoopCount == 0)
9784 return StmtError();
9785
9786 assert((CurContext->isDependentContext() || B.builtAll()) &&
9787 "omp for loop exprs were not built");
9788
9789 if (!CurContext->isDependentContext()) {
9790 // Finalize the clauses that need pre-built expressions for CodeGen.
9791 for (OMPClause *C : Clauses) {
9792 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9793 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9794 B.NumIterations, *this, CurScope,
9795 DSAStack))
9796 return StmtError();
9797 }
9798 }
9799
9800 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9801 // The grainsize clause and num_tasks clause are mutually exclusive and may
9802 // not appear on the same taskloop directive.
9803 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9804 return StmtError();
9805 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9806 // If a reduction clause is present on the taskloop directive, the nogroup
9807 // clause must not be specified.
9808 if (checkReductionClauseWithNogroup(*this, Clauses))
9809 return StmtError();
9810 if (checkSimdlenSafelenSpecified(*this, Clauses))
9811 return StmtError();
9812
9813 setFunctionHasBranchProtectedScope();
9814 return OMPMasterTaskLoopSimdDirective::Create(
9815 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9816}
9817
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009818StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9820 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9821 if (!AStmt)
9822 return StmtError();
9823
9824 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9825 auto *CS = cast<CapturedStmt>(AStmt);
9826 // 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();
9832 for (int ThisCaptureLevel =
9833 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
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 }
9843
9844 OMPLoopDirective::HelperExprs B;
9845 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9846 // define the nested loops number.
9847 unsigned NestedLoopCount = checkOpenMPLoop(
9848 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9849 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9850 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
9857 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9858 // The grainsize clause and num_tasks clause are mutually exclusive and may
9859 // not appear on the same taskloop directive.
9860 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9861 return StmtError();
9862 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9863 // If a reduction clause is present on the taskloop directive, the nogroup
9864 // clause must not be specified.
9865 if (checkReductionClauseWithNogroup(*this, Clauses))
9866 return StmtError();
9867
9868 setFunctionHasBranchProtectedScope();
9869 return OMPParallelMasterTaskLoopDirective::Create(
9870 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9871}
9872
Alexey Bataev14a388f2019-10-25 10:27:13 -04009873StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9874 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9875 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9876 if (!AStmt)
9877 return StmtError();
9878
9879 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9880 auto *CS = cast<CapturedStmt>(AStmt);
9881 // 1.2.2 OpenMP Language Terminology
9882 // Structured block - An executable statement with a single entry at the
9883 // top and a single exit at the bottom.
9884 // The point of exit cannot be a branch out of the structured block.
9885 // longjmp() and throw() must not violate the entry/exit criteria.
9886 CS->getCapturedDecl()->setNothrow();
9887 for (int ThisCaptureLevel =
9888 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
9889 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9890 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9891 // 1.2.2 OpenMP Language Terminology
9892 // Structured block - An executable statement with a single entry at the
9893 // top and a single exit at the bottom.
9894 // The point of exit cannot be a branch out of the structured block.
9895 // longjmp() and throw() must not violate the entry/exit criteria.
9896 CS->getCapturedDecl()->setNothrow();
9897 }
9898
9899 OMPLoopDirective::HelperExprs B;
9900 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9901 // define the nested loops number.
9902 unsigned NestedLoopCount = checkOpenMPLoop(
9903 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9904 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9905 VarsWithImplicitDSA, B);
9906 if (NestedLoopCount == 0)
9907 return StmtError();
9908
9909 assert((CurContext->isDependentContext() || B.builtAll()) &&
9910 "omp for loop exprs were not built");
9911
9912 if (!CurContext->isDependentContext()) {
9913 // Finalize the clauses that need pre-built expressions for CodeGen.
9914 for (OMPClause *C : Clauses) {
9915 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9916 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9917 B.NumIterations, *this, CurScope,
9918 DSAStack))
9919 return StmtError();
9920 }
9921 }
9922
9923 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9924 // The grainsize clause and num_tasks clause are mutually exclusive and may
9925 // not appear on the same taskloop directive.
9926 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9927 return StmtError();
9928 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9929 // If a reduction clause is present on the taskloop directive, the nogroup
9930 // clause must not be specified.
9931 if (checkReductionClauseWithNogroup(*this, Clauses))
9932 return StmtError();
9933 if (checkSimdlenSafelenSpecified(*this, Clauses))
9934 return StmtError();
9935
9936 setFunctionHasBranchProtectedScope();
9937 return OMPParallelMasterTaskLoopSimdDirective::Create(
9938 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9939}
9940
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009941StmtResult Sema::ActOnOpenMPDistributeDirective(
9942 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009943 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009944 if (!AStmt)
9945 return StmtError();
9946
9947 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9948 OMPLoopDirective::HelperExprs B;
9949 // In presence of clause 'collapse' with number of loops, it will
9950 // define the nested loops number.
9951 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009952 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009953 nullptr /*ordered not a clause on distribute*/, AStmt,
9954 *this, *DSAStack, VarsWithImplicitDSA, B);
9955 if (NestedLoopCount == 0)
9956 return StmtError();
9957
9958 assert((CurContext->isDependentContext() || B.builtAll()) &&
9959 "omp for loop exprs were not built");
9960
Reid Kleckner87a31802018-03-12 21:43:02 +00009961 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009962 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9963 NestedLoopCount, Clauses, AStmt, B);
9964}
9965
Carlo Bertolli9925f152016-06-27 14:55:37 +00009966StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9967 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009968 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009969 if (!AStmt)
9970 return StmtError();
9971
Alexey Bataeve3727102018-04-18 15:57:46 +00009972 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009973 // 1.2.2 OpenMP Language Terminology
9974 // Structured block - An executable statement with a single entry at the
9975 // top and a single exit at the bottom.
9976 // The point of exit cannot be a branch out of the structured block.
9977 // longjmp() and throw() must not violate the entry/exit criteria.
9978 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009979 for (int ThisCaptureLevel =
9980 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9981 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9982 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9983 // 1.2.2 OpenMP Language Terminology
9984 // Structured block - An executable statement with a single entry at the
9985 // top and a single exit at the bottom.
9986 // The point of exit cannot be a branch out of the structured block.
9987 // longjmp() and throw() must not violate the entry/exit criteria.
9988 CS->getCapturedDecl()->setNothrow();
9989 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009990
9991 OMPLoopDirective::HelperExprs B;
9992 // In presence of clause 'collapse' with number of loops, it will
9993 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009994 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009995 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009996 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009997 VarsWithImplicitDSA, B);
9998 if (NestedLoopCount == 0)
9999 return StmtError();
10000
10001 assert((CurContext->isDependentContext() || B.builtAll()) &&
10002 "omp for loop exprs were not built");
10003
Reid Kleckner87a31802018-03-12 21:43:02 +000010004 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +000010005 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010006 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10007 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +000010008}
10009
Kelvin Li4a39add2016-07-05 05:00:15 +000010010StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
10011 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010012 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +000010013 if (!AStmt)
10014 return StmtError();
10015
Alexey Bataeve3727102018-04-18 15:57:46 +000010016 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +000010017 // 1.2.2 OpenMP Language Terminology
10018 // Structured block - An executable statement with a single entry at the
10019 // top and a single exit at the bottom.
10020 // The point of exit cannot be a branch out of the structured block.
10021 // longjmp() and throw() must not violate the entry/exit criteria.
10022 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +000010023 for (int ThisCaptureLevel =
10024 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
10025 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10026 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10027 // 1.2.2 OpenMP Language Terminology
10028 // Structured block - An executable statement with a single entry at the
10029 // top and a single exit at the bottom.
10030 // The point of exit cannot be a branch out of the structured block.
10031 // longjmp() and throw() must not violate the entry/exit criteria.
10032 CS->getCapturedDecl()->setNothrow();
10033 }
Kelvin Li4a39add2016-07-05 05:00:15 +000010034
10035 OMPLoopDirective::HelperExprs B;
10036 // In presence of clause 'collapse' with number of loops, it will
10037 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010038 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +000010039 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +000010040 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +000010041 VarsWithImplicitDSA, B);
10042 if (NestedLoopCount == 0)
10043 return StmtError();
10044
10045 assert((CurContext->isDependentContext() || B.builtAll()) &&
10046 "omp for loop exprs were not built");
10047
Alexey Bataev438388c2017-11-22 18:34:02 +000010048 if (!CurContext->isDependentContext()) {
10049 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010050 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010051 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10052 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10053 B.NumIterations, *this, CurScope,
10054 DSAStack))
10055 return StmtError();
10056 }
10057 }
10058
Kelvin Lic5609492016-07-15 04:39:07 +000010059 if (checkSimdlenSafelenSpecified(*this, Clauses))
10060 return StmtError();
10061
Reid Kleckner87a31802018-03-12 21:43:02 +000010062 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +000010063 return OMPDistributeParallelForSimdDirective::Create(
10064 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10065}
10066
Kelvin Li787f3fc2016-07-06 04:45:38 +000010067StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10068 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010069 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +000010070 if (!AStmt)
10071 return StmtError();
10072
Alexey Bataeve3727102018-04-18 15:57:46 +000010073 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010074 // 1.2.2 OpenMP Language Terminology
10075 // Structured block - An executable statement with a single entry at the
10076 // top and a single exit at the bottom.
10077 // The point of exit cannot be a branch out of the structured block.
10078 // longjmp() and throw() must not violate the entry/exit criteria.
10079 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +000010080 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10081 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10082 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10083 // 1.2.2 OpenMP Language Terminology
10084 // Structured block - An executable statement with a single entry at the
10085 // top and a single exit at the bottom.
10086 // The point of exit cannot be a branch out of the structured block.
10087 // longjmp() and throw() must not violate the entry/exit criteria.
10088 CS->getCapturedDecl()->setNothrow();
10089 }
Kelvin Li787f3fc2016-07-06 04:45:38 +000010090
10091 OMPLoopDirective::HelperExprs B;
10092 // In presence of clause 'collapse' with number of loops, it will
10093 // define the nested loops number.
10094 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010095 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +000010096 nullptr /*ordered not a clause on distribute*/, CS, *this,
10097 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010098 if (NestedLoopCount == 0)
10099 return StmtError();
10100
10101 assert((CurContext->isDependentContext() || B.builtAll()) &&
10102 "omp for loop exprs were not built");
10103
Alexey Bataev438388c2017-11-22 18:34:02 +000010104 if (!CurContext->isDependentContext()) {
10105 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010106 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010107 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10108 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10109 B.NumIterations, *this, CurScope,
10110 DSAStack))
10111 return StmtError();
10112 }
10113 }
10114
Kelvin Lic5609492016-07-15 04:39:07 +000010115 if (checkSimdlenSafelenSpecified(*this, Clauses))
10116 return StmtError();
10117
Reid Kleckner87a31802018-03-12 21:43:02 +000010118 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +000010119 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
10120 NestedLoopCount, Clauses, AStmt, B);
10121}
10122
Kelvin Lia579b912016-07-14 02:54:56 +000010123StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
10124 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010125 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +000010126 if (!AStmt)
10127 return StmtError();
10128
Alexey Bataeve3727102018-04-18 15:57:46 +000010129 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +000010130 // 1.2.2 OpenMP Language Terminology
10131 // Structured block - An executable statement with a single entry at the
10132 // top and a single exit at the bottom.
10133 // The point of exit cannot be a branch out of the structured block.
10134 // longjmp() and throw() must not violate the entry/exit criteria.
10135 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010136 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10137 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10138 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10139 // 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();
10145 }
Kelvin Lia579b912016-07-14 02:54:56 +000010146
10147 OMPLoopDirective::HelperExprs B;
10148 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10149 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010150 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010151 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010152 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010153 VarsWithImplicitDSA, B);
10154 if (NestedLoopCount == 0)
10155 return StmtError();
10156
10157 assert((CurContext->isDependentContext() || B.builtAll()) &&
10158 "omp target parallel for simd loop exprs were not built");
10159
10160 if (!CurContext->isDependentContext()) {
10161 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010162 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010163 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010164 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10165 B.NumIterations, *this, CurScope,
10166 DSAStack))
10167 return StmtError();
10168 }
10169 }
Kelvin Lic5609492016-07-15 04:39:07 +000010170 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010171 return StmtError();
10172
Reid Kleckner87a31802018-03-12 21:43:02 +000010173 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010174 return OMPTargetParallelForSimdDirective::Create(
10175 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10176}
10177
Kelvin Li986330c2016-07-20 22:57:10 +000010178StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10179 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010180 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010181 if (!AStmt)
10182 return StmtError();
10183
Alexey Bataeve3727102018-04-18 15:57:46 +000010184 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010185 // 1.2.2 OpenMP Language Terminology
10186 // Structured block - An executable statement with a single entry at the
10187 // top and a single exit at the bottom.
10188 // The point of exit cannot be a branch out of the structured block.
10189 // longjmp() and throw() must not violate the entry/exit criteria.
10190 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010191 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10192 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10193 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10194 // 1.2.2 OpenMP Language Terminology
10195 // Structured block - An executable statement with a single entry at the
10196 // top and a single exit at the bottom.
10197 // The point of exit cannot be a branch out of the structured block.
10198 // longjmp() and throw() must not violate the entry/exit criteria.
10199 CS->getCapturedDecl()->setNothrow();
10200 }
10201
Kelvin Li986330c2016-07-20 22:57:10 +000010202 OMPLoopDirective::HelperExprs B;
10203 // In presence of clause 'collapse' with number of loops, it will define the
10204 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010205 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010206 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010207 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010208 VarsWithImplicitDSA, B);
10209 if (NestedLoopCount == 0)
10210 return StmtError();
10211
10212 assert((CurContext->isDependentContext() || B.builtAll()) &&
10213 "omp target simd loop exprs were not built");
10214
10215 if (!CurContext->isDependentContext()) {
10216 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010217 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010218 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010219 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10220 B.NumIterations, *this, CurScope,
10221 DSAStack))
10222 return StmtError();
10223 }
10224 }
10225
10226 if (checkSimdlenSafelenSpecified(*this, Clauses))
10227 return StmtError();
10228
Reid Kleckner87a31802018-03-12 21:43:02 +000010229 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010230 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10231 NestedLoopCount, Clauses, AStmt, B);
10232}
10233
Kelvin Li02532872016-08-05 14:37:37 +000010234StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10235 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010236 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010237 if (!AStmt)
10238 return StmtError();
10239
Alexey Bataeve3727102018-04-18 15:57:46 +000010240 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +000010241 // 1.2.2 OpenMP Language Terminology
10242 // Structured block - An executable statement with a single entry at the
10243 // top and a single exit at the bottom.
10244 // The point of exit cannot be a branch out of the structured block.
10245 // longjmp() and throw() must not violate the entry/exit criteria.
10246 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010247 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10248 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10249 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10250 // 1.2.2 OpenMP Language Terminology
10251 // Structured block - An executable statement with a single entry at the
10252 // top and a single exit at the bottom.
10253 // The point of exit cannot be a branch out of the structured block.
10254 // longjmp() and throw() must not violate the entry/exit criteria.
10255 CS->getCapturedDecl()->setNothrow();
10256 }
Kelvin Li02532872016-08-05 14:37:37 +000010257
10258 OMPLoopDirective::HelperExprs B;
10259 // In presence of clause 'collapse' with number of loops, it will
10260 // define the nested loops number.
10261 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010262 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010263 nullptr /*ordered not a clause on distribute*/, CS, *this,
10264 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010265 if (NestedLoopCount == 0)
10266 return StmtError();
10267
10268 assert((CurContext->isDependentContext() || B.builtAll()) &&
10269 "omp teams distribute loop exprs were not built");
10270
Reid Kleckner87a31802018-03-12 21:43:02 +000010271 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010272
10273 DSAStack->setParentTeamsRegionLoc(StartLoc);
10274
David Majnemer9d168222016-08-05 17:44:54 +000010275 return OMPTeamsDistributeDirective::Create(
10276 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010277}
10278
Kelvin Li4e325f72016-10-25 12:50:55 +000010279StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10280 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010281 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010282 if (!AStmt)
10283 return StmtError();
10284
Alexey Bataeve3727102018-04-18 15:57:46 +000010285 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010286 // 1.2.2 OpenMP Language Terminology
10287 // Structured block - An executable statement with a single entry at the
10288 // top and a single exit at the bottom.
10289 // The point of exit cannot be a branch out of the structured block.
10290 // longjmp() and throw() must not violate the entry/exit criteria.
10291 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010292 for (int ThisCaptureLevel =
10293 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10294 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10295 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10296 // 1.2.2 OpenMP Language Terminology
10297 // Structured block - An executable statement with a single entry at the
10298 // top and a single exit at the bottom.
10299 // The point of exit cannot be a branch out of the structured block.
10300 // longjmp() and throw() must not violate the entry/exit criteria.
10301 CS->getCapturedDecl()->setNothrow();
10302 }
10303
Kelvin Li4e325f72016-10-25 12:50:55 +000010304
10305 OMPLoopDirective::HelperExprs B;
10306 // In presence of clause 'collapse' with number of loops, it will
10307 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010308 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010309 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010310 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010311 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010312
10313 if (NestedLoopCount == 0)
10314 return StmtError();
10315
10316 assert((CurContext->isDependentContext() || B.builtAll()) &&
10317 "omp teams distribute simd loop exprs were not built");
10318
10319 if (!CurContext->isDependentContext()) {
10320 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010321 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010322 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10323 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10324 B.NumIterations, *this, CurScope,
10325 DSAStack))
10326 return StmtError();
10327 }
10328 }
10329
10330 if (checkSimdlenSafelenSpecified(*this, Clauses))
10331 return StmtError();
10332
Reid Kleckner87a31802018-03-12 21:43:02 +000010333 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010334
10335 DSAStack->setParentTeamsRegionLoc(StartLoc);
10336
Kelvin Li4e325f72016-10-25 12:50:55 +000010337 return OMPTeamsDistributeSimdDirective::Create(
10338 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10339}
10340
Kelvin Li579e41c2016-11-30 23:51:03 +000010341StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10342 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010343 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010344 if (!AStmt)
10345 return StmtError();
10346
Alexey Bataeve3727102018-04-18 15:57:46 +000010347 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010348 // 1.2.2 OpenMP Language Terminology
10349 // Structured block - An executable statement with a single entry at the
10350 // top and a single exit at the bottom.
10351 // The point of exit cannot be a branch out of the structured block.
10352 // longjmp() and throw() must not violate the entry/exit criteria.
10353 CS->getCapturedDecl()->setNothrow();
10354
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010355 for (int ThisCaptureLevel =
10356 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10357 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10358 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10359 // 1.2.2 OpenMP Language Terminology
10360 // Structured block - An executable statement with a single entry at the
10361 // top and a single exit at the bottom.
10362 // The point of exit cannot be a branch out of the structured block.
10363 // longjmp() and throw() must not violate the entry/exit criteria.
10364 CS->getCapturedDecl()->setNothrow();
10365 }
10366
Kelvin Li579e41c2016-11-30 23:51:03 +000010367 OMPLoopDirective::HelperExprs B;
10368 // In presence of clause 'collapse' with number of loops, it will
10369 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010370 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010371 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010372 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010373 VarsWithImplicitDSA, B);
10374
10375 if (NestedLoopCount == 0)
10376 return StmtError();
10377
10378 assert((CurContext->isDependentContext() || B.builtAll()) &&
10379 "omp for loop exprs were not built");
10380
10381 if (!CurContext->isDependentContext()) {
10382 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010383 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010384 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10385 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10386 B.NumIterations, *this, CurScope,
10387 DSAStack))
10388 return StmtError();
10389 }
10390 }
10391
10392 if (checkSimdlenSafelenSpecified(*this, Clauses))
10393 return StmtError();
10394
Reid Kleckner87a31802018-03-12 21:43:02 +000010395 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010396
10397 DSAStack->setParentTeamsRegionLoc(StartLoc);
10398
Kelvin Li579e41c2016-11-30 23:51:03 +000010399 return OMPTeamsDistributeParallelForSimdDirective::Create(
10400 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10401}
10402
Kelvin Li7ade93f2016-12-09 03:24:30 +000010403StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10404 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010405 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010406 if (!AStmt)
10407 return StmtError();
10408
Alexey Bataeve3727102018-04-18 15:57:46 +000010409 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010410 // 1.2.2 OpenMP Language Terminology
10411 // Structured block - An executable statement with a single entry at the
10412 // top and a single exit at the bottom.
10413 // The point of exit cannot be a branch out of the structured block.
10414 // longjmp() and throw() must not violate the entry/exit criteria.
10415 CS->getCapturedDecl()->setNothrow();
10416
Carlo Bertolli62fae152017-11-20 20:46:39 +000010417 for (int ThisCaptureLevel =
10418 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10419 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10420 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10421 // 1.2.2 OpenMP Language Terminology
10422 // Structured block - An executable statement with a single entry at the
10423 // top and a single exit at the bottom.
10424 // The point of exit cannot be a branch out of the structured block.
10425 // longjmp() and throw() must not violate the entry/exit criteria.
10426 CS->getCapturedDecl()->setNothrow();
10427 }
10428
Kelvin Li7ade93f2016-12-09 03:24:30 +000010429 OMPLoopDirective::HelperExprs B;
10430 // In presence of clause 'collapse' with number of loops, it will
10431 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010432 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010433 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010434 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010435 VarsWithImplicitDSA, B);
10436
10437 if (NestedLoopCount == 0)
10438 return StmtError();
10439
10440 assert((CurContext->isDependentContext() || B.builtAll()) &&
10441 "omp for loop exprs were not built");
10442
Reid Kleckner87a31802018-03-12 21:43:02 +000010443 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010444
10445 DSAStack->setParentTeamsRegionLoc(StartLoc);
10446
Kelvin Li7ade93f2016-12-09 03:24:30 +000010447 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010448 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10449 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010450}
10451
Kelvin Libf594a52016-12-17 05:48:59 +000010452StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10453 Stmt *AStmt,
10454 SourceLocation StartLoc,
10455 SourceLocation EndLoc) {
10456 if (!AStmt)
10457 return StmtError();
10458
Alexey Bataeve3727102018-04-18 15:57:46 +000010459 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010460 // 1.2.2 OpenMP Language Terminology
10461 // Structured block - An executable statement with a single entry at the
10462 // top and a single exit at the bottom.
10463 // The point of exit cannot be a branch out of the structured block.
10464 // longjmp() and throw() must not violate the entry/exit criteria.
10465 CS->getCapturedDecl()->setNothrow();
10466
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010467 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10468 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10469 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10470 // 1.2.2 OpenMP Language Terminology
10471 // Structured block - An executable statement with a single entry at the
10472 // top and a single exit at the bottom.
10473 // The point of exit cannot be a branch out of the structured block.
10474 // longjmp() and throw() must not violate the entry/exit criteria.
10475 CS->getCapturedDecl()->setNothrow();
10476 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010477 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010478
10479 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10480 AStmt);
10481}
10482
Kelvin Li83c451e2016-12-25 04:52:54 +000010483StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10484 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010485 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010486 if (!AStmt)
10487 return StmtError();
10488
Alexey Bataeve3727102018-04-18 15:57:46 +000010489 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010490 // 1.2.2 OpenMP Language Terminology
10491 // Structured block - An executable statement with a single entry at the
10492 // top and a single exit at the bottom.
10493 // The point of exit cannot be a branch out of the structured block.
10494 // longjmp() and throw() must not violate the entry/exit criteria.
10495 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010496 for (int ThisCaptureLevel =
10497 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10498 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10499 CS = cast<CapturedStmt>(CS->getCapturedStmt());
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();
10506 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010507
10508 OMPLoopDirective::HelperExprs B;
10509 // In presence of clause 'collapse' with number of loops, it will
10510 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010511 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010512 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10513 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010514 VarsWithImplicitDSA, B);
10515 if (NestedLoopCount == 0)
10516 return StmtError();
10517
10518 assert((CurContext->isDependentContext() || B.builtAll()) &&
10519 "omp target teams distribute loop exprs were not built");
10520
Reid Kleckner87a31802018-03-12 21:43:02 +000010521 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010522 return OMPTargetTeamsDistributeDirective::Create(
10523 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10524}
10525
Kelvin Li80e8f562016-12-29 22:16:30 +000010526StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10527 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010528 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010529 if (!AStmt)
10530 return StmtError();
10531
Alexey Bataeve3727102018-04-18 15:57:46 +000010532 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010533 // 1.2.2 OpenMP Language Terminology
10534 // Structured block - An executable statement with a single entry at the
10535 // top and a single exit at the bottom.
10536 // The point of exit cannot be a branch out of the structured block.
10537 // longjmp() and throw() must not violate the entry/exit criteria.
10538 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010539 for (int ThisCaptureLevel =
10540 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10541 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10542 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10543 // 1.2.2 OpenMP Language Terminology
10544 // Structured block - An executable statement with a single entry at the
10545 // top and a single exit at the bottom.
10546 // The point of exit cannot be a branch out of the structured block.
10547 // longjmp() and throw() must not violate the entry/exit criteria.
10548 CS->getCapturedDecl()->setNothrow();
10549 }
10550
Kelvin Li80e8f562016-12-29 22:16:30 +000010551 OMPLoopDirective::HelperExprs B;
10552 // In presence of clause 'collapse' with number of loops, it will
10553 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010554 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010555 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10556 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010557 VarsWithImplicitDSA, B);
10558 if (NestedLoopCount == 0)
10559 return StmtError();
10560
10561 assert((CurContext->isDependentContext() || B.builtAll()) &&
10562 "omp target teams distribute parallel for loop exprs were not built");
10563
Alexey Bataev647dd842018-01-15 20:59:40 +000010564 if (!CurContext->isDependentContext()) {
10565 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010566 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010567 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10568 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10569 B.NumIterations, *this, CurScope,
10570 DSAStack))
10571 return StmtError();
10572 }
10573 }
10574
Reid Kleckner87a31802018-03-12 21:43:02 +000010575 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010576 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010577 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10578 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010579}
10580
Kelvin Li1851df52017-01-03 05:23:48 +000010581StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10582 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010583 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010584 if (!AStmt)
10585 return StmtError();
10586
Alexey Bataeve3727102018-04-18 15:57:46 +000010587 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010588 // 1.2.2 OpenMP Language Terminology
10589 // Structured block - An executable statement with a single entry at the
10590 // top and a single exit at the bottom.
10591 // The point of exit cannot be a branch out of the structured block.
10592 // longjmp() and throw() must not violate the entry/exit criteria.
10593 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010594 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10595 OMPD_target_teams_distribute_parallel_for_simd);
10596 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10597 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10598 // 1.2.2 OpenMP Language Terminology
10599 // Structured block - An executable statement with a single entry at the
10600 // top and a single exit at the bottom.
10601 // The point of exit cannot be a branch out of the structured block.
10602 // longjmp() and throw() must not violate the entry/exit criteria.
10603 CS->getCapturedDecl()->setNothrow();
10604 }
Kelvin Li1851df52017-01-03 05:23:48 +000010605
10606 OMPLoopDirective::HelperExprs B;
10607 // In presence of clause 'collapse' with number of loops, it will
10608 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010609 unsigned NestedLoopCount =
10610 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010611 getCollapseNumberExpr(Clauses),
10612 nullptr /*ordered not a clause on distribute*/, CS, *this,
10613 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010614 if (NestedLoopCount == 0)
10615 return StmtError();
10616
10617 assert((CurContext->isDependentContext() || B.builtAll()) &&
10618 "omp target teams distribute parallel for simd loop exprs were not "
10619 "built");
10620
10621 if (!CurContext->isDependentContext()) {
10622 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010623 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010624 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10625 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10626 B.NumIterations, *this, CurScope,
10627 DSAStack))
10628 return StmtError();
10629 }
10630 }
10631
Alexey Bataev438388c2017-11-22 18:34:02 +000010632 if (checkSimdlenSafelenSpecified(*this, Clauses))
10633 return StmtError();
10634
Reid Kleckner87a31802018-03-12 21:43:02 +000010635 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010636 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10637 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10638}
10639
Kelvin Lida681182017-01-10 18:08:18 +000010640StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10641 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010642 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010643 if (!AStmt)
10644 return StmtError();
10645
10646 auto *CS = cast<CapturedStmt>(AStmt);
10647 // 1.2.2 OpenMP Language Terminology
10648 // Structured block - An executable statement with a single entry at the
10649 // top and a single exit at the bottom.
10650 // The point of exit cannot be a branch out of the structured block.
10651 // longjmp() and throw() must not violate the entry/exit criteria.
10652 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010653 for (int ThisCaptureLevel =
10654 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10655 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10656 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10657 // 1.2.2 OpenMP Language Terminology
10658 // Structured block - An executable statement with a single entry at the
10659 // top and a single exit at the bottom.
10660 // The point of exit cannot be a branch out of the structured block.
10661 // longjmp() and throw() must not violate the entry/exit criteria.
10662 CS->getCapturedDecl()->setNothrow();
10663 }
Kelvin Lida681182017-01-10 18:08:18 +000010664
10665 OMPLoopDirective::HelperExprs B;
10666 // In presence of clause 'collapse' with number of loops, it will
10667 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010668 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010669 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010670 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010671 VarsWithImplicitDSA, B);
10672 if (NestedLoopCount == 0)
10673 return StmtError();
10674
10675 assert((CurContext->isDependentContext() || B.builtAll()) &&
10676 "omp target teams distribute simd loop exprs were not built");
10677
Alexey Bataev438388c2017-11-22 18:34:02 +000010678 if (!CurContext->isDependentContext()) {
10679 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010680 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010681 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10682 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10683 B.NumIterations, *this, CurScope,
10684 DSAStack))
10685 return StmtError();
10686 }
10687 }
10688
10689 if (checkSimdlenSafelenSpecified(*this, Clauses))
10690 return StmtError();
10691
Reid Kleckner87a31802018-03-12 21:43:02 +000010692 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010693 return OMPTargetTeamsDistributeSimdDirective::Create(
10694 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10695}
10696
Alexey Bataeved09d242014-05-28 05:53:51 +000010697OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010698 SourceLocation StartLoc,
10699 SourceLocation LParenLoc,
10700 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010701 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010702 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010703 case OMPC_final:
10704 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10705 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010706 case OMPC_num_threads:
10707 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10708 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010709 case OMPC_safelen:
10710 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10711 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010712 case OMPC_simdlen:
10713 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10714 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010715 case OMPC_allocator:
10716 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10717 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010718 case OMPC_collapse:
10719 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10720 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010721 case OMPC_ordered:
10722 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10723 break;
Michael Wonge710d542015-08-07 16:16:36 +000010724 case OMPC_device:
10725 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10726 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010727 case OMPC_num_teams:
10728 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10729 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010730 case OMPC_thread_limit:
10731 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10732 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010733 case OMPC_priority:
10734 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10735 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010736 case OMPC_grainsize:
10737 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10738 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010739 case OMPC_num_tasks:
10740 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10741 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010742 case OMPC_hint:
10743 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10744 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010745 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010746 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010747 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010748 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010749 case OMPC_private:
10750 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010751 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010752 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010753 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010754 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010755 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010756 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010757 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010758 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010759 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010760 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010761 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010762 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010763 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010764 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010765 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010766 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010767 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010768 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010769 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010770 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010771 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010772 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010773 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010774 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010775 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010776 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010777 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010778 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010779 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010780 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010781 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010782 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010783 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010784 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010785 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010786 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010787 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010788 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010789 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010790 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050010791 case OMPC_nontemporal:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010792 llvm_unreachable("Clause is not allowed.");
10793 }
10794 return Res;
10795}
10796
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010797// An OpenMP directive such as 'target parallel' has two captured regions:
10798// for the 'target' and 'parallel' respectively. This function returns
10799// the region in which to capture expressions associated with a clause.
10800// A return value of OMPD_unknown signifies that the expression should not
10801// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010802static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050010803 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010804 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010805 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010806 switch (CKind) {
10807 case OMPC_if:
10808 switch (DKind) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010809 case OMPD_target_parallel_for_simd:
10810 if (OpenMPVersion >= 50 &&
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010811 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010812 CaptureRegion = OMPD_parallel;
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010813 break;
10814 }
Alexey Bataevda17a532019-12-10 11:37:03 -050010815 LLVM_FALLTHROUGH;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010816 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010817 case OMPD_target_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010818 // If this clause applies to the nested 'parallel' region, capture within
10819 // the 'target' region, otherwise do not capture.
10820 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10821 CaptureRegion = OMPD_target;
10822 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010823 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfd0c91b2019-12-16 10:27:39 -050010824 if (OpenMPVersion >= 50 &&
10825 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10826 CaptureRegion = OMPD_parallel;
10827 break;
10828 }
10829 LLVM_FALLTHROUGH;
10830 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +000010831 // If this clause applies to the nested 'parallel' region, capture within
10832 // the 'teams' region, otherwise do not capture.
10833 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10834 CaptureRegion = OMPD_teams;
10835 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010836 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataev0b978942019-12-11 15:26:38 -050010837 if (OpenMPVersion >= 50 &&
10838 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10839 CaptureRegion = OMPD_parallel;
10840 break;
10841 }
10842 LLVM_FALLTHROUGH;
10843 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010844 CaptureRegion = OMPD_teams;
10845 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010846 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010847 case OMPD_target_enter_data:
10848 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010849 CaptureRegion = OMPD_task;
10850 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010851 case OMPD_parallel_master_taskloop:
10852 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10853 CaptureRegion = OMPD_parallel;
10854 break;
Alexey Bataev5c517a62019-12-05 11:31:45 -050010855 case OMPD_parallel_master_taskloop_simd:
10856 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
10857 NameModifier == OMPD_taskloop) {
10858 CaptureRegion = OMPD_parallel;
10859 break;
10860 }
10861 if (OpenMPVersion <= 45)
10862 break;
10863 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10864 CaptureRegion = OMPD_taskloop;
10865 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010866 case OMPD_parallel_for_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010867 if (OpenMPVersion <= 45)
10868 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010869 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10870 CaptureRegion = OMPD_parallel;
10871 break;
Alexey Bataev61205822019-12-04 09:50:21 -050010872 case OMPD_taskloop_simd:
Alexey Bataev853961f2019-12-05 09:50:18 -050010873 case OMPD_master_taskloop_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010874 if (OpenMPVersion <= 45)
10875 break;
10876 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10877 CaptureRegion = OMPD_taskloop;
10878 break;
Alexey Bataev52812f22019-12-05 13:22:15 -050010879 case OMPD_distribute_parallel_for_simd:
10880 if (OpenMPVersion <= 45)
10881 break;
10882 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10883 CaptureRegion = OMPD_parallel;
10884 break;
Alexey Bataevef94cd12019-12-10 12:44:45 -050010885 case OMPD_target_simd:
10886 if (OpenMPVersion >= 50 &&
10887 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10888 CaptureRegion = OMPD_target;
10889 break;
Alexey Bataev7b774b72019-12-11 11:20:47 -050010890 case OMPD_teams_distribute_simd:
Alexey Bataev411e81a2019-12-16 11:16:46 -050010891 case OMPD_target_teams_distribute_simd:
Alexey Bataev7b774b72019-12-11 11:20:47 -050010892 if (OpenMPVersion >= 50 &&
10893 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10894 CaptureRegion = OMPD_teams;
10895 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010896 case OMPD_cancel:
10897 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010898 case OMPD_parallel_master:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010899 case OMPD_parallel_sections:
10900 case OMPD_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010901 case OMPD_target:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010902 case OMPD_target_teams:
10903 case OMPD_target_teams_distribute:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010904 case OMPD_distribute_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010905 case OMPD_task:
10906 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010907 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010908 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050010909 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050010910 case OMPD_for_simd:
Alexey Bataev779a1802019-12-06 12:21:31 -050010911 case OMPD_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010912 // Do not capture if-clause expressions.
10913 break;
10914 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010915 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010916 case OMPD_taskyield:
10917 case OMPD_barrier:
10918 case OMPD_taskwait:
10919 case OMPD_cancellation_point:
10920 case OMPD_flush:
10921 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010922 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010923 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010924 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010925 case OMPD_declare_target:
10926 case OMPD_end_declare_target:
10927 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010928 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010929 case OMPD_sections:
10930 case OMPD_section:
10931 case OMPD_single:
10932 case OMPD_master:
10933 case OMPD_critical:
10934 case OMPD_taskgroup:
10935 case OMPD_distribute:
10936 case OMPD_ordered:
10937 case OMPD_atomic:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010938 case OMPD_teams_distribute:
Kelvin Li1408f912018-09-26 04:28:39 +000010939 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010940 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10941 case OMPD_unknown:
10942 llvm_unreachable("Unknown OpenMP directive");
10943 }
10944 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010945 case OMPC_num_threads:
10946 switch (DKind) {
10947 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010948 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010949 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010950 CaptureRegion = OMPD_target;
10951 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010952 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010953 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010954 case OMPD_target_teams_distribute_parallel_for:
10955 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010956 CaptureRegion = OMPD_teams;
10957 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010958 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010959 case OMPD_parallel_master:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010960 case OMPD_parallel_sections:
10961 case OMPD_parallel_for:
10962 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010963 case OMPD_distribute_parallel_for:
10964 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010965 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040010966 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010967 // Do not capture num_threads-clause expressions.
10968 break;
10969 case OMPD_target_data:
10970 case OMPD_target_enter_data:
10971 case OMPD_target_exit_data:
10972 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010973 case OMPD_target:
10974 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010975 case OMPD_target_teams:
10976 case OMPD_target_teams_distribute:
10977 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010978 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010979 case OMPD_task:
10980 case OMPD_taskloop:
10981 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010982 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010983 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010984 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010985 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010986 case OMPD_taskyield:
10987 case OMPD_barrier:
10988 case OMPD_taskwait:
10989 case OMPD_cancellation_point:
10990 case OMPD_flush:
10991 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010992 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010993 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010994 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010995 case OMPD_declare_target:
10996 case OMPD_end_declare_target:
10997 case OMPD_teams:
10998 case OMPD_simd:
10999 case OMPD_for:
11000 case OMPD_for_simd:
11001 case OMPD_sections:
11002 case OMPD_section:
11003 case OMPD_single:
11004 case OMPD_master:
11005 case OMPD_critical:
11006 case OMPD_taskgroup:
11007 case OMPD_distribute:
11008 case OMPD_ordered:
11009 case OMPD_atomic:
11010 case OMPD_distribute_simd:
11011 case OMPD_teams_distribute:
11012 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011013 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011014 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
11015 case OMPD_unknown:
11016 llvm_unreachable("Unknown OpenMP directive");
11017 }
11018 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011019 case OMPC_num_teams:
11020 switch (DKind) {
11021 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011022 case OMPD_target_teams_distribute:
11023 case OMPD_target_teams_distribute_simd:
11024 case OMPD_target_teams_distribute_parallel_for:
11025 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011026 CaptureRegion = OMPD_target;
11027 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011028 case OMPD_teams_distribute_parallel_for:
11029 case OMPD_teams_distribute_parallel_for_simd:
11030 case OMPD_teams:
11031 case OMPD_teams_distribute:
11032 case OMPD_teams_distribute_simd:
11033 // Do not capture num_teams-clause expressions.
11034 break;
11035 case OMPD_distribute_parallel_for:
11036 case OMPD_distribute_parallel_for_simd:
11037 case OMPD_task:
11038 case OMPD_taskloop:
11039 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011040 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011041 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011042 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011043 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011044 case OMPD_target_data:
11045 case OMPD_target_enter_data:
11046 case OMPD_target_exit_data:
11047 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011048 case OMPD_cancel:
11049 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011050 case OMPD_parallel_master:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011051 case OMPD_parallel_sections:
11052 case OMPD_parallel_for:
11053 case OMPD_parallel_for_simd:
11054 case OMPD_target:
11055 case OMPD_target_simd:
11056 case OMPD_target_parallel:
11057 case OMPD_target_parallel_for:
11058 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011059 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011060 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011061 case OMPD_taskyield:
11062 case OMPD_barrier:
11063 case OMPD_taskwait:
11064 case OMPD_cancellation_point:
11065 case OMPD_flush:
11066 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011067 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011068 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011069 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011070 case OMPD_declare_target:
11071 case OMPD_end_declare_target:
11072 case OMPD_simd:
11073 case OMPD_for:
11074 case OMPD_for_simd:
11075 case OMPD_sections:
11076 case OMPD_section:
11077 case OMPD_single:
11078 case OMPD_master:
11079 case OMPD_critical:
11080 case OMPD_taskgroup:
11081 case OMPD_distribute:
11082 case OMPD_ordered:
11083 case OMPD_atomic:
11084 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011085 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011086 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11087 case OMPD_unknown:
11088 llvm_unreachable("Unknown OpenMP directive");
11089 }
11090 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011091 case OMPC_thread_limit:
11092 switch (DKind) {
11093 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011094 case OMPD_target_teams_distribute:
11095 case OMPD_target_teams_distribute_simd:
11096 case OMPD_target_teams_distribute_parallel_for:
11097 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011098 CaptureRegion = OMPD_target;
11099 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011100 case OMPD_teams_distribute_parallel_for:
11101 case OMPD_teams_distribute_parallel_for_simd:
11102 case OMPD_teams:
11103 case OMPD_teams_distribute:
11104 case OMPD_teams_distribute_simd:
11105 // Do not capture thread_limit-clause expressions.
11106 break;
11107 case OMPD_distribute_parallel_for:
11108 case OMPD_distribute_parallel_for_simd:
11109 case OMPD_task:
11110 case OMPD_taskloop:
11111 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011112 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011113 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011114 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011115 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011116 case OMPD_target_data:
11117 case OMPD_target_enter_data:
11118 case OMPD_target_exit_data:
11119 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011120 case OMPD_cancel:
11121 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011122 case OMPD_parallel_master:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011123 case OMPD_parallel_sections:
11124 case OMPD_parallel_for:
11125 case OMPD_parallel_for_simd:
11126 case OMPD_target:
11127 case OMPD_target_simd:
11128 case OMPD_target_parallel:
11129 case OMPD_target_parallel_for:
11130 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011131 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011132 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011133 case OMPD_taskyield:
11134 case OMPD_barrier:
11135 case OMPD_taskwait:
11136 case OMPD_cancellation_point:
11137 case OMPD_flush:
11138 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011139 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011140 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011141 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011142 case OMPD_declare_target:
11143 case OMPD_end_declare_target:
11144 case OMPD_simd:
11145 case OMPD_for:
11146 case OMPD_for_simd:
11147 case OMPD_sections:
11148 case OMPD_section:
11149 case OMPD_single:
11150 case OMPD_master:
11151 case OMPD_critical:
11152 case OMPD_taskgroup:
11153 case OMPD_distribute:
11154 case OMPD_ordered:
11155 case OMPD_atomic:
11156 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011157 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011158 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
11159 case OMPD_unknown:
11160 llvm_unreachable("Unknown OpenMP directive");
11161 }
11162 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011163 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011164 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000011165 case OMPD_parallel_for:
11166 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011167 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000011168 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011169 case OMPD_teams_distribute_parallel_for:
11170 case OMPD_teams_distribute_parallel_for_simd:
11171 case OMPD_target_parallel_for:
11172 case OMPD_target_parallel_for_simd:
11173 case OMPD_target_teams_distribute_parallel_for:
11174 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011175 CaptureRegion = OMPD_parallel;
11176 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011177 case OMPD_for:
11178 case OMPD_for_simd:
11179 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011180 break;
11181 case OMPD_task:
11182 case OMPD_taskloop:
11183 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011184 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011185 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011186 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011187 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011188 case OMPD_target_data:
11189 case OMPD_target_enter_data:
11190 case OMPD_target_exit_data:
11191 case OMPD_target_update:
11192 case OMPD_teams:
11193 case OMPD_teams_distribute:
11194 case OMPD_teams_distribute_simd:
11195 case OMPD_target_teams_distribute:
11196 case OMPD_target_teams_distribute_simd:
11197 case OMPD_target:
11198 case OMPD_target_simd:
11199 case OMPD_target_parallel:
11200 case OMPD_cancel:
11201 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011202 case OMPD_parallel_master:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011203 case OMPD_parallel_sections:
11204 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011205 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011206 case OMPD_taskyield:
11207 case OMPD_barrier:
11208 case OMPD_taskwait:
11209 case OMPD_cancellation_point:
11210 case OMPD_flush:
11211 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011212 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011213 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011214 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011215 case OMPD_declare_target:
11216 case OMPD_end_declare_target:
11217 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011218 case OMPD_sections:
11219 case OMPD_section:
11220 case OMPD_single:
11221 case OMPD_master:
11222 case OMPD_critical:
11223 case OMPD_taskgroup:
11224 case OMPD_distribute:
11225 case OMPD_ordered:
11226 case OMPD_atomic:
11227 case OMPD_distribute_simd:
11228 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011229 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011230 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11231 case OMPD_unknown:
11232 llvm_unreachable("Unknown OpenMP directive");
11233 }
11234 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011235 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011236 switch (DKind) {
11237 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011238 case OMPD_teams_distribute_parallel_for_simd:
11239 case OMPD_teams_distribute:
11240 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011241 case OMPD_target_teams_distribute_parallel_for:
11242 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011243 case OMPD_target_teams_distribute:
11244 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011245 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011246 break;
11247 case OMPD_distribute_parallel_for:
11248 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011249 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011250 case OMPD_distribute_simd:
11251 // Do not capture thread_limit-clause expressions.
11252 break;
11253 case OMPD_parallel_for:
11254 case OMPD_parallel_for_simd:
11255 case OMPD_target_parallel_for_simd:
11256 case OMPD_target_parallel_for:
11257 case OMPD_task:
11258 case OMPD_taskloop:
11259 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011260 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011261 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011262 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011263 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011264 case OMPD_target_data:
11265 case OMPD_target_enter_data:
11266 case OMPD_target_exit_data:
11267 case OMPD_target_update:
11268 case OMPD_teams:
11269 case OMPD_target:
11270 case OMPD_target_simd:
11271 case OMPD_target_parallel:
11272 case OMPD_cancel:
11273 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011274 case OMPD_parallel_master:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011275 case OMPD_parallel_sections:
11276 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011277 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011278 case OMPD_taskyield:
11279 case OMPD_barrier:
11280 case OMPD_taskwait:
11281 case OMPD_cancellation_point:
11282 case OMPD_flush:
11283 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011284 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011285 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011286 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011287 case OMPD_declare_target:
11288 case OMPD_end_declare_target:
11289 case OMPD_simd:
11290 case OMPD_for:
11291 case OMPD_for_simd:
11292 case OMPD_sections:
11293 case OMPD_section:
11294 case OMPD_single:
11295 case OMPD_master:
11296 case OMPD_critical:
11297 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011298 case OMPD_ordered:
11299 case OMPD_atomic:
11300 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011301 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011302 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11303 case OMPD_unknown:
11304 llvm_unreachable("Unknown OpenMP directive");
11305 }
11306 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011307 case OMPC_device:
11308 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011309 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011310 case OMPD_target_enter_data:
11311 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011312 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011313 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011314 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011315 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011316 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011317 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011318 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011319 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011320 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011321 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011322 CaptureRegion = OMPD_task;
11323 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011324 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011325 // Do not capture device-clause expressions.
11326 break;
11327 case OMPD_teams_distribute_parallel_for:
11328 case OMPD_teams_distribute_parallel_for_simd:
11329 case OMPD_teams:
11330 case OMPD_teams_distribute:
11331 case OMPD_teams_distribute_simd:
11332 case OMPD_distribute_parallel_for:
11333 case OMPD_distribute_parallel_for_simd:
11334 case OMPD_task:
11335 case OMPD_taskloop:
11336 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011337 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011338 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011339 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011340 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011341 case OMPD_cancel:
11342 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011343 case OMPD_parallel_master:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011344 case OMPD_parallel_sections:
11345 case OMPD_parallel_for:
11346 case OMPD_parallel_for_simd:
11347 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011348 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011349 case OMPD_taskyield:
11350 case OMPD_barrier:
11351 case OMPD_taskwait:
11352 case OMPD_cancellation_point:
11353 case OMPD_flush:
11354 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011355 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011356 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011357 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011358 case OMPD_declare_target:
11359 case OMPD_end_declare_target:
11360 case OMPD_simd:
11361 case OMPD_for:
11362 case OMPD_for_simd:
11363 case OMPD_sections:
11364 case OMPD_section:
11365 case OMPD_single:
11366 case OMPD_master:
11367 case OMPD_critical:
11368 case OMPD_taskgroup:
11369 case OMPD_distribute:
11370 case OMPD_ordered:
11371 case OMPD_atomic:
11372 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011373 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011374 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11375 case OMPD_unknown:
11376 llvm_unreachable("Unknown OpenMP directive");
11377 }
11378 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011379 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011380 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011381 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011382 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011383 switch (DKind) {
11384 case OMPD_task:
11385 case OMPD_taskloop:
11386 case OMPD_taskloop_simd:
11387 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011388 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011389 break;
11390 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011391 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011392 CaptureRegion = OMPD_parallel;
11393 break;
11394 case OMPD_target_update:
11395 case OMPD_target_enter_data:
11396 case OMPD_target_exit_data:
11397 case OMPD_target:
11398 case OMPD_target_simd:
11399 case OMPD_target_teams:
11400 case OMPD_target_parallel:
11401 case OMPD_target_teams_distribute:
11402 case OMPD_target_teams_distribute_simd:
11403 case OMPD_target_parallel_for:
11404 case OMPD_target_parallel_for_simd:
11405 case OMPD_target_teams_distribute_parallel_for:
11406 case OMPD_target_teams_distribute_parallel_for_simd:
11407 case OMPD_target_data:
11408 case OMPD_teams_distribute_parallel_for:
11409 case OMPD_teams_distribute_parallel_for_simd:
11410 case OMPD_teams:
11411 case OMPD_teams_distribute:
11412 case OMPD_teams_distribute_simd:
11413 case OMPD_distribute_parallel_for:
11414 case OMPD_distribute_parallel_for_simd:
11415 case OMPD_cancel:
11416 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011417 case OMPD_parallel_master:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011418 case OMPD_parallel_sections:
11419 case OMPD_parallel_for:
11420 case OMPD_parallel_for_simd:
11421 case OMPD_threadprivate:
11422 case OMPD_allocate:
11423 case OMPD_taskyield:
11424 case OMPD_barrier:
11425 case OMPD_taskwait:
11426 case OMPD_cancellation_point:
11427 case OMPD_flush:
11428 case OMPD_declare_reduction:
11429 case OMPD_declare_mapper:
11430 case OMPD_declare_simd:
11431 case OMPD_declare_variant:
11432 case OMPD_declare_target:
11433 case OMPD_end_declare_target:
11434 case OMPD_simd:
11435 case OMPD_for:
11436 case OMPD_for_simd:
11437 case OMPD_sections:
11438 case OMPD_section:
11439 case OMPD_single:
11440 case OMPD_master:
11441 case OMPD_critical:
11442 case OMPD_taskgroup:
11443 case OMPD_distribute:
11444 case OMPD_ordered:
11445 case OMPD_atomic:
11446 case OMPD_distribute_simd:
11447 case OMPD_requires:
11448 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11449 case OMPD_unknown:
11450 llvm_unreachable("Unknown OpenMP directive");
11451 }
11452 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011453 case OMPC_firstprivate:
11454 case OMPC_lastprivate:
11455 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011456 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011457 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011458 case OMPC_linear:
11459 case OMPC_default:
11460 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011461 case OMPC_safelen:
11462 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011463 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011464 case OMPC_collapse:
11465 case OMPC_private:
11466 case OMPC_shared:
11467 case OMPC_aligned:
11468 case OMPC_copyin:
11469 case OMPC_copyprivate:
11470 case OMPC_ordered:
11471 case OMPC_nowait:
11472 case OMPC_untied:
11473 case OMPC_mergeable:
11474 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011475 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011476 case OMPC_flush:
11477 case OMPC_read:
11478 case OMPC_write:
11479 case OMPC_update:
11480 case OMPC_capture:
11481 case OMPC_seq_cst:
11482 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011483 case OMPC_threads:
11484 case OMPC_simd:
11485 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011486 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011487 case OMPC_hint:
11488 case OMPC_defaultmap:
11489 case OMPC_unknown:
11490 case OMPC_uniform:
11491 case OMPC_to:
11492 case OMPC_from:
11493 case OMPC_use_device_ptr:
11494 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011495 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011496 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011497 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011498 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011499 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011500 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011501 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011502 case OMPC_nontemporal:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011503 llvm_unreachable("Unexpected OpenMP clause.");
11504 }
11505 return CaptureRegion;
11506}
11507
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011508OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11509 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011510 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011511 SourceLocation NameModifierLoc,
11512 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011513 SourceLocation EndLoc) {
11514 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011515 Stmt *HelperValStmt = nullptr;
11516 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011517 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11518 !Condition->isInstantiationDependent() &&
11519 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011520 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011521 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011522 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011523
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011524 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011525
11526 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011527 CaptureRegion = getOpenMPCaptureRegionForClause(
11528 DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011529 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011530 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011531 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011532 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11533 HelperValStmt = buildPreInits(Context, Captures);
11534 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011535 }
11536
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011537 return new (Context)
11538 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11539 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011540}
11541
Alexey Bataev3778b602014-07-17 07:32:53 +000011542OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11543 SourceLocation StartLoc,
11544 SourceLocation LParenLoc,
11545 SourceLocation EndLoc) {
11546 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011547 Stmt *HelperValStmt = nullptr;
11548 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011549 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11550 !Condition->isInstantiationDependent() &&
11551 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011552 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011553 if (Val.isInvalid())
11554 return nullptr;
11555
Richard Smith03a4aa32016-06-23 19:02:52 +000011556 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011557
11558 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011559 CaptureRegion =
11560 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011561 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11562 ValExpr = MakeFullExpr(ValExpr).get();
11563 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11564 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11565 HelperValStmt = buildPreInits(Context, Captures);
11566 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011567 }
11568
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011569 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11570 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011571}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011572
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011573ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11574 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011575 if (!Op)
11576 return ExprError();
11577
11578 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11579 public:
11580 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011581 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011582 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11583 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011584 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11585 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011586 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11587 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011588 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11589 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011590 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11591 QualType T,
11592 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011593 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11594 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011595 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11596 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011597 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011598 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011599 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011600 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11601 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011602 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11603 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011604 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11605 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011606 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011607 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011608 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011609 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11610 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011611 llvm_unreachable("conversion functions are permitted");
11612 }
11613 } ConvertDiagnoser;
11614 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11615}
11616
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011617static bool
11618isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11619 bool StrictlyPositive, bool BuildCapture = false,
11620 OpenMPDirectiveKind DKind = OMPD_unknown,
11621 OpenMPDirectiveKind *CaptureRegion = nullptr,
11622 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011623 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11624 !ValExpr->isInstantiationDependent()) {
11625 SourceLocation Loc = ValExpr->getExprLoc();
11626 ExprResult Value =
11627 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11628 if (Value.isInvalid())
11629 return false;
11630
11631 ValExpr = Value.get();
11632 // The expression must evaluate to a non-negative integer value.
11633 llvm::APSInt Result;
11634 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011635 Result.isSigned() &&
11636 !((!StrictlyPositive && Result.isNonNegative()) ||
11637 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011638 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011639 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11640 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011641 return false;
11642 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011643 if (!BuildCapture)
11644 return true;
Alexey Bataev61205822019-12-04 09:50:21 -050011645 *CaptureRegion =
11646 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011647 if (*CaptureRegion != OMPD_unknown &&
11648 !SemaRef.CurContext->isDependentContext()) {
11649 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11650 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11651 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11652 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11653 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011654 }
11655 return true;
11656}
11657
Alexey Bataev568a8332014-03-06 06:15:19 +000011658OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11659 SourceLocation StartLoc,
11660 SourceLocation LParenLoc,
11661 SourceLocation EndLoc) {
11662 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011663 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011664
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011665 // OpenMP [2.5, Restrictions]
11666 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011667 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011668 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011669 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011670
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011671 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011672 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050011673 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011674 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011675 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011676 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011677 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11678 HelperValStmt = buildPreInits(Context, Captures);
11679 }
11680
11681 return new (Context) OMPNumThreadsClause(
11682 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011683}
11684
Alexey Bataev62c87d22014-03-21 04:51:18 +000011685ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011686 OpenMPClauseKind CKind,
11687 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011688 if (!E)
11689 return ExprError();
11690 if (E->isValueDependent() || E->isTypeDependent() ||
11691 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011692 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011693 llvm::APSInt Result;
11694 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11695 if (ICE.isInvalid())
11696 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011697 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11698 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011699 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011700 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11701 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011702 return ExprError();
11703 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011704 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11705 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11706 << E->getSourceRange();
11707 return ExprError();
11708 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011709 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11710 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011711 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011712 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011713 return ICE;
11714}
11715
11716OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11717 SourceLocation LParenLoc,
11718 SourceLocation EndLoc) {
11719 // OpenMP [2.8.1, simd construct, Description]
11720 // The parameter of the safelen clause must be a constant
11721 // positive integer expression.
11722 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11723 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011724 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011725 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011726 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011727}
11728
Alexey Bataev66b15b52015-08-21 11:14:16 +000011729OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11730 SourceLocation LParenLoc,
11731 SourceLocation EndLoc) {
11732 // OpenMP [2.8.1, simd construct, Description]
11733 // The parameter of the simdlen clause must be a constant
11734 // positive integer expression.
11735 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11736 if (Simdlen.isInvalid())
11737 return nullptr;
11738 return new (Context)
11739 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11740}
11741
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011742/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011743static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11744 DSAStackTy *Stack) {
11745 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011746 if (!OMPAllocatorHandleT.isNull())
11747 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011748 // Build the predefined allocator expressions.
11749 bool ErrorFound = false;
11750 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11751 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11752 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11753 StringRef Allocator =
11754 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11755 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11756 auto *VD = dyn_cast_or_null<ValueDecl>(
11757 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11758 if (!VD) {
11759 ErrorFound = true;
11760 break;
11761 }
11762 QualType AllocatorType =
11763 VD->getType().getNonLValueExprType(S.getASTContext());
11764 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11765 if (!Res.isUsable()) {
11766 ErrorFound = true;
11767 break;
11768 }
11769 if (OMPAllocatorHandleT.isNull())
11770 OMPAllocatorHandleT = AllocatorType;
11771 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11772 ErrorFound = true;
11773 break;
11774 }
11775 Stack->setAllocator(AllocatorKind, Res.get());
11776 }
11777 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011778 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11779 return false;
11780 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011781 OMPAllocatorHandleT.addConst();
11782 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011783 return true;
11784}
11785
11786OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11787 SourceLocation LParenLoc,
11788 SourceLocation EndLoc) {
11789 // OpenMP [2.11.3, allocate Directive, Description]
11790 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011791 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011792 return nullptr;
11793
11794 ExprResult Allocator = DefaultLvalueConversion(A);
11795 if (Allocator.isInvalid())
11796 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011797 Allocator = PerformImplicitConversion(Allocator.get(),
11798 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011799 Sema::AA_Initializing,
11800 /*AllowExplicit=*/true);
11801 if (Allocator.isInvalid())
11802 return nullptr;
11803 return new (Context)
11804 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11805}
11806
Alexander Musman64d33f12014-06-04 07:53:32 +000011807OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11808 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011809 SourceLocation LParenLoc,
11810 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011811 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011812 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011813 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011814 // The parameter of the collapse clause must be a constant
11815 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011816 ExprResult NumForLoopsResult =
11817 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11818 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011819 return nullptr;
11820 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011821 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011822}
11823
Alexey Bataev10e775f2015-07-30 11:36:16 +000011824OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11825 SourceLocation EndLoc,
11826 SourceLocation LParenLoc,
11827 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011828 // OpenMP [2.7.1, loop construct, Description]
11829 // OpenMP [2.8.1, simd construct, Description]
11830 // OpenMP [2.9.6, distribute construct, Description]
11831 // The parameter of the ordered clause must be a constant
11832 // positive integer expression if any.
11833 if (NumForLoops && LParenLoc.isValid()) {
11834 ExprResult NumForLoopsResult =
11835 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11836 if (NumForLoopsResult.isInvalid())
11837 return nullptr;
11838 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011839 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011840 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011841 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011842 auto *Clause = OMPOrderedClause::Create(
11843 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11844 StartLoc, LParenLoc, EndLoc);
11845 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11846 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011847}
11848
Alexey Bataeved09d242014-05-28 05:53:51 +000011849OMPClause *Sema::ActOnOpenMPSimpleClause(
11850 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11851 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011852 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011853 switch (Kind) {
11854 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011855 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011856 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11857 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011858 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011859 case OMPC_proc_bind:
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060011860 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
11861 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011862 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011863 case OMPC_atomic_default_mem_order:
11864 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11865 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11866 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11867 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011868 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011869 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011870 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011871 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011872 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011873 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011874 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011875 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011876 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011877 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011878 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011879 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011880 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011881 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011882 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011883 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011884 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011885 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011886 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011887 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011888 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011889 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011890 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011891 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011892 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011893 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011894 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011895 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011896 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011897 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011898 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011899 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011900 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011901 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011902 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011903 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011904 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011905 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011906 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011907 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011908 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011909 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011910 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011911 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011912 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011913 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011914 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011915 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011916 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011917 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011918 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011919 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011920 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011921 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011922 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011923 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011924 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011925 case OMPC_nontemporal:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011926 llvm_unreachable("Clause is not allowed.");
11927 }
11928 return Res;
11929}
11930
Alexey Bataev6402bca2015-12-28 07:25:51 +000011931static std::string
11932getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11933 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011934 SmallString<256> Buffer;
11935 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011936 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11937 unsigned Skipped = Exclude.size();
11938 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011939 for (unsigned I = First; I < Last; ++I) {
11940 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011941 --Skipped;
11942 continue;
11943 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011944 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11945 if (I == Bound - Skipped)
11946 Out << " or ";
11947 else if (I != Bound + 1 - Skipped)
11948 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011949 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011950 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011951}
11952
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011953OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11954 SourceLocation KindKwLoc,
11955 SourceLocation StartLoc,
11956 SourceLocation LParenLoc,
11957 SourceLocation EndLoc) {
11958 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011959 static_assert(OMPC_DEFAULT_unknown > 0,
11960 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011961 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011962 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11963 /*Last=*/OMPC_DEFAULT_unknown)
11964 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011965 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011966 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011967 switch (Kind) {
11968 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011969 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011970 break;
11971 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011972 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011973 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011974 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011975 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011976 break;
11977 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011978 return new (Context)
11979 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011980}
11981
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060011982OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011983 SourceLocation KindKwLoc,
11984 SourceLocation StartLoc,
11985 SourceLocation LParenLoc,
11986 SourceLocation EndLoc) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060011987 if (Kind == OMP_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011988 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060011989 << getListOfPossibleValues(OMPC_proc_bind,
11990 /*First=*/unsigned(OMP_PROC_BIND_master),
11991 /*Last=*/5)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011992 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011993 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011994 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011995 return new (Context)
11996 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011997}
11998
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011999OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
12000 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
12001 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12002 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
12003 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12004 << getListOfPossibleValues(
12005 OMPC_atomic_default_mem_order, /*First=*/0,
12006 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
12007 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
12008 return nullptr;
12009 }
12010 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
12011 LParenLoc, EndLoc);
12012}
12013
Alexey Bataev56dafe82014-06-20 07:16:17 +000012014OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012015 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012016 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012017 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012018 SourceLocation EndLoc) {
12019 OMPClause *Res = nullptr;
12020 switch (Kind) {
12021 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012022 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
12023 assert(Argument.size() == NumberOfElements &&
12024 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012025 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012026 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
12027 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
12028 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
12029 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
12030 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012031 break;
12032 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012033 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
12034 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
12035 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
12036 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000012037 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012038 case OMPC_dist_schedule:
12039 Res = ActOnOpenMPDistScheduleClause(
12040 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
12041 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
12042 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012043 case OMPC_defaultmap:
12044 enum { Modifier, DefaultmapKind };
12045 Res = ActOnOpenMPDefaultmapClause(
12046 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
12047 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000012048 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
12049 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012050 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000012051 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012052 case OMPC_num_threads:
12053 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012054 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012055 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012056 case OMPC_collapse:
12057 case OMPC_default:
12058 case OMPC_proc_bind:
12059 case OMPC_private:
12060 case OMPC_firstprivate:
12061 case OMPC_lastprivate:
12062 case OMPC_shared:
12063 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012064 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012065 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012066 case OMPC_linear:
12067 case OMPC_aligned:
12068 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012069 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012070 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012071 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012072 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012073 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012074 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012075 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012076 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012077 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012078 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012079 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012080 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012081 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012082 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012083 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012084 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012085 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012086 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012087 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012088 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012089 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012090 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012091 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012092 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012093 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012094 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012095 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012096 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012097 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012098 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012099 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000012100 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012101 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012102 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012103 case OMPC_dynamic_allocators:
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 Bataevb6e70842019-12-16 15:54:17 -050012107 case OMPC_nontemporal:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012108 llvm_unreachable("Clause is not allowed.");
12109 }
12110 return Res;
12111}
12112
Alexey Bataev6402bca2015-12-28 07:25:51 +000012113static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
12114 OpenMPScheduleClauseModifier M2,
12115 SourceLocation M1Loc, SourceLocation M2Loc) {
12116 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
12117 SmallVector<unsigned, 2> Excluded;
12118 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
12119 Excluded.push_back(M2);
12120 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
12121 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
12122 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
12123 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
12124 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
12125 << getListOfPossibleValues(OMPC_schedule,
12126 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
12127 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12128 Excluded)
12129 << getOpenMPClauseName(OMPC_schedule);
12130 return true;
12131 }
12132 return false;
12133}
12134
Alexey Bataev56dafe82014-06-20 07:16:17 +000012135OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012136 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012137 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012138 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
12139 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
12140 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
12141 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
12142 return nullptr;
12143 // OpenMP, 2.7.1, Loop Construct, Restrictions
12144 // Either the monotonic modifier or the nonmonotonic modifier can be specified
12145 // but not both.
12146 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
12147 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
12148 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
12149 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
12150 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
12151 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
12152 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
12153 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
12154 return nullptr;
12155 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012156 if (Kind == OMPC_SCHEDULE_unknown) {
12157 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000012158 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
12159 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
12160 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12161 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12162 Exclude);
12163 } else {
12164 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12165 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012166 }
12167 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12168 << Values << getOpenMPClauseName(OMPC_schedule);
12169 return nullptr;
12170 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000012171 // OpenMP, 2.7.1, Loop Construct, Restrictions
12172 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
12173 // schedule(guided).
12174 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
12175 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
12176 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
12177 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
12178 diag::err_omp_schedule_nonmonotonic_static);
12179 return nullptr;
12180 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012181 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012182 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000012183 if (ChunkSize) {
12184 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12185 !ChunkSize->isInstantiationDependent() &&
12186 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012187 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000012188 ExprResult Val =
12189 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12190 if (Val.isInvalid())
12191 return nullptr;
12192
12193 ValExpr = Val.get();
12194
12195 // OpenMP [2.7.1, Restrictions]
12196 // chunk_size must be a loop invariant integer expression with a positive
12197 // value.
12198 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000012199 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12200 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12201 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000012202 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000012203 return nullptr;
12204 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012205 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050012206 DSAStack->getCurrentDirective(), OMPC_schedule,
12207 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012208 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012209 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012210 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012211 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12212 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012213 }
12214 }
12215 }
12216
Alexey Bataev6402bca2015-12-28 07:25:51 +000012217 return new (Context)
12218 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012219 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012220}
12221
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012222OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12223 SourceLocation StartLoc,
12224 SourceLocation EndLoc) {
12225 OMPClause *Res = nullptr;
12226 switch (Kind) {
12227 case OMPC_ordered:
12228 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12229 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012230 case OMPC_nowait:
12231 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12232 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012233 case OMPC_untied:
12234 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12235 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012236 case OMPC_mergeable:
12237 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12238 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012239 case OMPC_read:
12240 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12241 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012242 case OMPC_write:
12243 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12244 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012245 case OMPC_update:
12246 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12247 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012248 case OMPC_capture:
12249 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12250 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012251 case OMPC_seq_cst:
12252 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12253 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012254 case OMPC_threads:
12255 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12256 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012257 case OMPC_simd:
12258 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12259 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012260 case OMPC_nogroup:
12261 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12262 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012263 case OMPC_unified_address:
12264 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12265 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012266 case OMPC_unified_shared_memory:
12267 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12268 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012269 case OMPC_reverse_offload:
12270 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12271 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012272 case OMPC_dynamic_allocators:
12273 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12274 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012275 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012276 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012277 case OMPC_num_threads:
12278 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012279 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012280 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012281 case OMPC_collapse:
12282 case OMPC_schedule:
12283 case OMPC_private:
12284 case OMPC_firstprivate:
12285 case OMPC_lastprivate:
12286 case OMPC_shared:
12287 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012288 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012289 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012290 case OMPC_linear:
12291 case OMPC_aligned:
12292 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012293 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012294 case OMPC_default:
12295 case OMPC_proc_bind:
12296 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012297 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012298 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012299 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012300 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012301 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012302 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012303 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012304 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012305 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012306 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012307 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012308 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012309 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012310 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012311 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012312 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012313 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012314 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012315 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012316 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012317 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012318 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012319 case OMPC_nontemporal:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012320 llvm_unreachable("Clause is not allowed.");
12321 }
12322 return Res;
12323}
12324
Alexey Bataev236070f2014-06-20 11:19:47 +000012325OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12326 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012327 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012328 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12329}
12330
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012331OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12332 SourceLocation EndLoc) {
12333 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12334}
12335
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012336OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12337 SourceLocation EndLoc) {
12338 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12339}
12340
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012341OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12342 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012343 return new (Context) OMPReadClause(StartLoc, EndLoc);
12344}
12345
Alexey Bataevdea47612014-07-23 07:46:59 +000012346OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12347 SourceLocation EndLoc) {
12348 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12349}
12350
Alexey Bataev67a4f222014-07-23 10:25:33 +000012351OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12352 SourceLocation EndLoc) {
12353 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12354}
12355
Alexey Bataev459dec02014-07-24 06:46:57 +000012356OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12357 SourceLocation EndLoc) {
12358 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12359}
12360
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012361OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12362 SourceLocation EndLoc) {
12363 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12364}
12365
Alexey Bataev346265e2015-09-25 10:37:12 +000012366OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12367 SourceLocation EndLoc) {
12368 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12369}
12370
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012371OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12372 SourceLocation EndLoc) {
12373 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12374}
12375
Alexey Bataevb825de12015-12-07 10:51:44 +000012376OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12377 SourceLocation EndLoc) {
12378 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12379}
12380
Kelvin Li1408f912018-09-26 04:28:39 +000012381OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12382 SourceLocation EndLoc) {
12383 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12384}
12385
Patrick Lyster4a370b92018-10-01 13:47:43 +000012386OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12387 SourceLocation EndLoc) {
12388 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12389}
12390
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012391OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12392 SourceLocation EndLoc) {
12393 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12394}
12395
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012396OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12397 SourceLocation EndLoc) {
12398 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12399}
12400
Alexey Bataevc5e02582014-06-16 07:08:35 +000012401OMPClause *Sema::ActOnOpenMPVarListClause(
12402 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012403 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12404 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012405 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
Kelvin Lief579432018-12-18 22:18:41 +000012406 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012407 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
12408 SourceLocation DepLinMapLastLoc) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012409 SourceLocation StartLoc = Locs.StartLoc;
12410 SourceLocation LParenLoc = Locs.LParenLoc;
12411 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012412 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012413 switch (Kind) {
12414 case OMPC_private:
12415 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12416 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012417 case OMPC_firstprivate:
12418 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12419 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012420 case OMPC_lastprivate:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012421 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
12422 "Unexpected lastprivate modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012423 Res = ActOnOpenMPLastprivateClause(
12424 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
12425 DepLinMapLastLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012426 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012427 case OMPC_shared:
12428 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12429 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012430 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012431 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012432 EndLoc, ReductionOrMapperIdScopeSpec,
12433 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012434 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012435 case OMPC_task_reduction:
12436 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012437 EndLoc, ReductionOrMapperIdScopeSpec,
12438 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012439 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012440 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012441 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12442 EndLoc, ReductionOrMapperIdScopeSpec,
12443 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012444 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012445 case OMPC_linear:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012446 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
12447 "Unexpected linear modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012448 Res = ActOnOpenMPLinearClause(
12449 VarList, TailExpr, StartLoc, LParenLoc,
12450 static_cast<OpenMPLinearClauseKind>(ExtraModifier), DepLinMapLastLoc,
12451 ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012452 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012453 case OMPC_aligned:
12454 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12455 ColonLoc, EndLoc);
12456 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012457 case OMPC_copyin:
12458 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12459 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012460 case OMPC_copyprivate:
12461 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12462 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012463 case OMPC_flush:
12464 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12465 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012466 case OMPC_depend:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012467 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
12468 "Unexpected depend modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012469 Res = ActOnOpenMPDependClause(
12470 static_cast<OpenMPDependClauseKind>(ExtraModifier), DepLinMapLastLoc,
12471 ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012472 break;
12473 case OMPC_map:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012474 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
12475 "Unexpected map modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012476 Res = ActOnOpenMPMapClause(
12477 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
12478 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
12479 IsMapTypeImplicit, DepLinMapLastLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012480 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012481 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012482 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12483 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012484 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012485 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012486 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12487 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012488 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012489 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012490 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012491 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012492 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012493 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012494 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012495 case OMPC_allocate:
12496 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12497 ColonLoc, EndLoc);
12498 break;
Alexey Bataevb6e70842019-12-16 15:54:17 -050012499 case OMPC_nontemporal:
12500 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
12501 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012502 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012503 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012504 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012505 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012506 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012507 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012508 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012509 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012510 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012511 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012512 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012513 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012514 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012515 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012516 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012517 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012518 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012519 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012520 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012521 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012522 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012523 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012524 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012525 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012526 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012527 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012528 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012529 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012530 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012531 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012532 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012533 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012534 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012535 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012536 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012537 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012538 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012539 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012540 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012541 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012542 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012543 llvm_unreachable("Clause is not allowed.");
12544 }
12545 return Res;
12546}
12547
Alexey Bataev90c228f2016-02-08 09:29:13 +000012548ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012549 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012550 ExprResult Res = BuildDeclRefExpr(
12551 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12552 if (!Res.isUsable())
12553 return ExprError();
12554 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12555 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12556 if (!Res.isUsable())
12557 return ExprError();
12558 }
12559 if (VK != VK_LValue && Res.get()->isGLValue()) {
12560 Res = DefaultLvalueConversion(Res.get());
12561 if (!Res.isUsable())
12562 return ExprError();
12563 }
12564 return Res;
12565}
12566
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012567OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12568 SourceLocation StartLoc,
12569 SourceLocation LParenLoc,
12570 SourceLocation EndLoc) {
12571 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012572 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012573 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012574 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012575 SourceLocation ELoc;
12576 SourceRange ERange;
12577 Expr *SimpleRefExpr = RefExpr;
12578 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012579 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012580 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012581 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012582 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012583 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012584 ValueDecl *D = Res.first;
12585 if (!D)
12586 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012587
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012588 QualType Type = D->getType();
12589 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012590
12591 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12592 // A variable that appears in a private clause must not have an incomplete
12593 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012594 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012595 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012596 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012597
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012598 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12599 // A variable that is privatized must not have a const-qualified type
12600 // unless it is of class type with a mutable member. This restriction does
12601 // not apply to the firstprivate clause.
12602 //
12603 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12604 // A variable that appears in a private clause must not have a
12605 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012606 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012607 continue;
12608
Alexey Bataev758e55e2013-09-06 18:03:48 +000012609 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12610 // in a Construct]
12611 // Variables with the predetermined data-sharing attributes may not be
12612 // listed in data-sharing attributes clauses, except for the cases
12613 // listed below. For these exceptions only, listing a predetermined
12614 // variable in a data-sharing attribute clause is allowed and overrides
12615 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012616 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012617 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012618 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12619 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012620 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012621 continue;
12622 }
12623
Alexey Bataeve3727102018-04-18 15:57:46 +000012624 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012625 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012626 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012627 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012628 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12629 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012630 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012631 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012632 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012633 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012634 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012635 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012636 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012637 continue;
12638 }
12639
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012640 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12641 // A list item cannot appear in both a map clause and a data-sharing
12642 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012643 //
12644 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12645 // A list item cannot appear in both a map clause and a data-sharing
12646 // attribute clause on the same construct unless the construct is a
12647 // combined construct.
12648 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12649 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012650 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012651 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012652 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012653 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12654 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12655 ConflictKind = WhereFoundClauseKind;
12656 return true;
12657 })) {
12658 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012659 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012660 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012661 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012662 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012663 continue;
12664 }
12665 }
12666
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012667 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12668 // A variable of class type (or array thereof) that appears in a private
12669 // clause requires an accessible, unambiguous default constructor for the
12670 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012671 // Generate helper private variable and initialize it with the default
12672 // value. The address of the original variable is replaced by the address of
12673 // the new private variable in CodeGen. This new variable is not added to
12674 // IdResolver, so the code in the OpenMP region uses original variable for
12675 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012676 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012677 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012678 buildVarDecl(*this, ELoc, Type, D->getName(),
12679 D->hasAttrs() ? &D->getAttrs() : nullptr,
12680 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012681 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012682 if (VDPrivate->isInvalidDecl())
12683 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012684 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012685 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012686
Alexey Bataev90c228f2016-02-08 09:29:13 +000012687 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012688 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012689 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012690 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012691 Vars.push_back((VD || CurContext->isDependentContext())
12692 ? RefExpr->IgnoreParens()
12693 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012694 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012695 }
12696
Alexey Bataeved09d242014-05-28 05:53:51 +000012697 if (Vars.empty())
12698 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012699
Alexey Bataev03b340a2014-10-21 03:16:40 +000012700 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12701 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012702}
12703
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012704namespace {
12705class DiagsUninitializedSeveretyRAII {
12706private:
12707 DiagnosticsEngine &Diags;
12708 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012709 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012710
12711public:
12712 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12713 bool IsIgnored)
12714 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12715 if (!IsIgnored) {
12716 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12717 /*Map*/ diag::Severity::Ignored, Loc);
12718 }
12719 }
12720 ~DiagsUninitializedSeveretyRAII() {
12721 if (!IsIgnored)
12722 Diags.popMappings(SavedLoc);
12723 }
12724};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012725}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012726
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012727OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12728 SourceLocation StartLoc,
12729 SourceLocation LParenLoc,
12730 SourceLocation EndLoc) {
12731 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012732 SmallVector<Expr *, 8> PrivateCopies;
12733 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012734 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012735 bool IsImplicitClause =
12736 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012737 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012738
Alexey Bataeve3727102018-04-18 15:57:46 +000012739 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012740 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012741 SourceLocation ELoc;
12742 SourceRange ERange;
12743 Expr *SimpleRefExpr = RefExpr;
12744 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012745 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012746 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012747 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012748 PrivateCopies.push_back(nullptr);
12749 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012750 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012751 ValueDecl *D = Res.first;
12752 if (!D)
12753 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012754
Alexey Bataev60da77e2016-02-29 05:54:20 +000012755 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012756 QualType Type = D->getType();
12757 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012758
12759 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12760 // A variable that appears in a private clause must not have an incomplete
12761 // type or a reference type.
12762 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012763 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012764 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012765 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012766
12767 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12768 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012769 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012770 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012771 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012772
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012773 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012774 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012775 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012776 DSAStackTy::DSAVarData DVar =
12777 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012778 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012779 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012780 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012781 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12782 // A list item that specifies a given variable may not appear in more
12783 // than one clause on the same directive, except that a variable may be
12784 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012785 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12786 // A list item may appear in a firstprivate or lastprivate clause but not
12787 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012788 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012789 (isOpenMPDistributeDirective(CurrDir) ||
12790 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012791 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012792 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012793 << getOpenMPClauseName(DVar.CKind)
12794 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012795 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012796 continue;
12797 }
12798
12799 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12800 // in a Construct]
12801 // Variables with the predetermined data-sharing attributes may not be
12802 // listed in data-sharing attributes clauses, except for the cases
12803 // listed below. For these exceptions only, listing a predetermined
12804 // variable in a data-sharing attribute clause is allowed and overrides
12805 // the variable's predetermined data-sharing attributes.
12806 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12807 // in a Construct, C/C++, p.2]
12808 // Variables with const-qualified type having no mutable member may be
12809 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012810 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012811 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12812 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012813 << getOpenMPClauseName(DVar.CKind)
12814 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012815 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012816 continue;
12817 }
12818
12819 // OpenMP [2.9.3.4, Restrictions, p.2]
12820 // A list item that is private within a parallel region must not appear
12821 // in a firstprivate clause on a worksharing construct if any of the
12822 // worksharing regions arising from the worksharing construct ever bind
12823 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012824 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12825 // A list item that is private within a teams region must not appear in a
12826 // firstprivate clause on a distribute construct if any of the distribute
12827 // regions arising from the distribute construct ever bind to any of the
12828 // teams regions arising from the teams construct.
12829 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12830 // A list item that appears in a reduction clause of a teams construct
12831 // must not appear in a firstprivate clause on a distribute construct if
12832 // any of the distribute regions arising from the distribute construct
12833 // ever bind to any of the teams regions arising from the teams construct.
12834 if ((isOpenMPWorksharingDirective(CurrDir) ||
12835 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012836 !isOpenMPParallelDirective(CurrDir) &&
12837 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012838 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012839 if (DVar.CKind != OMPC_shared &&
12840 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012841 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012842 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012843 Diag(ELoc, diag::err_omp_required_access)
12844 << getOpenMPClauseName(OMPC_firstprivate)
12845 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012846 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012847 continue;
12848 }
12849 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012850 // OpenMP [2.9.3.4, Restrictions, p.3]
12851 // A list item that appears in a reduction clause of a parallel construct
12852 // must not appear in a firstprivate clause on a worksharing or task
12853 // construct if any of the worksharing or task regions arising from the
12854 // worksharing or task construct ever bind to any of the parallel regions
12855 // arising from the parallel construct.
12856 // OpenMP [2.9.3.4, Restrictions, p.4]
12857 // A list item that appears in a reduction clause in worksharing
12858 // construct must not appear in a firstprivate clause in a task construct
12859 // encountered during execution of any of the worksharing regions arising
12860 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012861 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012862 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012863 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12864 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012865 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012866 isOpenMPWorksharingDirective(K) ||
12867 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012868 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012869 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012870 if (DVar.CKind == OMPC_reduction &&
12871 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012872 isOpenMPWorksharingDirective(DVar.DKind) ||
12873 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012874 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12875 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012876 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012877 continue;
12878 }
12879 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012880
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012881 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12882 // A list item cannot appear in both a map clause and a data-sharing
12883 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012884 //
12885 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12886 // A list item cannot appear in both a map clause and a data-sharing
12887 // attribute clause on the same construct unless the construct is a
12888 // combined construct.
12889 if ((LangOpts.OpenMP <= 45 &&
12890 isOpenMPTargetExecutionDirective(CurrDir)) ||
12891 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012892 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012893 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012894 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012895 [&ConflictKind](
12896 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12897 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012898 ConflictKind = WhereFoundClauseKind;
12899 return true;
12900 })) {
12901 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012902 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012903 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012904 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012905 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012906 continue;
12907 }
12908 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012909 }
12910
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012911 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012912 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012913 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012914 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12915 << getOpenMPClauseName(OMPC_firstprivate) << Type
12916 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12917 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012918 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012919 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012920 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012921 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012922 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012923 continue;
12924 }
12925
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012926 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012927 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012928 buildVarDecl(*this, ELoc, Type, D->getName(),
12929 D->hasAttrs() ? &D->getAttrs() : nullptr,
12930 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012931 // Generate helper private variable and initialize it with the value of the
12932 // original variable. The address of the original variable is replaced by
12933 // the address of the new private variable in the CodeGen. This new variable
12934 // is not added to IdResolver, so the code in the OpenMP region uses
12935 // original variable for proper diagnostics and variable capturing.
12936 Expr *VDInitRefExpr = nullptr;
12937 // For arrays generate initializer for single element and replace it by the
12938 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012939 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012940 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012941 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012942 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012943 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012944 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012945 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12946 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012947 InitializedEntity Entity =
12948 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012949 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12950
12951 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12952 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12953 if (Result.isInvalid())
12954 VDPrivate->setInvalidDecl();
12955 else
12956 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012957 // Remove temp variable declaration.
12958 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012959 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012960 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12961 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012962 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12963 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012964 AddInitializerToDecl(VDPrivate,
12965 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012966 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012967 }
12968 if (VDPrivate->isInvalidDecl()) {
12969 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012970 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012971 diag::note_omp_task_predetermined_firstprivate_here);
12972 }
12973 continue;
12974 }
12975 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012976 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012977 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12978 RefExpr->getExprLoc());
12979 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012980 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012981 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012982 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012983 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012984 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012985 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012986 ExprCaptures.push_back(Ref->getDecl());
12987 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012988 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012989 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012990 Vars.push_back((VD || CurContext->isDependentContext())
12991 ? RefExpr->IgnoreParens()
12992 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012993 PrivateCopies.push_back(VDPrivateRefExpr);
12994 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012995 }
12996
Alexey Bataeved09d242014-05-28 05:53:51 +000012997 if (Vars.empty())
12998 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012999
13000 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013001 Vars, PrivateCopies, Inits,
13002 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013003}
13004
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013005OMPClause *Sema::ActOnOpenMPLastprivateClause(
13006 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
13007 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
13008 SourceLocation LParenLoc, SourceLocation EndLoc) {
13009 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
13010 assert(ColonLoc.isValid() && "Colon location must be valid.");
13011 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
13012 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
13013 /*Last=*/OMPC_LASTPRIVATE_unknown)
13014 << getOpenMPClauseName(OMPC_lastprivate);
13015 return nullptr;
13016 }
13017
Alexander Musman1bb328c2014-06-04 13:06:39 +000013018 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000013019 SmallVector<Expr *, 8> SrcExprs;
13020 SmallVector<Expr *, 8> DstExprs;
13021 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000013022 SmallVector<Decl *, 4> ExprCaptures;
13023 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000013024 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013025 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013026 SourceLocation ELoc;
13027 SourceRange ERange;
13028 Expr *SimpleRefExpr = RefExpr;
13029 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000013030 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013031 // It will be analyzed later.
13032 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013033 SrcExprs.push_back(nullptr);
13034 DstExprs.push_back(nullptr);
13035 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013036 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013037 ValueDecl *D = Res.first;
13038 if (!D)
13039 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013040
Alexey Bataev74caaf22016-02-20 04:09:36 +000013041 QualType Type = D->getType();
13042 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013043
13044 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
13045 // A variable that appears in a lastprivate clause must not have an
13046 // incomplete type or a reference type.
13047 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000013048 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000013049 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013050 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013051
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013052 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13053 // A variable that is privatized must not have a const-qualified type
13054 // unless it is of class type with a mutable member. This restriction does
13055 // not apply to the firstprivate clause.
13056 //
13057 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
13058 // A variable that appears in a lastprivate clause must not have a
13059 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013060 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013061 continue;
13062
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013063 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
13064 // A list item that appears in a lastprivate clause with the conditional
13065 // modifier must be a scalar variable.
13066 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
13067 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
13068 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13069 VarDecl::DeclarationOnly;
13070 Diag(D->getLocation(),
13071 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13072 << D;
13073 continue;
13074 }
13075
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013076 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013077 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13078 // in a Construct]
13079 // Variables with the predetermined data-sharing attributes may not be
13080 // listed in data-sharing attributes clauses, except for the cases
13081 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013082 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13083 // A list item may appear in a firstprivate or lastprivate clause but not
13084 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000013085 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013086 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000013087 (isOpenMPDistributeDirective(CurrDir) ||
13088 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000013089 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
13090 Diag(ELoc, diag::err_omp_wrong_dsa)
13091 << getOpenMPClauseName(DVar.CKind)
13092 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013093 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013094 continue;
13095 }
13096
Alexey Bataevf29276e2014-06-18 04:14:57 +000013097 // OpenMP [2.14.3.5, Restrictions, p.2]
13098 // A list item that is private within a parallel region, or that appears in
13099 // the reduction clause of a parallel construct, must not appear in a
13100 // lastprivate clause on a worksharing construct if any of the corresponding
13101 // worksharing regions ever binds to any of the corresponding parallel
13102 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000013103 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000013104 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013105 !isOpenMPParallelDirective(CurrDir) &&
13106 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000013107 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013108 if (DVar.CKind != OMPC_shared) {
13109 Diag(ELoc, diag::err_omp_required_access)
13110 << getOpenMPClauseName(OMPC_lastprivate)
13111 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013112 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013113 continue;
13114 }
13115 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013116
Alexander Musman1bb328c2014-06-04 13:06:39 +000013117 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000013118 // A variable of class type (or array thereof) that appears in a
13119 // lastprivate clause requires an accessible, unambiguous default
13120 // constructor for the class type, unless the list item is also specified
13121 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000013122 // A variable of class type (or array thereof) that appears in a
13123 // lastprivate clause requires an accessible, unambiguous copy assignment
13124 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000013125 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013126 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
13127 Type.getUnqualifiedType(), ".lastprivate.src",
13128 D->hasAttrs() ? &D->getAttrs() : nullptr);
13129 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000013130 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013131 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013132 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000013133 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013134 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000013135 // For arrays generate assignment operation for single element and replace
13136 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013137 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
13138 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013139 if (AssignmentOp.isInvalid())
13140 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013141 AssignmentOp =
13142 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000013143 if (AssignmentOp.isInvalid())
13144 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013145
Alexey Bataev74caaf22016-02-20 04:09:36 +000013146 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013147 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013148 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013149 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013150 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013151 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013152 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013153 ExprCaptures.push_back(Ref->getDecl());
13154 }
13155 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013156 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013157 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013158 ExprResult RefRes = DefaultLvalueConversion(Ref);
13159 if (!RefRes.isUsable())
13160 continue;
13161 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013162 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13163 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013164 if (!PostUpdateRes.isUsable())
13165 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013166 ExprPostUpdates.push_back(
13167 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013168 }
13169 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013170 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013171 Vars.push_back((VD || CurContext->isDependentContext())
13172 ? RefExpr->IgnoreParens()
13173 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000013174 SrcExprs.push_back(PseudoSrcExpr);
13175 DstExprs.push_back(PseudoDstExpr);
13176 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000013177 }
13178
13179 if (Vars.empty())
13180 return nullptr;
13181
13182 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000013183 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013184 LPKind, LPKindLoc, ColonLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013185 buildPreInits(Context, ExprCaptures),
13186 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000013187}
13188
Alexey Bataev758e55e2013-09-06 18:03:48 +000013189OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
13190 SourceLocation StartLoc,
13191 SourceLocation LParenLoc,
13192 SourceLocation EndLoc) {
13193 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013194 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013195 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013196 SourceLocation ELoc;
13197 SourceRange ERange;
13198 Expr *SimpleRefExpr = RefExpr;
13199 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013200 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000013201 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013202 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013203 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013204 ValueDecl *D = Res.first;
13205 if (!D)
13206 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013207
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013208 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013209 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13210 // in a Construct]
13211 // Variables with the predetermined data-sharing attributes may not be
13212 // listed in data-sharing attributes clauses, except for the cases
13213 // listed below. For these exceptions only, listing a predetermined
13214 // variable in a data-sharing attribute clause is allowed and overrides
13215 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000013216 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000013217 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
13218 DVar.RefExpr) {
13219 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13220 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013221 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013222 continue;
13223 }
13224
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013225 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013226 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000013227 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013228 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013229 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
13230 ? RefExpr->IgnoreParens()
13231 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013232 }
13233
Alexey Bataeved09d242014-05-28 05:53:51 +000013234 if (Vars.empty())
13235 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013236
13237 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13238}
13239
Alexey Bataevc5e02582014-06-16 07:08:35 +000013240namespace {
13241class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13242 DSAStackTy *Stack;
13243
13244public:
13245 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013246 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13247 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013248 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13249 return false;
13250 if (DVar.CKind != OMPC_unknown)
13251 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013252 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013253 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013254 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013255 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013256 }
13257 return false;
13258 }
13259 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013260 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013261 if (Child && Visit(Child))
13262 return true;
13263 }
13264 return false;
13265 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013266 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013267};
Alexey Bataev23b69422014-06-18 07:08:49 +000013268} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013269
Alexey Bataev60da77e2016-02-29 05:54:20 +000013270namespace {
13271// Transform MemberExpression for specified FieldDecl of current class to
13272// DeclRefExpr to specified OMPCapturedExprDecl.
13273class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13274 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013275 ValueDecl *Field = nullptr;
13276 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013277
13278public:
13279 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13280 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13281
13282 ExprResult TransformMemberExpr(MemberExpr *E) {
13283 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13284 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013285 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013286 return CapturedExpr;
13287 }
13288 return BaseTransform::TransformMemberExpr(E);
13289 }
13290 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13291};
13292} // namespace
13293
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013294template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013295static T filterLookupForUDReductionAndMapper(
13296 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013297 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013298 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013299 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013300 return Res;
13301 }
13302 }
13303 return T();
13304}
13305
Alexey Bataev43b90b72018-09-12 16:31:59 +000013306static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13307 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13308
13309 for (auto RD : D->redecls()) {
13310 // Don't bother with extra checks if we already know this one isn't visible.
13311 if (RD == D)
13312 continue;
13313
13314 auto ND = cast<NamedDecl>(RD);
13315 if (LookupResult::isVisible(SemaRef, ND))
13316 return ND;
13317 }
13318
13319 return nullptr;
13320}
13321
13322static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013323argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013324 SourceLocation Loc, QualType Ty,
13325 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13326 // Find all of the associated namespaces and classes based on the
13327 // arguments we have.
13328 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13329 Sema::AssociatedClassSet AssociatedClasses;
13330 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13331 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13332 AssociatedClasses);
13333
13334 // C++ [basic.lookup.argdep]p3:
13335 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13336 // and let Y be the lookup set produced by argument dependent
13337 // lookup (defined as follows). If X contains [...] then Y is
13338 // empty. Otherwise Y is the set of declarations found in the
13339 // namespaces associated with the argument types as described
13340 // below. The set of declarations found by the lookup of the name
13341 // is the union of X and Y.
13342 //
13343 // Here, we compute Y and add its members to the overloaded
13344 // candidate set.
13345 for (auto *NS : AssociatedNamespaces) {
13346 // When considering an associated namespace, the lookup is the
13347 // same as the lookup performed when the associated namespace is
13348 // used as a qualifier (3.4.3.2) except that:
13349 //
13350 // -- Any using-directives in the associated namespace are
13351 // ignored.
13352 //
13353 // -- Any namespace-scope friend functions declared in
13354 // associated classes are visible within their respective
13355 // namespaces even if they are not visible during an ordinary
13356 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013357 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013358 for (auto *D : R) {
13359 auto *Underlying = D;
13360 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13361 Underlying = USD->getTargetDecl();
13362
Michael Kruse4304e9d2019-02-19 16:38:20 +000013363 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13364 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013365 continue;
13366
13367 if (!SemaRef.isVisible(D)) {
13368 D = findAcceptableDecl(SemaRef, D);
13369 if (!D)
13370 continue;
13371 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13372 Underlying = USD->getTargetDecl();
13373 }
13374 Lookups.emplace_back();
13375 Lookups.back().addDecl(Underlying);
13376 }
13377 }
13378}
13379
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013380static ExprResult
13381buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13382 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13383 const DeclarationNameInfo &ReductionId, QualType Ty,
13384 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13385 if (ReductionIdScopeSpec.isInvalid())
13386 return ExprError();
13387 SmallVector<UnresolvedSet<8>, 4> Lookups;
13388 if (S) {
13389 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13390 Lookup.suppressDiagnostics();
13391 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013392 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013393 do {
13394 S = S->getParent();
13395 } while (S && !S->isDeclScope(D));
13396 if (S)
13397 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013398 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013399 Lookups.back().append(Lookup.begin(), Lookup.end());
13400 Lookup.clear();
13401 }
13402 } else if (auto *ULE =
13403 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13404 Lookups.push_back(UnresolvedSet<8>());
13405 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013406 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013407 if (D == PrevD)
13408 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013409 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013410 Lookups.back().addDecl(DRD);
13411 PrevD = D;
13412 }
13413 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013414 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13415 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013416 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013417 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013418 return !D->isInvalidDecl() &&
13419 (D->getType()->isDependentType() ||
13420 D->getType()->isInstantiationDependentType() ||
13421 D->getType()->containsUnexpandedParameterPack());
13422 })) {
13423 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013424 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013425 if (Set.empty())
13426 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013427 ResSet.append(Set.begin(), Set.end());
13428 // The last item marks the end of all declarations at the specified scope.
13429 ResSet.addDecl(Set[Set.size() - 1]);
13430 }
13431 return UnresolvedLookupExpr::Create(
13432 SemaRef.Context, /*NamingClass=*/nullptr,
13433 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13434 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13435 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013436 // Lookup inside the classes.
13437 // C++ [over.match.oper]p3:
13438 // For a unary operator @ with an operand of a type whose
13439 // cv-unqualified version is T1, and for a binary operator @ with
13440 // a left operand of a type whose cv-unqualified version is T1 and
13441 // a right operand of a type whose cv-unqualified version is T2,
13442 // three sets of candidate functions, designated member
13443 // candidates, non-member candidates and built-in candidates, are
13444 // constructed as follows:
13445 // -- If T1 is a complete class type or a class currently being
13446 // defined, the set of member candidates is the result of the
13447 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13448 // the set of member candidates is empty.
13449 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13450 Lookup.suppressDiagnostics();
13451 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13452 // Complete the type if it can be completed.
13453 // If the type is neither complete nor being defined, bail out now.
13454 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13455 TyRec->getDecl()->getDefinition()) {
13456 Lookup.clear();
13457 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13458 if (Lookup.empty()) {
13459 Lookups.emplace_back();
13460 Lookups.back().append(Lookup.begin(), Lookup.end());
13461 }
13462 }
13463 }
13464 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013465 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013466 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013467 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13468 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13469 if (!D->isInvalidDecl() &&
13470 SemaRef.Context.hasSameType(D->getType(), Ty))
13471 return D;
13472 return nullptr;
13473 }))
13474 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13475 VK_LValue, Loc);
13476 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013477 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13478 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13479 if (!D->isInvalidDecl() &&
13480 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13481 !Ty.isMoreQualifiedThan(D->getType()))
13482 return D;
13483 return nullptr;
13484 })) {
13485 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13486 /*DetectVirtual=*/false);
13487 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13488 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13489 VD->getType().getUnqualifiedType()))) {
13490 if (SemaRef.CheckBaseClassAccess(
13491 Loc, VD->getType(), Ty, Paths.front(),
13492 /*DiagID=*/0) != Sema::AR_inaccessible) {
13493 SemaRef.BuildBasePathArray(Paths, BasePath);
13494 return SemaRef.BuildDeclRefExpr(
13495 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13496 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013497 }
13498 }
13499 }
13500 }
13501 if (ReductionIdScopeSpec.isSet()) {
13502 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
13503 return ExprError();
13504 }
13505 return ExprEmpty();
13506}
13507
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013508namespace {
13509/// Data for the reduction-based clauses.
13510struct ReductionData {
13511 /// List of original reduction items.
13512 SmallVector<Expr *, 8> Vars;
13513 /// List of private copies of the reduction items.
13514 SmallVector<Expr *, 8> Privates;
13515 /// LHS expressions for the reduction_op expressions.
13516 SmallVector<Expr *, 8> LHSs;
13517 /// RHS expressions for the reduction_op expressions.
13518 SmallVector<Expr *, 8> RHSs;
13519 /// Reduction operation expression.
13520 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013521 /// Taskgroup descriptors for the corresponding reduction items in
13522 /// in_reduction clauses.
13523 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013524 /// List of captures for clause.
13525 SmallVector<Decl *, 4> ExprCaptures;
13526 /// List of postupdate expressions.
13527 SmallVector<Expr *, 4> ExprPostUpdates;
13528 ReductionData() = delete;
13529 /// Reserves required memory for the reduction data.
13530 ReductionData(unsigned Size) {
13531 Vars.reserve(Size);
13532 Privates.reserve(Size);
13533 LHSs.reserve(Size);
13534 RHSs.reserve(Size);
13535 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013536 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013537 ExprCaptures.reserve(Size);
13538 ExprPostUpdates.reserve(Size);
13539 }
13540 /// Stores reduction item and reduction operation only (required for dependent
13541 /// reduction item).
13542 void push(Expr *Item, Expr *ReductionOp) {
13543 Vars.emplace_back(Item);
13544 Privates.emplace_back(nullptr);
13545 LHSs.emplace_back(nullptr);
13546 RHSs.emplace_back(nullptr);
13547 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013548 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013549 }
13550 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013551 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13552 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013553 Vars.emplace_back(Item);
13554 Privates.emplace_back(Private);
13555 LHSs.emplace_back(LHS);
13556 RHSs.emplace_back(RHS);
13557 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013558 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013559 }
13560};
13561} // namespace
13562
Alexey Bataeve3727102018-04-18 15:57:46 +000013563static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013564 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13565 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13566 const Expr *Length = OASE->getLength();
13567 if (Length == nullptr) {
13568 // For array sections of the form [1:] or [:], we would need to analyze
13569 // the lower bound...
13570 if (OASE->getColonLoc().isValid())
13571 return false;
13572
13573 // This is an array subscript which has implicit length 1!
13574 SingleElement = true;
13575 ArraySizes.push_back(llvm::APSInt::get(1));
13576 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013577 Expr::EvalResult Result;
13578 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013579 return false;
13580
Fangrui Song407659a2018-11-30 23:41:18 +000013581 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013582 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13583 ArraySizes.push_back(ConstantLengthValue);
13584 }
13585
13586 // Get the base of this array section and walk up from there.
13587 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13588
13589 // We require length = 1 for all array sections except the right-most to
13590 // guarantee that the memory region is contiguous and has no holes in it.
13591 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13592 Length = TempOASE->getLength();
13593 if (Length == nullptr) {
13594 // For array sections of the form [1:] or [:], we would need to analyze
13595 // the lower bound...
13596 if (OASE->getColonLoc().isValid())
13597 return false;
13598
13599 // This is an array subscript which has implicit length 1!
13600 ArraySizes.push_back(llvm::APSInt::get(1));
13601 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013602 Expr::EvalResult Result;
13603 if (!Length->EvaluateAsInt(Result, Context))
13604 return false;
13605
13606 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13607 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013608 return false;
13609
13610 ArraySizes.push_back(ConstantLengthValue);
13611 }
13612 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13613 }
13614
13615 // If we have a single element, we don't need to add the implicit lengths.
13616 if (!SingleElement) {
13617 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13618 // Has implicit length 1!
13619 ArraySizes.push_back(llvm::APSInt::get(1));
13620 Base = TempASE->getBase()->IgnoreParenImpCasts();
13621 }
13622 }
13623
13624 // This array section can be privatized as a single value or as a constant
13625 // sized array.
13626 return true;
13627}
13628
Alexey Bataeve3727102018-04-18 15:57:46 +000013629static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013630 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13631 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13632 SourceLocation ColonLoc, SourceLocation EndLoc,
13633 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013634 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013635 DeclarationName DN = ReductionId.getName();
13636 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013637 BinaryOperatorKind BOK = BO_Comma;
13638
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013639 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013640 // OpenMP [2.14.3.6, reduction clause]
13641 // C
13642 // reduction-identifier is either an identifier or one of the following
13643 // operators: +, -, *, &, |, ^, && and ||
13644 // C++
13645 // reduction-identifier is either an id-expression or one of the following
13646 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013647 switch (OOK) {
13648 case OO_Plus:
13649 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013650 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013651 break;
13652 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013653 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013654 break;
13655 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013656 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013657 break;
13658 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013659 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013660 break;
13661 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013662 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013663 break;
13664 case OO_AmpAmp:
13665 BOK = BO_LAnd;
13666 break;
13667 case OO_PipePipe:
13668 BOK = BO_LOr;
13669 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013670 case OO_New:
13671 case OO_Delete:
13672 case OO_Array_New:
13673 case OO_Array_Delete:
13674 case OO_Slash:
13675 case OO_Percent:
13676 case OO_Tilde:
13677 case OO_Exclaim:
13678 case OO_Equal:
13679 case OO_Less:
13680 case OO_Greater:
13681 case OO_LessEqual:
13682 case OO_GreaterEqual:
13683 case OO_PlusEqual:
13684 case OO_MinusEqual:
13685 case OO_StarEqual:
13686 case OO_SlashEqual:
13687 case OO_PercentEqual:
13688 case OO_CaretEqual:
13689 case OO_AmpEqual:
13690 case OO_PipeEqual:
13691 case OO_LessLess:
13692 case OO_GreaterGreater:
13693 case OO_LessLessEqual:
13694 case OO_GreaterGreaterEqual:
13695 case OO_EqualEqual:
13696 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013697 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013698 case OO_PlusPlus:
13699 case OO_MinusMinus:
13700 case OO_Comma:
13701 case OO_ArrowStar:
13702 case OO_Arrow:
13703 case OO_Call:
13704 case OO_Subscript:
13705 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013706 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013707 case NUM_OVERLOADED_OPERATORS:
13708 llvm_unreachable("Unexpected reduction identifier");
13709 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013710 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013711 if (II->isStr("max"))
13712 BOK = BO_GT;
13713 else if (II->isStr("min"))
13714 BOK = BO_LT;
13715 }
13716 break;
13717 }
13718 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013719 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013720 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013721 else
13722 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013723 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013724
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013725 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13726 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013727 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013728 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013729 // OpenMP [2.1, C/C++]
13730 // A list item is a variable or array section, subject to the restrictions
13731 // specified in Section 2.4 on page 42 and in each of the sections
13732 // describing clauses and directives for which a list appears.
13733 // OpenMP [2.14.3.3, Restrictions, p.1]
13734 // A variable that is part of another variable (as an array or
13735 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013736 if (!FirstIter && IR != ER)
13737 ++IR;
13738 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013739 SourceLocation ELoc;
13740 SourceRange ERange;
13741 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013742 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013743 /*AllowArraySection=*/true);
13744 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013745 // Try to find 'declare reduction' corresponding construct before using
13746 // builtin/overloaded operators.
13747 QualType Type = Context.DependentTy;
13748 CXXCastPath BasePath;
13749 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013750 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013751 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013752 Expr *ReductionOp = nullptr;
13753 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013754 (DeclareReductionRef.isUnset() ||
13755 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013756 ReductionOp = DeclareReductionRef.get();
13757 // It will be analyzed later.
13758 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013759 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013760 ValueDecl *D = Res.first;
13761 if (!D)
13762 continue;
13763
Alexey Bataev88202be2017-07-27 13:20:36 +000013764 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013765 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013766 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13767 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013768 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013769 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013770 } else if (OASE) {
13771 QualType BaseType =
13772 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13773 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013774 Type = ATy->getElementType();
13775 else
13776 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013777 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013778 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013779 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013780 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013781 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013782
Alexey Bataevc5e02582014-06-16 07:08:35 +000013783 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13784 // A variable that appears in a private clause must not have an incomplete
13785 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013786 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013787 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013788 continue;
13789 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013790 // A list item that appears in a reduction clause must not be
13791 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013792 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13793 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013794 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013795
13796 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013797 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13798 // If a list-item is a reference type then it must bind to the same object
13799 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013800 if (!ASE && !OASE) {
13801 if (VD) {
13802 VarDecl *VDDef = VD->getDefinition();
13803 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13804 DSARefChecker Check(Stack);
13805 if (Check.Visit(VDDef->getInit())) {
13806 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13807 << getOpenMPClauseName(ClauseKind) << ERange;
13808 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13809 continue;
13810 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013811 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013812 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013813
Alexey Bataevbc529672018-09-28 19:33:14 +000013814 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13815 // in a Construct]
13816 // Variables with the predetermined data-sharing attributes may not be
13817 // listed in data-sharing attributes clauses, except for the cases
13818 // listed below. For these exceptions only, listing a predetermined
13819 // variable in a data-sharing attribute clause is allowed and overrides
13820 // the variable's predetermined data-sharing attributes.
13821 // OpenMP [2.14.3.6, Restrictions, p.3]
13822 // Any number of reduction clauses can be specified on the directive,
13823 // but a list item can appear only once in the reduction clauses for that
13824 // directive.
13825 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13826 if (DVar.CKind == OMPC_reduction) {
13827 S.Diag(ELoc, diag::err_omp_once_referenced)
13828 << getOpenMPClauseName(ClauseKind);
13829 if (DVar.RefExpr)
13830 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13831 continue;
13832 }
13833 if (DVar.CKind != OMPC_unknown) {
13834 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13835 << getOpenMPClauseName(DVar.CKind)
13836 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013837 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013838 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013839 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013840
13841 // OpenMP [2.14.3.6, Restrictions, p.1]
13842 // A list item that appears in a reduction clause of a worksharing
13843 // construct must be shared in the parallel regions to which any of the
13844 // worksharing regions arising from the worksharing construct bind.
13845 if (isOpenMPWorksharingDirective(CurrDir) &&
13846 !isOpenMPParallelDirective(CurrDir) &&
13847 !isOpenMPTeamsDirective(CurrDir)) {
13848 DVar = Stack->getImplicitDSA(D, true);
13849 if (DVar.CKind != OMPC_shared) {
13850 S.Diag(ELoc, diag::err_omp_required_access)
13851 << getOpenMPClauseName(OMPC_reduction)
13852 << getOpenMPClauseName(OMPC_shared);
13853 reportOriginalDsa(S, Stack, D, DVar);
13854 continue;
13855 }
13856 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013857 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013858
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013859 // Try to find 'declare reduction' corresponding construct before using
13860 // builtin/overloaded operators.
13861 CXXCastPath BasePath;
13862 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013863 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013864 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13865 if (DeclareReductionRef.isInvalid())
13866 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013867 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013868 (DeclareReductionRef.isUnset() ||
13869 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013870 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013871 continue;
13872 }
13873 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13874 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013875 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013876 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013877 << Type << ReductionIdRange;
13878 continue;
13879 }
13880
13881 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13882 // The type of a list item that appears in a reduction clause must be valid
13883 // for the reduction-identifier. For a max or min reduction in C, the type
13884 // of the list item must be an allowed arithmetic data type: char, int,
13885 // float, double, or _Bool, possibly modified with long, short, signed, or
13886 // unsigned. For a max or min reduction in C++, the type of the list item
13887 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13888 // double, or bool, possibly modified with long, short, signed, or unsigned.
13889 if (DeclareReductionRef.isUnset()) {
13890 if ((BOK == BO_GT || BOK == BO_LT) &&
13891 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013892 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13893 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013894 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013895 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013896 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13897 VarDecl::DeclarationOnly;
13898 S.Diag(D->getLocation(),
13899 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013900 << D;
13901 }
13902 continue;
13903 }
13904 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013905 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013906 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13907 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013908 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013909 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13910 VarDecl::DeclarationOnly;
13911 S.Diag(D->getLocation(),
13912 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013913 << D;
13914 }
13915 continue;
13916 }
13917 }
13918
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013919 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013920 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13921 D->hasAttrs() ? &D->getAttrs() : nullptr);
13922 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13923 D->hasAttrs() ? &D->getAttrs() : nullptr);
13924 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013925
13926 // Try if we can determine constant lengths for all array sections and avoid
13927 // the VLA.
13928 bool ConstantLengthOASE = false;
13929 if (OASE) {
13930 bool SingleElement;
13931 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013932 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013933 Context, OASE, SingleElement, ArraySizes);
13934
13935 // If we don't have a single element, we must emit a constant array type.
13936 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013937 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013938 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13939 ArrayType::Normal,
13940 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013941 }
13942 }
13943
13944 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013945 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013946 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013947 if (!Context.getTargetInfo().isVLASupported()) {
13948 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13949 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13950 S.Diag(ELoc, diag::note_vla_unsupported);
13951 } else {
13952 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13953 S.targetDiag(ELoc, diag::note_vla_unsupported);
13954 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013955 continue;
13956 }
David Majnemer9d168222016-08-05 17:44:54 +000013957 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013958 // Create pseudo array type for private copy. The size for this array will
13959 // be generated during codegen.
13960 // For array subscripts or single variables Private Ty is the same as Type
13961 // (type of the variable or single array element).
13962 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013963 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013964 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013965 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013966 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013967 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013968 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013969 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013970 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013971 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013972 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13973 D->hasAttrs() ? &D->getAttrs() : nullptr,
13974 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013975 // Add initializer for private variable.
13976 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013977 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13978 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013979 if (DeclareReductionRef.isUsable()) {
13980 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13981 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13982 if (DRD->getInitializer()) {
13983 Init = DRDRef;
13984 RHSVD->setInit(DRDRef);
13985 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013986 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013987 } else {
13988 switch (BOK) {
13989 case BO_Add:
13990 case BO_Xor:
13991 case BO_Or:
13992 case BO_LOr:
13993 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13994 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013995 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013996 break;
13997 case BO_Mul:
13998 case BO_LAnd:
13999 if (Type->isScalarType() || Type->isAnyComplexType()) {
14000 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014001 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000014002 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014003 break;
14004 case BO_And: {
14005 // '&' reduction op - initializer is '~0'.
14006 QualType OrigType = Type;
14007 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
14008 Type = ComplexTy->getElementType();
14009 if (Type->isRealFloatingType()) {
14010 llvm::APFloat InitValue =
14011 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
14012 /*isIEEE=*/true);
14013 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14014 Type, ELoc);
14015 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014016 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014017 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
14018 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
14019 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14020 }
14021 if (Init && OrigType->isAnyComplexType()) {
14022 // Init = 0xFFFF + 0xFFFFi;
14023 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014024 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014025 }
14026 Type = OrigType;
14027 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014028 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014029 case BO_LT:
14030 case BO_GT: {
14031 // 'min' reduction op - initializer is 'Largest representable number in
14032 // the reduction list item type'.
14033 // 'max' reduction op - initializer is 'Least representable number in
14034 // the reduction list item type'.
14035 if (Type->isIntegerType() || Type->isPointerType()) {
14036 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014037 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014038 QualType IntTy =
14039 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
14040 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014041 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
14042 : llvm::APInt::getMinValue(Size)
14043 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
14044 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014045 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14046 if (Type->isPointerType()) {
14047 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014048 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000014049 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014050 if (CastExpr.isInvalid())
14051 continue;
14052 Init = CastExpr.get();
14053 }
14054 } else if (Type->isRealFloatingType()) {
14055 llvm::APFloat InitValue = llvm::APFloat::getLargest(
14056 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
14057 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14058 Type, ELoc);
14059 }
14060 break;
14061 }
14062 case BO_PtrMemD:
14063 case BO_PtrMemI:
14064 case BO_MulAssign:
14065 case BO_Div:
14066 case BO_Rem:
14067 case BO_Sub:
14068 case BO_Shl:
14069 case BO_Shr:
14070 case BO_LE:
14071 case BO_GE:
14072 case BO_EQ:
14073 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000014074 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014075 case BO_AndAssign:
14076 case BO_XorAssign:
14077 case BO_OrAssign:
14078 case BO_Assign:
14079 case BO_AddAssign:
14080 case BO_SubAssign:
14081 case BO_DivAssign:
14082 case BO_RemAssign:
14083 case BO_ShlAssign:
14084 case BO_ShrAssign:
14085 case BO_Comma:
14086 llvm_unreachable("Unexpected reduction operation");
14087 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014088 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014089 if (Init && DeclareReductionRef.isUnset())
14090 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
14091 else if (!Init)
14092 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014093 if (RHSVD->isInvalidDecl())
14094 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000014095 if (!RHSVD->hasInit() &&
14096 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014097 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
14098 << Type << ReductionIdRange;
14099 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14100 VarDecl::DeclarationOnly;
14101 S.Diag(D->getLocation(),
14102 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000014103 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014104 continue;
14105 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014106 // Store initializer for single element in private copy. Will be used during
14107 // codegen.
14108 PrivateVD->setInit(RHSVD->getInit());
14109 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000014110 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014111 ExprResult ReductionOp;
14112 if (DeclareReductionRef.isUsable()) {
14113 QualType RedTy = DeclareReductionRef.get()->getType();
14114 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014115 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
14116 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014117 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014118 LHS = S.DefaultLvalueConversion(LHS.get());
14119 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014120 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14121 CK_UncheckedDerivedToBase, LHS.get(),
14122 &BasePath, LHS.get()->getValueKind());
14123 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14124 CK_UncheckedDerivedToBase, RHS.get(),
14125 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014126 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014127 FunctionProtoType::ExtProtoInfo EPI;
14128 QualType Params[] = {PtrRedTy, PtrRedTy};
14129 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
14130 auto *OVE = new (Context) OpaqueValueExpr(
14131 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014132 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014133 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000014134 ReductionOp =
14135 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014136 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014137 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014138 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014139 if (ReductionOp.isUsable()) {
14140 if (BOK != BO_LT && BOK != BO_GT) {
14141 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014142 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014143 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014144 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000014145 auto *ConditionalOp = new (Context)
14146 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
14147 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014148 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014149 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014150 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014151 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014152 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014153 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
14154 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014155 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014156 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014157 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000014158 }
14159
Alexey Bataevfa312f32017-07-21 18:48:21 +000014160 // OpenMP [2.15.4.6, Restrictions, p.2]
14161 // A list item that appears in an in_reduction clause of a task construct
14162 // must appear in a task_reduction clause of a construct associated with a
14163 // taskgroup region that includes the participating task in its taskgroup
14164 // set. The construct associated with the innermost region that meets this
14165 // condition must specify the same reduction-identifier as the in_reduction
14166 // clause.
14167 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000014168 SourceRange ParentSR;
14169 BinaryOperatorKind ParentBOK;
14170 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000014171 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000014172 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014173 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
14174 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014175 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014176 Stack->getTopMostTaskgroupReductionData(
14177 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014178 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
14179 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
14180 if (!IsParentBOK && !IsParentReductionOp) {
14181 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
14182 continue;
14183 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000014184 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
14185 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
14186 IsParentReductionOp) {
14187 bool EmitError = true;
14188 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
14189 llvm::FoldingSetNodeID RedId, ParentRedId;
14190 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
14191 DeclareReductionRef.get()->Profile(RedId, Context,
14192 /*Canonical=*/true);
14193 EmitError = RedId != ParentRedId;
14194 }
14195 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014196 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000014197 diag::err_omp_reduction_identifier_mismatch)
14198 << ReductionIdRange << RefExpr->getSourceRange();
14199 S.Diag(ParentSR.getBegin(),
14200 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000014201 << ParentSR
14202 << (IsParentBOK ? ParentBOKDSA.RefExpr
14203 : ParentReductionOpDSA.RefExpr)
14204 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000014205 continue;
14206 }
14207 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014208 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
14209 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000014210 }
14211
Alexey Bataev60da77e2016-02-29 05:54:20 +000014212 DeclRefExpr *Ref = nullptr;
14213 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014214 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014215 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014216 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000014217 VarsExpr =
14218 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
14219 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000014220 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014221 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014222 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014223 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014224 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014225 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014226 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014227 if (!RefRes.isUsable())
14228 continue;
14229 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014230 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14231 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014232 if (!PostUpdateRes.isUsable())
14233 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014234 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14235 Stack->getCurrentDirective() == OMPD_taskgroup) {
14236 S.Diag(RefExpr->getExprLoc(),
14237 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014238 << RefExpr->getSourceRange();
14239 continue;
14240 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014241 RD.ExprPostUpdates.emplace_back(
14242 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014243 }
14244 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014245 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014246 // All reduction items are still marked as reduction (to do not increase
14247 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014248 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014249 if (CurrDir == OMPD_taskgroup) {
14250 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014251 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14252 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014253 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014254 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014255 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014256 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14257 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014258 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014259 return RD.Vars.empty();
14260}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014261
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014262OMPClause *Sema::ActOnOpenMPReductionClause(
14263 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14264 SourceLocation ColonLoc, SourceLocation EndLoc,
14265 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14266 ArrayRef<Expr *> UnresolvedReductions) {
14267 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014268 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014269 StartLoc, LParenLoc, ColonLoc, EndLoc,
14270 ReductionIdScopeSpec, ReductionId,
14271 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014272 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014273
Alexey Bataevc5e02582014-06-16 07:08:35 +000014274 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014275 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14276 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14277 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14278 buildPreInits(Context, RD.ExprCaptures),
14279 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014280}
14281
Alexey Bataev169d96a2017-07-18 20:17:46 +000014282OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14283 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14284 SourceLocation ColonLoc, SourceLocation EndLoc,
14285 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14286 ArrayRef<Expr *> UnresolvedReductions) {
14287 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014288 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14289 StartLoc, LParenLoc, ColonLoc, EndLoc,
14290 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014291 UnresolvedReductions, RD))
14292 return nullptr;
14293
14294 return OMPTaskReductionClause::Create(
14295 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14296 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14297 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14298 buildPreInits(Context, RD.ExprCaptures),
14299 buildPostUpdate(*this, RD.ExprPostUpdates));
14300}
14301
Alexey Bataevfa312f32017-07-21 18:48:21 +000014302OMPClause *Sema::ActOnOpenMPInReductionClause(
14303 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14304 SourceLocation ColonLoc, SourceLocation EndLoc,
14305 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14306 ArrayRef<Expr *> UnresolvedReductions) {
14307 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014308 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014309 StartLoc, LParenLoc, ColonLoc, EndLoc,
14310 ReductionIdScopeSpec, ReductionId,
14311 UnresolvedReductions, RD))
14312 return nullptr;
14313
14314 return OMPInReductionClause::Create(
14315 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14316 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014317 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014318 buildPreInits(Context, RD.ExprCaptures),
14319 buildPostUpdate(*this, RD.ExprPostUpdates));
14320}
14321
Alexey Bataevecba70f2016-04-12 11:02:11 +000014322bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14323 SourceLocation LinLoc) {
14324 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14325 LinKind == OMPC_LINEAR_unknown) {
14326 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14327 return true;
14328 }
14329 return false;
14330}
14331
Alexey Bataeve3727102018-04-18 15:57:46 +000014332bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014333 OpenMPLinearClauseKind LinKind,
14334 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014335 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014336 // A variable must not have an incomplete type or a reference type.
14337 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14338 return true;
14339 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14340 !Type->isReferenceType()) {
14341 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14342 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14343 return true;
14344 }
14345 Type = Type.getNonReferenceType();
14346
Joel E. Dennybae586f2019-01-04 22:12:13 +000014347 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14348 // A variable that is privatized must not have a const-qualified type
14349 // unless it is of class type with a mutable member. This restriction does
14350 // not apply to the firstprivate clause.
14351 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014352 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014353
14354 // A list item must be of integral or pointer type.
14355 Type = Type.getUnqualifiedType().getCanonicalType();
14356 const auto *Ty = Type.getTypePtrOrNull();
14357 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
14358 !Ty->isPointerType())) {
14359 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14360 if (D) {
14361 bool IsDecl =
14362 !VD ||
14363 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14364 Diag(D->getLocation(),
14365 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14366 << D;
14367 }
14368 return true;
14369 }
14370 return false;
14371}
14372
Alexey Bataev182227b2015-08-20 10:54:39 +000014373OMPClause *Sema::ActOnOpenMPLinearClause(
14374 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14375 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14376 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014377 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014378 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014379 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014380 SmallVector<Decl *, 4> ExprCaptures;
14381 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014382 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014383 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014384 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014385 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014386 SourceLocation ELoc;
14387 SourceRange ERange;
14388 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014389 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014390 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014391 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014392 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014393 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014394 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014395 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014396 ValueDecl *D = Res.first;
14397 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014398 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014399
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014400 QualType Type = D->getType();
14401 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014402
14403 // OpenMP [2.14.3.7, linear clause]
14404 // A list-item cannot appear in more than one linear clause.
14405 // A list-item that appears in a linear clause cannot appear in any
14406 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014407 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014408 if (DVar.RefExpr) {
14409 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14410 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014411 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014412 continue;
14413 }
14414
Alexey Bataevecba70f2016-04-12 11:02:11 +000014415 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014416 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014417 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014418
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014419 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014420 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014421 buildVarDecl(*this, ELoc, Type, D->getName(),
14422 D->hasAttrs() ? &D->getAttrs() : nullptr,
14423 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014424 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014425 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014426 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014427 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014428 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014429 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014430 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014431 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014432 ExprCaptures.push_back(Ref->getDecl());
14433 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14434 ExprResult RefRes = DefaultLvalueConversion(Ref);
14435 if (!RefRes.isUsable())
14436 continue;
14437 ExprResult PostUpdateRes =
14438 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14439 SimpleRefExpr, RefRes.get());
14440 if (!PostUpdateRes.isUsable())
14441 continue;
14442 ExprPostUpdates.push_back(
14443 IgnoredValueConversions(PostUpdateRes.get()).get());
14444 }
14445 }
14446 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014447 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014448 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014449 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014450 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014451 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014452 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014453 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014454
14455 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014456 Vars.push_back((VD || CurContext->isDependentContext())
14457 ? RefExpr->IgnoreParens()
14458 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014459 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014460 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014461 }
14462
14463 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014464 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014465
14466 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014467 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014468 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14469 !Step->isInstantiationDependent() &&
14470 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014471 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014472 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014473 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014474 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014475 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014476
Alexander Musman3276a272015-03-21 10:12:56 +000014477 // Build var to save the step value.
14478 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014479 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014480 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014481 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014482 ExprResult CalcStep =
14483 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014484 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014485
Alexander Musman8dba6642014-04-22 13:09:42 +000014486 // Warn about zero linear step (it would be probably better specified as
14487 // making corresponding variables 'const').
14488 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014489 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14490 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014491 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14492 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014493 if (!IsConstant && CalcStep.isUsable()) {
14494 // Calculate the step beforehand instead of doing this on each iteration.
14495 // (This is not used if the number of iterations may be kfold-ed).
14496 CalcStepExpr = CalcStep.get();
14497 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014498 }
14499
Alexey Bataev182227b2015-08-20 10:54:39 +000014500 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14501 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014502 StepExpr, CalcStepExpr,
14503 buildPreInits(Context, ExprCaptures),
14504 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014505}
14506
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014507static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14508 Expr *NumIterations, Sema &SemaRef,
14509 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014510 // Walk the vars and build update/final expressions for the CodeGen.
14511 SmallVector<Expr *, 8> Updates;
14512 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014513 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014514 Expr *Step = Clause.getStep();
14515 Expr *CalcStep = Clause.getCalcStep();
14516 // OpenMP [2.14.3.7, linear clause]
14517 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014518 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014519 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014520 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014521 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14522 bool HasErrors = false;
14523 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014524 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014525 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14526 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014527 SourceLocation ELoc;
14528 SourceRange ERange;
14529 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014530 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014531 ValueDecl *D = Res.first;
14532 if (Res.second || !D) {
14533 Updates.push_back(nullptr);
14534 Finals.push_back(nullptr);
14535 HasErrors = true;
14536 continue;
14537 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014538 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014539 // OpenMP [2.15.11, distribute simd Construct]
14540 // A list item may not appear in a linear clause, unless it is the loop
14541 // iteration variable.
14542 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14543 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14544 SemaRef.Diag(ELoc,
14545 diag::err_omp_linear_distribute_var_non_loop_iteration);
14546 Updates.push_back(nullptr);
14547 Finals.push_back(nullptr);
14548 HasErrors = true;
14549 continue;
14550 }
Alexander Musman3276a272015-03-21 10:12:56 +000014551 Expr *InitExpr = *CurInit;
14552
14553 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014554 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014555 Expr *CapturedRef;
14556 if (LinKind == OMPC_LINEAR_uval)
14557 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14558 else
14559 CapturedRef =
14560 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14561 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14562 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014563
14564 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014565 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014566 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014567 Update = buildCounterUpdate(
14568 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14569 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014570 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014571 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014572 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014573 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014574
14575 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014576 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014577 if (!Info.first)
14578 Final =
14579 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014580 InitExpr, NumIterations, Step, /*Subtract=*/false,
14581 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014582 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014583 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014584 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014585 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014586
Alexander Musman3276a272015-03-21 10:12:56 +000014587 if (!Update.isUsable() || !Final.isUsable()) {
14588 Updates.push_back(nullptr);
14589 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014590 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014591 HasErrors = true;
14592 } else {
14593 Updates.push_back(Update.get());
14594 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014595 if (!Info.first)
14596 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014597 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014598 ++CurInit;
14599 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014600 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014601 if (Expr *S = Clause.getStep())
14602 UsedExprs.push_back(S);
14603 // Fill the remaining part with the nullptr.
14604 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014605 Clause.setUpdates(Updates);
14606 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014607 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014608 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014609}
14610
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014611OMPClause *Sema::ActOnOpenMPAlignedClause(
14612 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14613 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014614 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014615 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014616 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14617 SourceLocation ELoc;
14618 SourceRange ERange;
14619 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014620 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014621 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014622 // It will be analyzed later.
14623 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014624 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014625 ValueDecl *D = Res.first;
14626 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014627 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014628
Alexey Bataev1efd1662016-03-29 10:59:56 +000014629 QualType QType = D->getType();
14630 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014631
14632 // OpenMP [2.8.1, simd construct, Restrictions]
14633 // The type of list items appearing in the aligned clause must be
14634 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014635 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014636 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014637 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014638 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014639 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014640 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014641 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014642 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014643 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014644 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014645 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014646 continue;
14647 }
14648
14649 // OpenMP [2.8.1, simd construct, Restrictions]
14650 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014651 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevb6e70842019-12-16 15:54:17 -050014652 Diag(ELoc, diag::err_omp_used_in_clause_twice)
14653 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014654 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14655 << getOpenMPClauseName(OMPC_aligned);
14656 continue;
14657 }
14658
Alexey Bataev1efd1662016-03-29 10:59:56 +000014659 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014660 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014661 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14662 Vars.push_back(DefaultFunctionArrayConversion(
14663 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14664 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014665 }
14666
14667 // OpenMP [2.8.1, simd construct, Description]
14668 // The parameter of the aligned clause, alignment, must be a constant
14669 // positive integer expression.
14670 // If no optional parameter is specified, implementation-defined default
14671 // alignments for SIMD instructions on the target platforms are assumed.
14672 if (Alignment != nullptr) {
14673 ExprResult AlignResult =
14674 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14675 if (AlignResult.isInvalid())
14676 return nullptr;
14677 Alignment = AlignResult.get();
14678 }
14679 if (Vars.empty())
14680 return nullptr;
14681
14682 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14683 EndLoc, Vars, Alignment);
14684}
14685
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014686OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14687 SourceLocation StartLoc,
14688 SourceLocation LParenLoc,
14689 SourceLocation EndLoc) {
14690 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014691 SmallVector<Expr *, 8> SrcExprs;
14692 SmallVector<Expr *, 8> DstExprs;
14693 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014694 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014695 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14696 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014697 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014698 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014699 SrcExprs.push_back(nullptr);
14700 DstExprs.push_back(nullptr);
14701 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014702 continue;
14703 }
14704
Alexey Bataeved09d242014-05-28 05:53:51 +000014705 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014706 // OpenMP [2.1, C/C++]
14707 // A list item is a variable name.
14708 // OpenMP [2.14.4.1, Restrictions, p.1]
14709 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014710 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014711 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014712 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14713 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014714 continue;
14715 }
14716
14717 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014718 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014719
14720 QualType Type = VD->getType();
14721 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14722 // It will be analyzed later.
14723 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014724 SrcExprs.push_back(nullptr);
14725 DstExprs.push_back(nullptr);
14726 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014727 continue;
14728 }
14729
14730 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14731 // A list item that appears in a copyin clause must be threadprivate.
14732 if (!DSAStack->isThreadPrivate(VD)) {
14733 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014734 << getOpenMPClauseName(OMPC_copyin)
14735 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014736 continue;
14737 }
14738
14739 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14740 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014741 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014742 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014743 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14744 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014745 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014746 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014747 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014748 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014749 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014750 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014751 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014752 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014753 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014754 // For arrays generate assignment operation for single element and replace
14755 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014756 ExprResult AssignmentOp =
14757 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14758 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014759 if (AssignmentOp.isInvalid())
14760 continue;
14761 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014762 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014763 if (AssignmentOp.isInvalid())
14764 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014765
14766 DSAStack->addDSA(VD, DE, OMPC_copyin);
14767 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014768 SrcExprs.push_back(PseudoSrcExpr);
14769 DstExprs.push_back(PseudoDstExpr);
14770 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014771 }
14772
Alexey Bataeved09d242014-05-28 05:53:51 +000014773 if (Vars.empty())
14774 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014775
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014776 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14777 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014778}
14779
Alexey Bataevbae9a792014-06-27 10:37:06 +000014780OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14781 SourceLocation StartLoc,
14782 SourceLocation LParenLoc,
14783 SourceLocation EndLoc) {
14784 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014785 SmallVector<Expr *, 8> SrcExprs;
14786 SmallVector<Expr *, 8> DstExprs;
14787 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014788 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014789 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14790 SourceLocation ELoc;
14791 SourceRange ERange;
14792 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014793 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014794 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014795 // It will be analyzed later.
14796 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014797 SrcExprs.push_back(nullptr);
14798 DstExprs.push_back(nullptr);
14799 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014800 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014801 ValueDecl *D = Res.first;
14802 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014803 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014804
Alexey Bataeve122da12016-03-17 10:50:17 +000014805 QualType Type = D->getType();
14806 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014807
14808 // OpenMP [2.14.4.2, Restrictions, p.2]
14809 // A list item that appears in a copyprivate clause may not appear in a
14810 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014811 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014812 DSAStackTy::DSAVarData DVar =
14813 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014814 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14815 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014816 Diag(ELoc, diag::err_omp_wrong_dsa)
14817 << getOpenMPClauseName(DVar.CKind)
14818 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014819 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014820 continue;
14821 }
14822
14823 // OpenMP [2.11.4.2, Restrictions, p.1]
14824 // All list items that appear in a copyprivate clause must be either
14825 // threadprivate or private in the enclosing context.
14826 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014827 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014828 if (DVar.CKind == OMPC_shared) {
14829 Diag(ELoc, diag::err_omp_required_access)
14830 << getOpenMPClauseName(OMPC_copyprivate)
14831 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014832 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014833 continue;
14834 }
14835 }
14836 }
14837
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014838 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014839 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014840 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014841 << getOpenMPClauseName(OMPC_copyprivate) << Type
14842 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014843 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014844 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014845 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014846 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014847 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014848 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014849 continue;
14850 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014851
Alexey Bataevbae9a792014-06-27 10:37:06 +000014852 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14853 // A variable of class type (or array thereof) that appears in a
14854 // copyin clause requires an accessible, unambiguous copy assignment
14855 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014856 Type = Context.getBaseElementType(Type.getNonReferenceType())
14857 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014858 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014859 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014860 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014861 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14862 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014863 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014864 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014865 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14866 ExprResult AssignmentOp = BuildBinOp(
14867 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014868 if (AssignmentOp.isInvalid())
14869 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014870 AssignmentOp =
14871 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014872 if (AssignmentOp.isInvalid())
14873 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014874
14875 // No need to mark vars as copyprivate, they are already threadprivate or
14876 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014877 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014878 Vars.push_back(
14879 VD ? RefExpr->IgnoreParens()
14880 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014881 SrcExprs.push_back(PseudoSrcExpr);
14882 DstExprs.push_back(PseudoDstExpr);
14883 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014884 }
14885
14886 if (Vars.empty())
14887 return nullptr;
14888
Alexey Bataeva63048e2015-03-23 06:18:07 +000014889 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14890 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014891}
14892
Alexey Bataev6125da92014-07-21 11:26:11 +000014893OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14894 SourceLocation StartLoc,
14895 SourceLocation LParenLoc,
14896 SourceLocation EndLoc) {
14897 if (VarList.empty())
14898 return nullptr;
14899
14900 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14901}
Alexey Bataevdea47612014-07-23 07:46:59 +000014902
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014903OMPClause *
14904Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14905 SourceLocation DepLoc, SourceLocation ColonLoc,
14906 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14907 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014908 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014909 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014910 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014911 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014912 return nullptr;
14913 }
14914 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014915 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14916 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014917 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014918 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014919 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14920 /*Last=*/OMPC_DEPEND_unknown, Except)
14921 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014922 return nullptr;
14923 }
14924 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014925 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014926 llvm::APSInt DepCounter(/*BitWidth=*/32);
14927 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014928 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14929 if (const Expr *OrderedCountExpr =
14930 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014931 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14932 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014933 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014934 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014935 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014936 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14937 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14938 // It will be analyzed later.
14939 Vars.push_back(RefExpr);
14940 continue;
14941 }
14942
14943 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014944 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014945 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014946 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014947 DepCounter >= TotalDepCount) {
14948 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14949 continue;
14950 }
14951 ++DepCounter;
14952 // OpenMP [2.13.9, Summary]
14953 // depend(dependence-type : vec), where dependence-type is:
14954 // 'sink' and where vec is the iteration vector, which has the form:
14955 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14956 // where n is the value specified by the ordered clause in the loop
14957 // directive, xi denotes the loop iteration variable of the i-th nested
14958 // loop associated with the loop directive, and di is a constant
14959 // non-negative integer.
14960 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014961 // It will be analyzed later.
14962 Vars.push_back(RefExpr);
14963 continue;
14964 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014965 SimpleExpr = SimpleExpr->IgnoreImplicit();
14966 OverloadedOperatorKind OOK = OO_None;
14967 SourceLocation OOLoc;
14968 Expr *LHS = SimpleExpr;
14969 Expr *RHS = nullptr;
14970 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14971 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14972 OOLoc = BO->getOperatorLoc();
14973 LHS = BO->getLHS()->IgnoreParenImpCasts();
14974 RHS = BO->getRHS()->IgnoreParenImpCasts();
14975 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14976 OOK = OCE->getOperator();
14977 OOLoc = OCE->getOperatorLoc();
14978 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14979 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14980 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14981 OOK = MCE->getMethodDecl()
14982 ->getNameInfo()
14983 .getName()
14984 .getCXXOverloadedOperator();
14985 OOLoc = MCE->getCallee()->getExprLoc();
14986 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14987 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014988 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014989 SourceLocation ELoc;
14990 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014991 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014992 if (Res.second) {
14993 // It will be analyzed later.
14994 Vars.push_back(RefExpr);
14995 }
14996 ValueDecl *D = Res.first;
14997 if (!D)
14998 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014999
Alexey Bataev17daedf2018-02-15 22:42:57 +000015000 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
15001 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
15002 continue;
15003 }
15004 if (RHS) {
15005 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
15006 RHS, OMPC_depend, /*StrictlyPositive=*/false);
15007 if (RHSRes.isInvalid())
15008 continue;
15009 }
15010 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015011 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015012 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015013 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000015014 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000015015 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000015016 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
15017 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000015018 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000015019 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000015020 continue;
15021 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015022 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015023 } else {
15024 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
15025 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
15026 (ASE &&
15027 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
15028 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
15029 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15030 << RefExpr->getSourceRange();
15031 continue;
15032 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000015033
15034 ExprResult Res;
15035 {
15036 Sema::TentativeAnalysisScope Trap(*this);
15037 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
15038 RefExpr->IgnoreParenImpCasts());
15039 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015040 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
15041 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15042 << RefExpr->getSourceRange();
15043 continue;
15044 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015045 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015046 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015047 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015048
15049 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
15050 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015051 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015052 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
15053 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
15054 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
15055 }
15056 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
15057 Vars.empty())
15058 return nullptr;
15059
Alexey Bataev8b427062016-05-25 12:36:08 +000015060 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000015061 DepKind, DepLoc, ColonLoc, Vars,
15062 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000015063 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
15064 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000015065 DSAStack->addDoacrossDependClause(C, OpsOffs);
15066 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015067}
Michael Wonge710d542015-08-07 16:16:36 +000015068
15069OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
15070 SourceLocation LParenLoc,
15071 SourceLocation EndLoc) {
15072 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015073 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000015074
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015075 // OpenMP [2.9.1, Restrictions]
15076 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015077 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000015078 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015079 return nullptr;
15080
Alexey Bataev931e19b2017-10-02 16:32:39 +000015081 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015082 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050015083 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000015084 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015085 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015086 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015087 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15088 HelperValStmt = buildPreInits(Context, Captures);
15089 }
15090
Alexey Bataev8451efa2018-01-15 19:06:12 +000015091 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
15092 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000015093}
Kelvin Li0bff7af2015-11-23 05:32:03 +000015094
Alexey Bataeve3727102018-04-18 15:57:46 +000015095static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000015096 DSAStackTy *Stack, QualType QTy,
15097 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000015098 NamedDecl *ND;
15099 if (QTy->isIncompleteType(&ND)) {
15100 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
15101 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015102 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000015103 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
Jonas Hahnfeld071dca22019-12-07 13:31:46 +010015104 !QTy.isTriviallyCopyableType(SemaRef.Context))
Alexey Bataev95c23e72018-02-27 21:31:11 +000015105 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015106 return true;
15107}
15108
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000015109/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015110/// (array section or array subscript) does NOT specify the whole size of the
15111/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015112static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015113 const Expr *E,
15114 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015115 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015116
15117 // If this is an array subscript, it refers to the whole size if the size of
15118 // the dimension is constant and equals 1. Also, an array section assumes the
15119 // format of an array subscript if no colon is used.
15120 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015121 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015122 return ATy->getSize().getSExtValue() != 1;
15123 // Size can't be evaluated statically.
15124 return false;
15125 }
15126
15127 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015128 const Expr *LowerBound = OASE->getLowerBound();
15129 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015130
15131 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000015132 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015133 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000015134 Expr::EvalResult Result;
15135 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015136 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000015137
15138 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015139 if (ConstLowerBound.getSExtValue())
15140 return true;
15141 }
15142
15143 // If we don't have a length we covering the whole dimension.
15144 if (!Length)
15145 return false;
15146
15147 // If the base is a pointer, we don't have a way to get the size of the
15148 // pointee.
15149 if (BaseQTy->isPointerType())
15150 return false;
15151
15152 // We can only check if the length is the same as the size of the dimension
15153 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000015154 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015155 if (!CATy)
15156 return false;
15157
Fangrui Song407659a2018-11-30 23:41:18 +000015158 Expr::EvalResult Result;
15159 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015160 return false; // Can't get the integer value as a constant.
15161
Fangrui Song407659a2018-11-30 23:41:18 +000015162 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015163 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
15164}
15165
15166// Return true if it can be proven that the provided array expression (array
15167// section or array subscript) does NOT specify a single element of the array
15168// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015169static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000015170 const Expr *E,
15171 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015172 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015173
15174 // An array subscript always refer to a single element. Also, an array section
15175 // assumes the format of an array subscript if no colon is used.
15176 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
15177 return false;
15178
15179 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015180 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015181
15182 // If we don't have a length we have to check if the array has unitary size
15183 // for this dimension. Also, we should always expect a length if the base type
15184 // is pointer.
15185 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015186 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015187 return ATy->getSize().getSExtValue() != 1;
15188 // We cannot assume anything.
15189 return false;
15190 }
15191
15192 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000015193 Expr::EvalResult Result;
15194 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015195 return false; // Can't get the integer value as a constant.
15196
Fangrui Song407659a2018-11-30 23:41:18 +000015197 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015198 return ConstLength.getSExtValue() != 1;
15199}
15200
Samuel Antao661c0902016-05-26 17:39:58 +000015201// Return the expression of the base of the mappable expression or null if it
15202// cannot be determined and do all the necessary checks to see if the expression
15203// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000015204// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015205static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000015206 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000015207 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015208 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015209 SourceLocation ELoc = E->getExprLoc();
15210 SourceRange ERange = E->getSourceRange();
15211
15212 // The base of elements of list in a map clause have to be either:
15213 // - a reference to variable or field.
15214 // - a member expression.
15215 // - an array expression.
15216 //
15217 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
15218 // reference to 'r'.
15219 //
15220 // If we have:
15221 //
15222 // struct SS {
15223 // Bla S;
15224 // foo() {
15225 // #pragma omp target map (S.Arr[:12]);
15226 // }
15227 // }
15228 //
15229 // We want to retrieve the member expression 'this->S';
15230
Alexey Bataeve3727102018-04-18 15:57:46 +000015231 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015232
Samuel Antao5de996e2016-01-22 20:21:36 +000015233 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15234 // If a list item is an array section, it must specify contiguous storage.
15235 //
15236 // For this restriction it is sufficient that we make sure only references
15237 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015238 // exist except in the rightmost expression (unless they cover the whole
15239 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015240 //
15241 // r.ArrS[3:5].Arr[6:7]
15242 //
15243 // r.ArrS[3:5].x
15244 //
15245 // but these would be valid:
15246 // r.ArrS[3].Arr[6:7]
15247 //
15248 // r.ArrS[3].x
15249
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015250 bool AllowUnitySizeArraySection = true;
15251 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015252
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015253 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015254 E = E->IgnoreParenImpCasts();
15255
15256 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15257 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015258 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015259
15260 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015261
15262 // If we got a reference to a declaration, we should not expect any array
15263 // section before that.
15264 AllowUnitySizeArraySection = false;
15265 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015266
15267 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015268 CurComponents.emplace_back(CurE, CurE->getDecl());
15269 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015270 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015271
15272 if (isa<CXXThisExpr>(BaseE))
15273 // We found a base expression: this->Val.
15274 RelevantExpr = CurE;
15275 else
15276 E = BaseE;
15277
15278 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015279 if (!NoDiagnose) {
15280 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15281 << CurE->getSourceRange();
15282 return nullptr;
15283 }
15284 if (RelevantExpr)
15285 return nullptr;
15286 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015287 }
15288
15289 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15290
15291 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15292 // A bit-field cannot appear in a map clause.
15293 //
15294 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015295 if (!NoDiagnose) {
15296 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15297 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15298 return nullptr;
15299 }
15300 if (RelevantExpr)
15301 return nullptr;
15302 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015303 }
15304
15305 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15306 // If the type of a list item is a reference to a type T then the type
15307 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015308 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015309
15310 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15311 // A list item cannot be a variable that is a member of a structure with
15312 // a union type.
15313 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015314 if (CurType->isUnionType()) {
15315 if (!NoDiagnose) {
15316 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15317 << CurE->getSourceRange();
15318 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015319 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015320 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015321 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015322
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015323 // If we got a member expression, we should not expect any array section
15324 // before that:
15325 //
15326 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15327 // If a list item is an element of a structure, only the rightmost symbol
15328 // of the variable reference can be an array section.
15329 //
15330 AllowUnitySizeArraySection = false;
15331 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015332
15333 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015334 CurComponents.emplace_back(CurE, FD);
15335 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015336 E = CurE->getBase()->IgnoreParenImpCasts();
15337
15338 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015339 if (!NoDiagnose) {
15340 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15341 << 0 << CurE->getSourceRange();
15342 return nullptr;
15343 }
15344 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015345 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015346
15347 // If we got an array subscript that express the whole dimension we
15348 // can have any array expressions before. If it only expressing part of
15349 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015350 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015351 E->getType()))
15352 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015353
Patrick Lystere13b1e32019-01-02 19:28:48 +000015354 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15355 Expr::EvalResult Result;
15356 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15357 if (!Result.Val.getInt().isNullValue()) {
15358 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15359 diag::err_omp_invalid_map_this_expr);
15360 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15361 diag::note_omp_invalid_subscript_on_this_ptr_map);
15362 }
15363 }
15364 RelevantExpr = TE;
15365 }
15366
Samuel Antao90927002016-04-26 14:54:23 +000015367 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015368 CurComponents.emplace_back(CurE, nullptr);
15369 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015370 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015371 E = CurE->getBase()->IgnoreParenImpCasts();
15372
Alexey Bataev27041fa2017-12-05 15:22:49 +000015373 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015374 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15375
Samuel Antao5de996e2016-01-22 20:21:36 +000015376 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15377 // If the type of a list item is a reference to a type T then the type
15378 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015379 if (CurType->isReferenceType())
15380 CurType = CurType->getPointeeType();
15381
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015382 bool IsPointer = CurType->isAnyPointerType();
15383
15384 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015385 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15386 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015387 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015388 }
15389
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015390 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015391 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015392 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015393 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015394
Samuel Antaodab51bb2016-07-18 23:22:11 +000015395 if (AllowWholeSizeArraySection) {
15396 // Any array section is currently allowed. Allowing a whole size array
15397 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015398 //
15399 // If this array section refers to the whole dimension we can still
15400 // accept other array sections before this one, except if the base is a
15401 // pointer. Otherwise, only unitary sections are accepted.
15402 if (NotWhole || IsPointer)
15403 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015404 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015405 // A unity or whole array section is not allowed and that is not
15406 // compatible with the properties of the current array section.
15407 SemaRef.Diag(
15408 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15409 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015410 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015411 }
Samuel Antao90927002016-04-26 14:54:23 +000015412
Patrick Lystere13b1e32019-01-02 19:28:48 +000015413 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15414 Expr::EvalResult ResultR;
15415 Expr::EvalResult ResultL;
15416 if (CurE->getLength()->EvaluateAsInt(ResultR,
15417 SemaRef.getASTContext())) {
15418 if (!ResultR.Val.getInt().isOneValue()) {
15419 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15420 diag::err_omp_invalid_map_this_expr);
15421 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15422 diag::note_omp_invalid_length_on_this_ptr_mapping);
15423 }
15424 }
15425 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15426 ResultL, SemaRef.getASTContext())) {
15427 if (!ResultL.Val.getInt().isNullValue()) {
15428 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15429 diag::err_omp_invalid_map_this_expr);
15430 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15431 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15432 }
15433 }
15434 RelevantExpr = TE;
15435 }
15436
Samuel Antao90927002016-04-26 14:54:23 +000015437 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015438 CurComponents.emplace_back(CurE, nullptr);
15439 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015440 if (!NoDiagnose) {
15441 // If nothing else worked, this is not a valid map clause expression.
15442 SemaRef.Diag(
15443 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15444 << ERange;
15445 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015446 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015447 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015448 }
15449
15450 return RelevantExpr;
15451}
15452
15453// Return true if expression E associated with value VD has conflicts with other
15454// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015455static bool checkMapConflicts(
15456 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015457 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015458 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15459 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015460 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015461 SourceLocation ELoc = E->getExprLoc();
15462 SourceRange ERange = E->getSourceRange();
15463
15464 // In order to easily check the conflicts we need to match each component of
15465 // the expression under test with the components of the expressions that are
15466 // already in the stack.
15467
Samuel Antao5de996e2016-01-22 20:21:36 +000015468 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015469 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015470 "Map clause expression with unexpected base!");
15471
15472 // Variables to help detecting enclosing problems in data environment nests.
15473 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015474 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015475
Samuel Antao90927002016-04-26 14:54:23 +000015476 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15477 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015478 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15479 ERange, CKind, &EnclosingExpr,
15480 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15481 StackComponents,
15482 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015483 assert(!StackComponents.empty() &&
15484 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015485 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015486 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015487 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015488
Samuel Antao90927002016-04-26 14:54:23 +000015489 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015490 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015491
Samuel Antao5de996e2016-01-22 20:21:36 +000015492 // Expressions must start from the same base. Here we detect at which
15493 // point both expressions diverge from each other and see if we can
15494 // detect if the memory referred to both expressions is contiguous and
15495 // do not overlap.
15496 auto CI = CurComponents.rbegin();
15497 auto CE = CurComponents.rend();
15498 auto SI = StackComponents.rbegin();
15499 auto SE = StackComponents.rend();
15500 for (; CI != CE && SI != SE; ++CI, ++SI) {
15501
15502 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15503 // At most one list item can be an array item derived from a given
15504 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015505 if (CurrentRegionOnly &&
15506 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15507 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15508 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15509 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15510 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015511 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015512 << CI->getAssociatedExpression()->getSourceRange();
15513 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15514 diag::note_used_here)
15515 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015516 return true;
15517 }
15518
15519 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015520 if (CI->getAssociatedExpression()->getStmtClass() !=
15521 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015522 break;
15523
15524 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015525 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015526 break;
15527 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015528 // Check if the extra components of the expressions in the enclosing
15529 // data environment are redundant for the current base declaration.
15530 // If they are, the maps completely overlap, which is legal.
15531 for (; SI != SE; ++SI) {
15532 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015533 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015534 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015535 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015536 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015537 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015538 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015539 Type =
15540 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15541 }
15542 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015543 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015544 SemaRef, SI->getAssociatedExpression(), Type))
15545 break;
15546 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015547
15548 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15549 // List items of map clauses in the same construct must not share
15550 // original storage.
15551 //
15552 // If the expressions are exactly the same or one is a subset of the
15553 // other, it means they are sharing storage.
15554 if (CI == CE && SI == SE) {
15555 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015556 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015557 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015558 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015559 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015560 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15561 << ERange;
15562 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015563 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15564 << RE->getSourceRange();
15565 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015566 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015567 // If we find the same expression in the enclosing data environment,
15568 // that is legal.
15569 IsEnclosedByDataEnvironmentExpr = true;
15570 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015571 }
15572
Samuel Antao90927002016-04-26 14:54:23 +000015573 QualType DerivedType =
15574 std::prev(CI)->getAssociatedDeclaration()->getType();
15575 SourceLocation DerivedLoc =
15576 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015577
15578 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15579 // If the type of a list item is a reference to a type T then the type
15580 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015581 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015582
15583 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15584 // A variable for which the type is pointer and an array section
15585 // derived from that variable must not appear as list items of map
15586 // clauses of the same construct.
15587 //
15588 // Also, cover one of the cases in:
15589 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15590 // If any part of the original storage of a list item has corresponding
15591 // storage in the device data environment, all of the original storage
15592 // must have corresponding storage in the device data environment.
15593 //
15594 if (DerivedType->isAnyPointerType()) {
15595 if (CI == CE || SI == SE) {
15596 SemaRef.Diag(
15597 DerivedLoc,
15598 diag::err_omp_pointer_mapped_along_with_derived_section)
15599 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015600 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15601 << RE->getSourceRange();
15602 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015603 }
15604 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015605 SI->getAssociatedExpression()->getStmtClass() ||
15606 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15607 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015608 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015609 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015610 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015611 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15612 << RE->getSourceRange();
15613 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015614 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015615 }
15616
15617 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15618 // List items of map clauses in the same construct must not share
15619 // original storage.
15620 //
15621 // An expression is a subset of the other.
15622 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015623 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015624 if (CI != CE || SI != SE) {
15625 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15626 // a pointer.
15627 auto Begin =
15628 CI != CE ? CurComponents.begin() : StackComponents.begin();
15629 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15630 auto It = Begin;
15631 while (It != End && !It->getAssociatedDeclaration())
15632 std::advance(It, 1);
15633 assert(It != End &&
15634 "Expected at least one component with the declaration.");
15635 if (It != Begin && It->getAssociatedDeclaration()
15636 ->getType()
15637 .getCanonicalType()
15638 ->isAnyPointerType()) {
15639 IsEnclosedByDataEnvironmentExpr = false;
15640 EnclosingExpr = nullptr;
15641 return false;
15642 }
15643 }
Samuel Antao661c0902016-05-26 17:39:58 +000015644 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015645 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015646 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015647 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15648 << ERange;
15649 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015650 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15651 << RE->getSourceRange();
15652 return true;
15653 }
15654
15655 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015656 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015657 if (!CurrentRegionOnly && SI != SE)
15658 EnclosingExpr = RE;
15659
15660 // The current expression is a subset of the expression in the data
15661 // environment.
15662 IsEnclosedByDataEnvironmentExpr |=
15663 (!CurrentRegionOnly && CI != CE && SI == SE);
15664
15665 return false;
15666 });
15667
15668 if (CurrentRegionOnly)
15669 return FoundError;
15670
15671 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15672 // If any part of the original storage of a list item has corresponding
15673 // storage in the device data environment, all of the original storage must
15674 // have corresponding storage in the device data environment.
15675 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15676 // If a list item is an element of a structure, and a different element of
15677 // the structure has a corresponding list item in the device data environment
15678 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015679 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015680 // data environment prior to the task encountering the construct.
15681 //
15682 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15683 SemaRef.Diag(ELoc,
15684 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15685 << ERange;
15686 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15687 << EnclosingExpr->getSourceRange();
15688 return true;
15689 }
15690
15691 return FoundError;
15692}
15693
Michael Kruse4304e9d2019-02-19 16:38:20 +000015694// Look up the user-defined mapper given the mapper name and mapped type, and
15695// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015696static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15697 CXXScopeSpec &MapperIdScopeSpec,
15698 const DeclarationNameInfo &MapperId,
15699 QualType Type,
15700 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015701 if (MapperIdScopeSpec.isInvalid())
15702 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015703 // Get the actual type for the array type.
15704 if (Type->isArrayType()) {
15705 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15706 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15707 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015708 // Find all user-defined mappers with the given MapperId.
15709 SmallVector<UnresolvedSet<8>, 4> Lookups;
15710 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15711 Lookup.suppressDiagnostics();
15712 if (S) {
15713 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15714 NamedDecl *D = Lookup.getRepresentativeDecl();
15715 while (S && !S->isDeclScope(D))
15716 S = S->getParent();
15717 if (S)
15718 S = S->getParent();
15719 Lookups.emplace_back();
15720 Lookups.back().append(Lookup.begin(), Lookup.end());
15721 Lookup.clear();
15722 }
15723 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15724 // Extract the user-defined mappers with the given MapperId.
15725 Lookups.push_back(UnresolvedSet<8>());
15726 for (NamedDecl *D : ULE->decls()) {
15727 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15728 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15729 Lookups.back().addDecl(DMD);
15730 }
15731 }
15732 // Defer the lookup for dependent types. The results will be passed through
15733 // UnresolvedMapper on instantiation.
15734 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15735 Type->isInstantiationDependentType() ||
15736 Type->containsUnexpandedParameterPack() ||
15737 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15738 return !D->isInvalidDecl() &&
15739 (D->getType()->isDependentType() ||
15740 D->getType()->isInstantiationDependentType() ||
15741 D->getType()->containsUnexpandedParameterPack());
15742 })) {
15743 UnresolvedSet<8> URS;
15744 for (const UnresolvedSet<8> &Set : Lookups) {
15745 if (Set.empty())
15746 continue;
15747 URS.append(Set.begin(), Set.end());
15748 }
15749 return UnresolvedLookupExpr::Create(
15750 SemaRef.Context, /*NamingClass=*/nullptr,
15751 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15752 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15753 }
Michael Kruse945249b2019-09-26 22:53:01 +000015754 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015755 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15756 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015757 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15758 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15759 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15760 return ExprError();
15761 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015762 // Perform argument dependent lookup.
15763 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15764 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15765 // Return the first user-defined mapper with the desired type.
15766 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15767 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15768 if (!D->isInvalidDecl() &&
15769 SemaRef.Context.hasSameType(D->getType(), Type))
15770 return D;
15771 return nullptr;
15772 }))
15773 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15774 // Find the first user-defined mapper with a type derived from the desired
15775 // type.
15776 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15777 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15778 if (!D->isInvalidDecl() &&
15779 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15780 !Type.isMoreQualifiedThan(D->getType()))
15781 return D;
15782 return nullptr;
15783 })) {
15784 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15785 /*DetectVirtual=*/false);
15786 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15787 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15788 VD->getType().getUnqualifiedType()))) {
15789 if (SemaRef.CheckBaseClassAccess(
15790 Loc, VD->getType(), Type, Paths.front(),
15791 /*DiagID=*/0) != Sema::AR_inaccessible) {
15792 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15793 }
15794 }
15795 }
15796 }
15797 // Report error if a mapper is specified, but cannot be found.
15798 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15799 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15800 << Type << MapperId.getName();
15801 return ExprError();
15802 }
15803 return ExprEmpty();
15804}
15805
Samuel Antao661c0902016-05-26 17:39:58 +000015806namespace {
15807// Utility struct that gathers all the related lists associated with a mappable
15808// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015809struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015810 // The list of expressions.
15811 ArrayRef<Expr *> VarList;
15812 // The list of processed expressions.
15813 SmallVector<Expr *, 16> ProcessedVarList;
15814 // The mappble components for each expression.
15815 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15816 // The base declaration of the variable.
15817 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015818 // The reference to the user-defined mapper associated with every expression.
15819 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015820
15821 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15822 // We have a list of components and base declarations for each entry in the
15823 // variable list.
15824 VarComponents.reserve(VarList.size());
15825 VarBaseDeclarations.reserve(VarList.size());
15826 }
15827};
15828}
15829
15830// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015831// \a CKind. In the check process the valid expressions, mappable expression
15832// components, variables, and user-defined mappers are extracted and used to
15833// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15834// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15835// and \a MapperId are expected to be valid if the clause kind is 'map'.
15836static void checkMappableExpressionList(
15837 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15838 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015839 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15840 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015841 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015842 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015843 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15844 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015845 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015846
15847 // If the identifier of user-defined mapper is not specified, it is "default".
15848 // We do not change the actual name in this clause to distinguish whether a
15849 // mapper is specified explicitly, i.e., it is not explicitly specified when
15850 // MapperId.getName() is empty.
15851 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15852 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15853 MapperId.setName(DeclNames.getIdentifier(
15854 &SemaRef.getASTContext().Idents.get("default")));
15855 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015856
15857 // Iterators to find the current unresolved mapper expression.
15858 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15859 bool UpdateUMIt = false;
15860 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015861
Samuel Antao90927002016-04-26 14:54:23 +000015862 // Keep track of the mappable components and base declarations in this clause.
15863 // Each entry in the list is going to have a list of components associated. We
15864 // record each set of the components so that we can build the clause later on.
15865 // In the end we should have the same amount of declarations and component
15866 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015867
Alexey Bataeve3727102018-04-18 15:57:46 +000015868 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015869 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015870 SourceLocation ELoc = RE->getExprLoc();
15871
Michael Kruse4304e9d2019-02-19 16:38:20 +000015872 // Find the current unresolved mapper expression.
15873 if (UpdateUMIt && UMIt != UMEnd) {
15874 UMIt++;
15875 assert(
15876 UMIt != UMEnd &&
15877 "Expect the size of UnresolvedMappers to match with that of VarList");
15878 }
15879 UpdateUMIt = true;
15880 if (UMIt != UMEnd)
15881 UnresolvedMapper = *UMIt;
15882
Alexey Bataeve3727102018-04-18 15:57:46 +000015883 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015884
15885 if (VE->isValueDependent() || VE->isTypeDependent() ||
15886 VE->isInstantiationDependent() ||
15887 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015888 // Try to find the associated user-defined mapper.
15889 ExprResult ER = buildUserDefinedMapperRef(
15890 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15891 VE->getType().getCanonicalType(), UnresolvedMapper);
15892 if (ER.isInvalid())
15893 continue;
15894 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015895 // We can only analyze this information once the missing information is
15896 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015897 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015898 continue;
15899 }
15900
Alexey Bataeve3727102018-04-18 15:57:46 +000015901 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015902
Samuel Antao5de996e2016-01-22 20:21:36 +000015903 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015904 SemaRef.Diag(ELoc,
15905 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015906 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015907 continue;
15908 }
15909
Samuel Antao90927002016-04-26 14:54:23 +000015910 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15911 ValueDecl *CurDeclaration = nullptr;
15912
15913 // Obtain the array or member expression bases if required. Also, fill the
15914 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015915 const Expr *BE = checkMapClauseExpressionBase(
15916 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015917 if (!BE)
15918 continue;
15919
Samuel Antao90927002016-04-26 14:54:23 +000015920 assert(!CurComponents.empty() &&
15921 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015922
Patrick Lystere13b1e32019-01-02 19:28:48 +000015923 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15924 // Add store "this" pointer to class in DSAStackTy for future checking
15925 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015926 // Try to find the associated user-defined mapper.
15927 ExprResult ER = buildUserDefinedMapperRef(
15928 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15929 VE->getType().getCanonicalType(), UnresolvedMapper);
15930 if (ER.isInvalid())
15931 continue;
15932 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015933 // Skip restriction checking for variable or field declarations
15934 MVLI.ProcessedVarList.push_back(RE);
15935 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15936 MVLI.VarComponents.back().append(CurComponents.begin(),
15937 CurComponents.end());
15938 MVLI.VarBaseDeclarations.push_back(nullptr);
15939 continue;
15940 }
15941
Samuel Antao90927002016-04-26 14:54:23 +000015942 // For the following checks, we rely on the base declaration which is
15943 // expected to be associated with the last component. The declaration is
15944 // expected to be a variable or a field (if 'this' is being mapped).
15945 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15946 assert(CurDeclaration && "Null decl on map clause.");
15947 assert(
15948 CurDeclaration->isCanonicalDecl() &&
15949 "Expecting components to have associated only canonical declarations.");
15950
15951 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015952 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015953
15954 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015955 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015956
15957 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015958 // threadprivate variables cannot appear in a map clause.
15959 // OpenMP 4.5 [2.10.5, target update Construct]
15960 // threadprivate variables cannot appear in a from clause.
15961 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015962 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015963 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15964 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015965 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015966 continue;
15967 }
15968
Samuel Antao5de996e2016-01-22 20:21:36 +000015969 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15970 // A list item cannot appear in both a map clause and a data-sharing
15971 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015972
Samuel Antao5de996e2016-01-22 20:21:36 +000015973 // Check conflicts with other map clause expressions. We check the conflicts
15974 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015975 // environment, because the restrictions are different. We only have to
15976 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015977 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015978 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015979 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015980 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015981 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015982 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015983 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015984
Samuel Antao661c0902016-05-26 17:39:58 +000015985 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015986 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15987 // If the type of a list item is a reference to a type T then the type will
15988 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015989 auto I = llvm::find_if(
15990 CurComponents,
15991 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15992 return MC.getAssociatedDeclaration();
15993 });
15994 assert(I != CurComponents.end() && "Null decl on map clause.");
15995 QualType Type =
15996 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015997
Samuel Antao661c0902016-05-26 17:39:58 +000015998 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15999 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000016000 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000016001 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000016002 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000016003 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000016004 continue;
16005
Samuel Antao661c0902016-05-26 17:39:58 +000016006 if (CKind == OMPC_map) {
16007 // target enter data
16008 // OpenMP [2.10.2, Restrictions, p. 99]
16009 // A map-type must be specified in all map clauses and must be either
16010 // to or alloc.
16011 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
16012 if (DKind == OMPD_target_enter_data &&
16013 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
16014 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16015 << (IsMapTypeImplicit ? 1 : 0)
16016 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16017 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016018 continue;
16019 }
Samuel Antao661c0902016-05-26 17:39:58 +000016020
16021 // target exit_data
16022 // OpenMP [2.10.3, Restrictions, p. 102]
16023 // A map-type must be specified in all map clauses and must be either
16024 // from, release, or delete.
16025 if (DKind == OMPD_target_exit_data &&
16026 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
16027 MapType == OMPC_MAP_delete)) {
16028 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16029 << (IsMapTypeImplicit ? 1 : 0)
16030 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16031 << getOpenMPDirectiveName(DKind);
16032 continue;
16033 }
16034
16035 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16036 // A list item cannot appear in both a map clause and a data-sharing
16037 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000016038 //
16039 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16040 // A list item cannot appear in both a map clause and a data-sharing
16041 // attribute clause on the same construct unless the construct is a
16042 // combined construct.
16043 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
16044 isOpenMPTargetExecutionDirective(DKind)) ||
16045 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016046 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016047 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000016048 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000016049 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000016050 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000016051 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016052 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000016053 continue;
16054 }
16055 }
Michael Kruse01f670d2019-02-22 22:29:42 +000016056 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016057
Michael Kruse01f670d2019-02-22 22:29:42 +000016058 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000016059 ExprResult ER = buildUserDefinedMapperRef(
16060 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16061 Type.getCanonicalType(), UnresolvedMapper);
16062 if (ER.isInvalid())
16063 continue;
16064 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016065
Samuel Antao90927002016-04-26 14:54:23 +000016066 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000016067 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000016068
16069 // Store the components in the stack so that they can be used to check
16070 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000016071 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
16072 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000016073
16074 // Save the components and declaration to create the clause. For purposes of
16075 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000016076 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000016077 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16078 MVLI.VarComponents.back().append(CurComponents.begin(),
16079 CurComponents.end());
16080 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
16081 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016082 }
Samuel Antao661c0902016-05-26 17:39:58 +000016083}
16084
Michael Kruse4304e9d2019-02-19 16:38:20 +000016085OMPClause *Sema::ActOnOpenMPMapClause(
16086 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16087 ArrayRef<SourceLocation> MapTypeModifiersLoc,
16088 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
16089 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
16090 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
16091 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
16092 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
16093 OMPC_MAP_MODIFIER_unknown,
16094 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000016095 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
16096
16097 // Process map-type-modifiers, flag errors for duplicate modifiers.
16098 unsigned Count = 0;
16099 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
16100 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
16101 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
16102 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
16103 continue;
16104 }
16105 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000016106 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000016107 Modifiers[Count] = MapTypeModifiers[I];
16108 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
16109 ++Count;
16110 }
16111
Michael Kruse4304e9d2019-02-19 16:38:20 +000016112 MappableVarListInfo MVLI(VarList);
16113 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016114 MapperIdScopeSpec, MapperId, UnresolvedMappers,
16115 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000016116
Samuel Antao5de996e2016-01-22 20:21:36 +000016117 // We need to produce a map clause even if we don't have variables so that
16118 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000016119 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
16120 MVLI.VarBaseDeclarations, MVLI.VarComponents,
16121 MVLI.UDMapperList, Modifiers, ModifiersLoc,
16122 MapperIdScopeSpec.getWithLocInContext(Context),
16123 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016124}
Kelvin Li099bb8c2015-11-24 20:50:12 +000016125
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016126QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
16127 TypeResult ParsedType) {
16128 assert(ParsedType.isUsable());
16129
16130 QualType ReductionType = GetTypeFromParser(ParsedType.get());
16131 if (ReductionType.isNull())
16132 return QualType();
16133
16134 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
16135 // A type name in a declare reduction directive cannot be a function type, an
16136 // array type, a reference type, or a type qualified with const, volatile or
16137 // restrict.
16138 if (ReductionType.hasQualifiers()) {
16139 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
16140 return QualType();
16141 }
16142
16143 if (ReductionType->isFunctionType()) {
16144 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
16145 return QualType();
16146 }
16147 if (ReductionType->isReferenceType()) {
16148 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
16149 return QualType();
16150 }
16151 if (ReductionType->isArrayType()) {
16152 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
16153 return QualType();
16154 }
16155 return ReductionType;
16156}
16157
16158Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
16159 Scope *S, DeclContext *DC, DeclarationName Name,
16160 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
16161 AccessSpecifier AS, Decl *PrevDeclInScope) {
16162 SmallVector<Decl *, 8> Decls;
16163 Decls.reserve(ReductionTypes.size());
16164
16165 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000016166 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016167 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
16168 // A reduction-identifier may not be re-declared 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 OMPDeclareReductionDecl *PrevDRD = 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<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000016184 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016185 while (Filter.hasNext()) {
16186 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
16187 if (InCompoundScope) {
16188 auto I = UsedAsPrevious.find(PrevDecl);
16189 if (I == UsedAsPrevious.end())
16190 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000016191 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016192 UsedAsPrevious[D] = true;
16193 }
16194 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16195 PrevDecl->getLocation();
16196 }
16197 Filter.done();
16198 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016199 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016200 if (!PrevData.second) {
16201 PrevDRD = PrevData.first;
16202 break;
16203 }
16204 }
16205 }
16206 } else if (PrevDeclInScope != nullptr) {
16207 auto *PrevDRDInScope = PrevDRD =
16208 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
16209 do {
16210 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
16211 PrevDRDInScope->getLocation();
16212 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
16213 } while (PrevDRDInScope != nullptr);
16214 }
Alexey Bataeve3727102018-04-18 15:57:46 +000016215 for (const auto &TyData : ReductionTypes) {
16216 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016217 bool Invalid = false;
16218 if (I != PreviousRedeclTypes.end()) {
16219 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
16220 << TyData.first;
16221 Diag(I->second, diag::note_previous_definition);
16222 Invalid = true;
16223 }
16224 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
16225 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
16226 Name, TyData.first, PrevDRD);
16227 DC->addDecl(DRD);
16228 DRD->setAccess(AS);
16229 Decls.push_back(DRD);
16230 if (Invalid)
16231 DRD->setInvalidDecl();
16232 else
16233 PrevDRD = DRD;
16234 }
16235
16236 return DeclGroupPtrTy::make(
16237 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16238}
16239
16240void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16241 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16242
16243 // Enter new function scope.
16244 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016245 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016246 getCurFunction()->setHasOMPDeclareReductionCombiner();
16247
16248 if (S != nullptr)
16249 PushDeclContext(S, DRD);
16250 else
16251 CurContext = DRD;
16252
Faisal Valid143a0c2017-04-01 21:30:49 +000016253 PushExpressionEvaluationContext(
16254 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016255
16256 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016257 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16258 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16259 // uses semantics of argument handles by value, but it should be passed by
16260 // reference. C lang does not support references, so pass all parameters as
16261 // pointers.
16262 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016263 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016264 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016265 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16266 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16267 // uses semantics of argument handles by value, but it should be passed by
16268 // reference. C lang does not support references, so pass all parameters as
16269 // pointers.
16270 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016271 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016272 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16273 if (S != nullptr) {
16274 PushOnScopeChains(OmpInParm, S);
16275 PushOnScopeChains(OmpOutParm, S);
16276 } else {
16277 DRD->addDecl(OmpInParm);
16278 DRD->addDecl(OmpOutParm);
16279 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016280 Expr *InE =
16281 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16282 Expr *OutE =
16283 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16284 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016285}
16286
16287void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16288 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16289 DiscardCleanupsInEvaluationContext();
16290 PopExpressionEvaluationContext();
16291
16292 PopDeclContext();
16293 PopFunctionScopeInfo();
16294
16295 if (Combiner != nullptr)
16296 DRD->setCombiner(Combiner);
16297 else
16298 DRD->setInvalidDecl();
16299}
16300
Alexey Bataev070f43a2017-09-06 14:49:58 +000016301VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016302 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16303
16304 // Enter new function scope.
16305 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016306 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016307
16308 if (S != nullptr)
16309 PushDeclContext(S, DRD);
16310 else
16311 CurContext = DRD;
16312
Faisal Valid143a0c2017-04-01 21:30:49 +000016313 PushExpressionEvaluationContext(
16314 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016315
16316 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016317 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16318 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16319 // uses semantics of argument handles by value, but it should be passed by
16320 // reference. C lang does not support references, so pass all parameters as
16321 // pointers.
16322 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016323 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016324 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016325 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16326 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16327 // uses semantics of argument handles by value, but it should be passed by
16328 // reference. C lang does not support references, so pass all parameters as
16329 // pointers.
16330 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016331 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016332 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016333 if (S != nullptr) {
16334 PushOnScopeChains(OmpPrivParm, S);
16335 PushOnScopeChains(OmpOrigParm, S);
16336 } else {
16337 DRD->addDecl(OmpPrivParm);
16338 DRD->addDecl(OmpOrigParm);
16339 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016340 Expr *OrigE =
16341 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16342 Expr *PrivE =
16343 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16344 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016345 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016346}
16347
Alexey Bataev070f43a2017-09-06 14:49:58 +000016348void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16349 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016350 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16351 DiscardCleanupsInEvaluationContext();
16352 PopExpressionEvaluationContext();
16353
16354 PopDeclContext();
16355 PopFunctionScopeInfo();
16356
Alexey Bataev070f43a2017-09-06 14:49:58 +000016357 if (Initializer != nullptr) {
16358 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16359 } else if (OmpPrivParm->hasInit()) {
16360 DRD->setInitializer(OmpPrivParm->getInit(),
16361 OmpPrivParm->isDirectInit()
16362 ? OMPDeclareReductionDecl::DirectInit
16363 : OMPDeclareReductionDecl::CopyInit);
16364 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016365 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016366 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016367}
16368
16369Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16370 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016371 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016372 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016373 if (S)
16374 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16375 /*AddToContext=*/false);
16376 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016377 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016378 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016379 }
16380 return DeclReductions;
16381}
16382
Michael Kruse251e1482019-02-01 20:25:04 +000016383TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16384 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16385 QualType T = TInfo->getType();
16386 if (D.isInvalidType())
16387 return true;
16388
16389 if (getLangOpts().CPlusPlus) {
16390 // Check that there are no default arguments (C++ only).
16391 CheckExtraCXXDefaultArguments(D);
16392 }
16393
16394 return CreateParsedType(T, TInfo);
16395}
16396
16397QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16398 TypeResult ParsedType) {
16399 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16400
16401 QualType MapperType = GetTypeFromParser(ParsedType.get());
16402 assert(!MapperType.isNull() && "Expect valid mapper type");
16403
16404 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16405 // The type must be of struct, union or class type in C and C++
16406 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16407 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16408 return QualType();
16409 }
16410 return MapperType;
16411}
16412
16413OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16414 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16415 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16416 Decl *PrevDeclInScope) {
16417 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16418 forRedeclarationInCurContext());
16419 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16420 // A mapper-identifier may not be redeclared in the current scope for the
16421 // same type or for a type that is compatible according to the base language
16422 // rules.
16423 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16424 OMPDeclareMapperDecl *PrevDMD = nullptr;
16425 bool InCompoundScope = true;
16426 if (S != nullptr) {
16427 // Find previous declaration with the same name not referenced in other
16428 // declarations.
16429 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16430 InCompoundScope =
16431 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16432 LookupName(Lookup, S);
16433 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16434 /*AllowInlineNamespace=*/false);
16435 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16436 LookupResult::Filter Filter = Lookup.makeFilter();
16437 while (Filter.hasNext()) {
16438 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16439 if (InCompoundScope) {
16440 auto I = UsedAsPrevious.find(PrevDecl);
16441 if (I == UsedAsPrevious.end())
16442 UsedAsPrevious[PrevDecl] = false;
16443 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16444 UsedAsPrevious[D] = true;
16445 }
16446 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16447 PrevDecl->getLocation();
16448 }
16449 Filter.done();
16450 if (InCompoundScope) {
16451 for (const auto &PrevData : UsedAsPrevious) {
16452 if (!PrevData.second) {
16453 PrevDMD = PrevData.first;
16454 break;
16455 }
16456 }
16457 }
16458 } else if (PrevDeclInScope) {
16459 auto *PrevDMDInScope = PrevDMD =
16460 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16461 do {
16462 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16463 PrevDMDInScope->getLocation();
16464 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16465 } while (PrevDMDInScope != nullptr);
16466 }
16467 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16468 bool Invalid = false;
16469 if (I != PreviousRedeclTypes.end()) {
16470 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16471 << MapperType << Name;
16472 Diag(I->second, diag::note_previous_definition);
16473 Invalid = true;
16474 }
16475 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16476 MapperType, VN, PrevDMD);
16477 DC->addDecl(DMD);
16478 DMD->setAccess(AS);
16479 if (Invalid)
16480 DMD->setInvalidDecl();
16481
16482 // Enter new function scope.
16483 PushFunctionScope();
16484 setFunctionHasBranchProtectedScope();
16485
16486 CurContext = DMD;
16487
16488 return DMD;
16489}
16490
16491void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16492 Scope *S,
16493 QualType MapperType,
16494 SourceLocation StartLoc,
16495 DeclarationName VN) {
16496 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16497 if (S)
16498 PushOnScopeChains(VD, S);
16499 else
16500 DMD->addDecl(VD);
16501 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16502 DMD->setMapperVarRef(MapperVarRefExpr);
16503}
16504
16505Sema::DeclGroupPtrTy
16506Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16507 ArrayRef<OMPClause *> ClauseList) {
16508 PopDeclContext();
16509 PopFunctionScopeInfo();
16510
16511 if (D) {
16512 if (S)
16513 PushOnScopeChains(D, S, /*AddToContext=*/false);
16514 D->CreateClauses(Context, ClauseList);
16515 }
16516
16517 return DeclGroupPtrTy::make(DeclGroupRef(D));
16518}
16519
David Majnemer9d168222016-08-05 17:44:54 +000016520OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016521 SourceLocation StartLoc,
16522 SourceLocation LParenLoc,
16523 SourceLocation EndLoc) {
16524 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016525 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016526
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016527 // OpenMP [teams Constrcut, Restrictions]
16528 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016529 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016530 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016531 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016532
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016533 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016534 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016535 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016536 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016537 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016538 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016539 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16540 HelperValStmt = buildPreInits(Context, Captures);
16541 }
16542
16543 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16544 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016545}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016546
16547OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16548 SourceLocation StartLoc,
16549 SourceLocation LParenLoc,
16550 SourceLocation EndLoc) {
16551 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016552 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016553
16554 // OpenMP [teams Constrcut, Restrictions]
16555 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016556 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016557 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016558 return nullptr;
16559
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016560 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016561 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16562 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016563 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016564 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016565 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016566 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16567 HelperValStmt = buildPreInits(Context, Captures);
16568 }
16569
16570 return new (Context) OMPThreadLimitClause(
16571 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016572}
Alexey Bataeva0569352015-12-01 10:17:31 +000016573
16574OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16575 SourceLocation StartLoc,
16576 SourceLocation LParenLoc,
16577 SourceLocation EndLoc) {
16578 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016579 Stmt *HelperValStmt = nullptr;
16580 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016581
16582 // OpenMP [2.9.1, task Constrcut]
16583 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016584 if (!isNonNegativeIntegerValue(
16585 ValExpr, *this, OMPC_priority,
16586 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16587 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016588 return nullptr;
16589
Alexey Bataev31ba4762019-10-16 18:09:37 +000016590 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16591 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016592}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016593
16594OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16595 SourceLocation StartLoc,
16596 SourceLocation LParenLoc,
16597 SourceLocation EndLoc) {
16598 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016599 Stmt *HelperValStmt = nullptr;
16600 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016601
16602 // OpenMP [2.9.2, taskloop Constrcut]
16603 // The parameter of the grainsize clause must be a positive integer
16604 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016605 if (!isNonNegativeIntegerValue(
16606 ValExpr, *this, OMPC_grainsize,
16607 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16608 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016609 return nullptr;
16610
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016611 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16612 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016613}
Alexey Bataev382967a2015-12-08 12:06:20 +000016614
16615OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16616 SourceLocation StartLoc,
16617 SourceLocation LParenLoc,
16618 SourceLocation EndLoc) {
16619 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016620 Stmt *HelperValStmt = nullptr;
16621 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016622
16623 // OpenMP [2.9.2, taskloop Constrcut]
16624 // The parameter of the num_tasks clause must be a positive integer
16625 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016626 if (!isNonNegativeIntegerValue(
16627 ValExpr, *this, OMPC_num_tasks,
16628 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16629 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016630 return nullptr;
16631
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016632 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16633 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016634}
16635
Alexey Bataev28c75412015-12-15 08:19:24 +000016636OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16637 SourceLocation LParenLoc,
16638 SourceLocation EndLoc) {
16639 // OpenMP [2.13.2, critical construct, Description]
16640 // ... where hint-expression is an integer constant expression that evaluates
16641 // to a valid lock hint.
16642 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16643 if (HintExpr.isInvalid())
16644 return nullptr;
16645 return new (Context)
16646 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16647}
16648
Carlo Bertollib4adf552016-01-15 18:50:31 +000016649OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16650 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16651 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16652 SourceLocation EndLoc) {
16653 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16654 std::string Values;
16655 Values += "'";
16656 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16657 Values += "'";
16658 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16659 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16660 return nullptr;
16661 }
16662 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016663 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016664 if (ChunkSize) {
16665 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16666 !ChunkSize->isInstantiationDependent() &&
16667 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016668 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016669 ExprResult Val =
16670 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16671 if (Val.isInvalid())
16672 return nullptr;
16673
16674 ValExpr = Val.get();
16675
16676 // OpenMP [2.7.1, Restrictions]
16677 // chunk_size must be a loop invariant integer expression with a positive
16678 // value.
16679 llvm::APSInt Result;
16680 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16681 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16682 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16683 << "dist_schedule" << ChunkSize->getSourceRange();
16684 return nullptr;
16685 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016686 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016687 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16688 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016689 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016690 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016691 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016692 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16693 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016694 }
16695 }
16696 }
16697
16698 return new (Context)
16699 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016700 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016701}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016702
16703OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16704 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16705 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16706 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016707 if (getLangOpts().OpenMP < 50) {
16708 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16709 Kind != OMPC_DEFAULTMAP_scalar) {
16710 std::string Value;
16711 SourceLocation Loc;
16712 Value += "'";
16713 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16714 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16715 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16716 Loc = MLoc;
16717 } else {
16718 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16719 OMPC_DEFAULTMAP_scalar);
16720 Loc = KindLoc;
16721 }
16722 Value += "'";
16723 Diag(Loc, diag::err_omp_unexpected_clause_value)
16724 << Value << getOpenMPClauseName(OMPC_defaultmap);
16725 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016726 }
cchene06f3e02019-11-15 13:02:06 -050016727 } else {
16728 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16729 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16730 if (!isDefaultmapKind || !isDefaultmapModifier) {
16731 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16732 "'firstprivate', 'none', 'default'";
16733 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16734 if (!isDefaultmapKind && isDefaultmapModifier) {
16735 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16736 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16737 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16738 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16739 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16740 } else {
16741 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16742 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16743 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16744 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16745 }
16746 return nullptr;
16747 }
16748
16749 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
16750 // At most one defaultmap clause for each category can appear on the
16751 // directive.
16752 if (DSAStack->checkDefaultmapCategory(Kind)) {
16753 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
16754 return nullptr;
16755 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016756 }
cchene06f3e02019-11-15 13:02:06 -050016757 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016758
16759 return new (Context)
16760 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16761}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016762
16763bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16764 DeclContext *CurLexicalContext = getCurLexicalContext();
16765 if (!CurLexicalContext->isFileContext() &&
16766 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016767 !CurLexicalContext->isExternCXXContext() &&
16768 !isa<CXXRecordDecl>(CurLexicalContext) &&
16769 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16770 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16771 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016772 Diag(Loc, diag::err_omp_region_not_file_context);
16773 return false;
16774 }
Kelvin Libc38e632018-09-10 02:07:09 +000016775 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016776 return true;
16777}
16778
16779void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016780 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016781 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016782 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016783}
16784
Alexey Bataev729e2422019-08-23 16:11:14 +000016785NamedDecl *
16786Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16787 const DeclarationNameInfo &Id,
16788 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016789 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16790 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16791
16792 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016793 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016794 Lookup.suppressDiagnostics();
16795
16796 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016797 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016798 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016799 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016800 CTK_ErrorRecovery)) {
16801 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16802 << Id.getName());
16803 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016804 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016805 }
16806
16807 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016808 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016809 }
16810
16811 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016812 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16813 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016814 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016815 return nullptr;
16816 }
16817 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16818 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16819 return ND;
16820}
16821
16822void Sema::ActOnOpenMPDeclareTargetName(
16823 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16824 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16825 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16826 isa<FunctionTemplateDecl>(ND)) &&
16827 "Expected variable, function or function template.");
16828
16829 // Diagnose marking after use as it may lead to incorrect diagnosis and
16830 // codegen.
16831 if (LangOpts.OpenMP >= 50 &&
16832 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16833 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16834
16835 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16836 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16837 if (DevTy.hasValue() && *DevTy != DT) {
16838 Diag(Loc, diag::err_omp_device_type_mismatch)
16839 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16840 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16841 return;
16842 }
16843 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16844 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16845 if (!Res) {
16846 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16847 SourceRange(Loc, Loc));
16848 ND->addAttr(A);
16849 if (ASTMutationListener *ML = Context.getASTMutationListener())
16850 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16851 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16852 } else if (*Res != MT) {
16853 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016854 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016855}
16856
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016857static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16858 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016859 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016860 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016861 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016862 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16863 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16864 if (SemaRef.LangOpts.OpenMP >= 50 &&
16865 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16866 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16867 VD->hasGlobalStorage()) {
16868 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16869 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16870 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16871 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16872 // If a lambda declaration and definition appears between a
16873 // declare target directive and the matching end declare target
16874 // directive, all variables that are captured by the lambda
16875 // expression must also appear in a to clause.
16876 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016877 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016878 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16879 << VD << 0 << SR;
16880 return;
16881 }
16882 }
16883 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016884 return;
16885 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16886 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016887}
16888
16889static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16890 Sema &SemaRef, DSAStackTy *Stack,
16891 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016892 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016893 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16894 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016895}
16896
Kelvin Li1ce87c72017-12-12 20:08:12 +000016897void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16898 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016899 if (!D || D->isInvalidDecl())
16900 return;
16901 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016902 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016903 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016904 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016905 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16906 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016907 return;
16908 // 2.10.6: threadprivate variable cannot appear in a declare target
16909 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016910 if (DSAStack->isThreadPrivate(VD)) {
16911 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016912 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016913 return;
16914 }
16915 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016916 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16917 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016918 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016919 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16920 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016921 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016922 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16923 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16924 return;
16925 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016926 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016927 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16928 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16929 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16930 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016931 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016932 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16933 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16934 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016935 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016936 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16937 // Problem if any with var declared with incomplete type will be reported
16938 // as normal, so no need to check it here.
16939 if ((E || !VD->getType()->isIncompleteType()) &&
16940 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16941 return;
16942 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16943 // Checking declaration inside declare target region.
16944 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16945 isa<FunctionTemplateDecl>(D)) {
16946 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016947 Context, OMPDeclareTargetDeclAttr::MT_To,
16948 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000016949 D->addAttr(A);
16950 if (ASTMutationListener *ML = Context.getASTMutationListener())
16951 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16952 }
16953 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016954 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016955 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016956 if (!E)
16957 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016958 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16959}
Samuel Antao661c0902016-05-26 17:39:58 +000016960
16961OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000016962 CXXScopeSpec &MapperIdScopeSpec,
16963 DeclarationNameInfo &MapperId,
16964 const OMPVarListLocTy &Locs,
16965 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000016966 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016967 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
16968 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000016969 if (MVLI.ProcessedVarList.empty())
16970 return nullptr;
16971
Michael Kruse01f670d2019-02-22 22:29:42 +000016972 return OMPToClause::Create(
16973 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16974 MVLI.VarComponents, MVLI.UDMapperList,
16975 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000016976}
Samuel Antaoec172c62016-05-26 17:49:04 +000016977
16978OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000016979 CXXScopeSpec &MapperIdScopeSpec,
16980 DeclarationNameInfo &MapperId,
16981 const OMPVarListLocTy &Locs,
16982 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016983 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016984 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
16985 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000016986 if (MVLI.ProcessedVarList.empty())
16987 return nullptr;
16988
Michael Kruse0336c752019-02-25 20:34:15 +000016989 return OMPFromClause::Create(
16990 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16991 MVLI.VarComponents, MVLI.UDMapperList,
16992 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016993}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016994
16995OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016996 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016997 MappableVarListInfo MVLI(VarList);
16998 SmallVector<Expr *, 8> PrivateCopies;
16999 SmallVector<Expr *, 8> Inits;
17000
Alexey Bataeve3727102018-04-18 15:57:46 +000017001 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017002 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
17003 SourceLocation ELoc;
17004 SourceRange ERange;
17005 Expr *SimpleRefExpr = RefExpr;
17006 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17007 if (Res.second) {
17008 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000017009 MVLI.ProcessedVarList.push_back(RefExpr);
17010 PrivateCopies.push_back(nullptr);
17011 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017012 }
17013 ValueDecl *D = Res.first;
17014 if (!D)
17015 continue;
17016
17017 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000017018 Type = Type.getNonReferenceType().getUnqualifiedType();
17019
17020 auto *VD = dyn_cast<VarDecl>(D);
17021
17022 // Item should be a pointer or reference to pointer.
17023 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017024 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
17025 << 0 << RefExpr->getSourceRange();
17026 continue;
17027 }
Samuel Antaocc10b852016-07-28 14:23:26 +000017028
17029 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000017030 auto VDPrivate =
17031 buildVarDecl(*this, ELoc, Type, D->getName(),
17032 D->hasAttrs() ? &D->getAttrs() : nullptr,
17033 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000017034 if (VDPrivate->isInvalidDecl())
17035 continue;
17036
17037 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000017038 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000017039 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
17040
17041 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000017042 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000017043 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000017044 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
17045 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000017046 AddInitializerToDecl(VDPrivate,
17047 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000017048 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000017049
17050 // If required, build a capture to implement the privatization initialized
17051 // with the current list item value.
17052 DeclRefExpr *Ref = nullptr;
17053 if (!VD)
17054 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17055 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
17056 PrivateCopies.push_back(VDPrivateRefExpr);
17057 Inits.push_back(VDInitRefExpr);
17058
17059 // We need to add a data sharing attribute for this variable to make sure it
17060 // is correctly captured. A variable that shows up in a use_device_ptr has
17061 // similar properties of a first private variable.
17062 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
17063
17064 // Create a mappable component for the list item. List items in this clause
17065 // only need a component.
17066 MVLI.VarBaseDeclarations.push_back(D);
17067 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17068 MVLI.VarComponents.back().push_back(
17069 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000017070 }
17071
Samuel Antaocc10b852016-07-28 14:23:26 +000017072 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000017073 return nullptr;
17074
Samuel Antaocc10b852016-07-28 14:23:26 +000017075 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000017076 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
17077 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017078}
Carlo Bertolli70594e92016-07-13 17:16:49 +000017079
17080OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017081 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000017082 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000017083 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000017084 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000017085 SourceLocation ELoc;
17086 SourceRange ERange;
17087 Expr *SimpleRefExpr = RefExpr;
17088 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17089 if (Res.second) {
17090 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000017091 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017092 }
17093 ValueDecl *D = Res.first;
17094 if (!D)
17095 continue;
17096
17097 QualType Type = D->getType();
17098 // item should be a pointer or array or reference to pointer or array
17099 if (!Type.getNonReferenceType()->isPointerType() &&
17100 !Type.getNonReferenceType()->isArrayType()) {
17101 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
17102 << 0 << RefExpr->getSourceRange();
17103 continue;
17104 }
Samuel Antao6890b092016-07-28 14:25:09 +000017105
17106 // Check if the declaration in the clause does not show up in any data
17107 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000017108 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000017109 if (isOpenMPPrivate(DVar.CKind)) {
17110 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17111 << getOpenMPClauseName(DVar.CKind)
17112 << getOpenMPClauseName(OMPC_is_device_ptr)
17113 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000017114 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000017115 continue;
17116 }
17117
Alexey Bataeve3727102018-04-18 15:57:46 +000017118 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000017119 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000017120 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000017121 [&ConflictExpr](
17122 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
17123 OpenMPClauseKind) -> bool {
17124 ConflictExpr = R.front().getAssociatedExpression();
17125 return true;
17126 })) {
17127 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
17128 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
17129 << ConflictExpr->getSourceRange();
17130 continue;
17131 }
17132
17133 // Store the components in the stack so that they can be used to check
17134 // against other clauses later on.
17135 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
17136 DSAStack->addMappableExpressionComponents(
17137 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
17138
17139 // Record the expression we've just processed.
17140 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
17141
17142 // Create a mappable component for the list item. List items in this clause
17143 // only need a component. We use a null declaration to signal fields in
17144 // 'this'.
17145 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
17146 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
17147 "Unexpected device pointer expression!");
17148 MVLI.VarBaseDeclarations.push_back(
17149 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
17150 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17151 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017152 }
17153
Samuel Antao6890b092016-07-28 14:25:09 +000017154 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000017155 return nullptr;
17156
Michael Kruse4304e9d2019-02-19 16:38:20 +000017157 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
17158 MVLI.VarBaseDeclarations,
17159 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017160}
Alexey Bataeve04483e2019-03-27 14:14:31 +000017161
17162OMPClause *Sema::ActOnOpenMPAllocateClause(
17163 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17164 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
17165 if (Allocator) {
17166 // OpenMP [2.11.4 allocate Clause, Description]
17167 // allocator is an expression of omp_allocator_handle_t type.
17168 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
17169 return nullptr;
17170
17171 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
17172 if (AllocatorRes.isInvalid())
17173 return nullptr;
17174 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
17175 DSAStack->getOMPAllocatorHandleT(),
17176 Sema::AA_Initializing,
17177 /*AllowExplicit=*/true);
17178 if (AllocatorRes.isInvalid())
17179 return nullptr;
17180 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000017181 } else {
17182 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
17183 // allocate clauses that appear on a target construct or on constructs in a
17184 // target region must specify an allocator expression unless a requires
17185 // directive with the dynamic_allocators clause is present in the same
17186 // compilation unit.
17187 if (LangOpts.OpenMPIsDevice &&
17188 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
17189 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017190 }
17191 // Analyze and build list of variables.
17192 SmallVector<Expr *, 8> Vars;
17193 for (Expr *RefExpr : VarList) {
17194 assert(RefExpr && "NULL expr in OpenMP private clause.");
17195 SourceLocation ELoc;
17196 SourceRange ERange;
17197 Expr *SimpleRefExpr = RefExpr;
17198 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17199 if (Res.second) {
17200 // It will be analyzed later.
17201 Vars.push_back(RefExpr);
17202 }
17203 ValueDecl *D = Res.first;
17204 if (!D)
17205 continue;
17206
17207 auto *VD = dyn_cast<VarDecl>(D);
17208 DeclRefExpr *Ref = nullptr;
17209 if (!VD && !CurContext->isDependentContext())
17210 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17211 Vars.push_back((VD || CurContext->isDependentContext())
17212 ? RefExpr->IgnoreParens()
17213 : Ref);
17214 }
17215
17216 if (Vars.empty())
17217 return nullptr;
17218
17219 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
17220 ColonLoc, EndLoc, Vars);
17221}
Alexey Bataevb6e70842019-12-16 15:54:17 -050017222
17223OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
17224 SourceLocation StartLoc,
17225 SourceLocation LParenLoc,
17226 SourceLocation EndLoc) {
17227 SmallVector<Expr *, 8> Vars;
17228 for (Expr *RefExpr : VarList) {
17229 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
17230 SourceLocation ELoc;
17231 SourceRange ERange;
17232 Expr *SimpleRefExpr = RefExpr;
17233 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17234 if (Res.second)
17235 // It will be analyzed later.
17236 Vars.push_back(RefExpr);
17237 ValueDecl *D = Res.first;
17238 if (!D)
17239 continue;
17240
Alexey Bataevb6e70842019-12-16 15:54:17 -050017241 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
17242 // A list-item cannot appear in more than one nontemporal clause.
17243 if (const Expr *PrevRef =
17244 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
17245 Diag(ELoc, diag::err_omp_used_in_clause_twice)
17246 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
17247 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17248 << getOpenMPClauseName(OMPC_nontemporal);
17249 continue;
17250 }
17251
Alexey Bataev0860db92019-12-19 10:01:10 -050017252 Vars.push_back(RefExpr);
Alexey Bataevb6e70842019-12-16 15:54:17 -050017253 }
17254
17255 if (Vars.empty())
17256 return nullptr;
17257
17258 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17259 Vars);
17260}