blob: 7365fda62beee3146cd1d006b00fc6ad759c9727 [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:
Alexey Bataeved09d242014-05-28 05:53:51 +000011860 Res = ActOnOpenMPProcBindClause(
11861 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
11862 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011863 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011864 case OMPC_atomic_default_mem_order:
11865 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11866 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11867 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11868 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011869 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011870 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011871 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011872 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011873 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011874 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011875 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011876 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011877 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011878 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011879 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011880 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011881 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011882 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011883 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011884 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011885 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011886 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011887 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011888 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011889 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011890 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011891 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011892 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011893 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011894 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011895 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011896 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011897 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011898 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011899 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011900 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011901 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011902 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011903 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011904 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011905 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011906 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011907 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011908 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011909 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011910 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011911 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011912 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011913 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011914 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011915 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011916 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011917 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011918 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011919 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011920 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011921 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011922 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011923 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011924 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011925 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011926 case OMPC_nontemporal:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011927 llvm_unreachable("Clause is not allowed.");
11928 }
11929 return Res;
11930}
11931
Alexey Bataev6402bca2015-12-28 07:25:51 +000011932static std::string
11933getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11934 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011935 SmallString<256> Buffer;
11936 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011937 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11938 unsigned Skipped = Exclude.size();
11939 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011940 for (unsigned I = First; I < Last; ++I) {
11941 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011942 --Skipped;
11943 continue;
11944 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011945 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11946 if (I == Bound - Skipped)
11947 Out << " or ";
11948 else if (I != Bound + 1 - Skipped)
11949 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011950 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011951 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011952}
11953
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011954OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11955 SourceLocation KindKwLoc,
11956 SourceLocation StartLoc,
11957 SourceLocation LParenLoc,
11958 SourceLocation EndLoc) {
11959 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011960 static_assert(OMPC_DEFAULT_unknown > 0,
11961 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011962 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011963 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11964 /*Last=*/OMPC_DEFAULT_unknown)
11965 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011966 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011967 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011968 switch (Kind) {
11969 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011970 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011971 break;
11972 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011973 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011974 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011975 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011976 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011977 break;
11978 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011979 return new (Context)
11980 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011981}
11982
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011983OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11984 SourceLocation KindKwLoc,
11985 SourceLocation StartLoc,
11986 SourceLocation LParenLoc,
11987 SourceLocation EndLoc) {
11988 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011989 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011990 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11991 /*Last=*/OMPC_PROC_BIND_unknown)
11992 << 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,
12405 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000012406 OpenMPLinearClauseKind LinKind,
12407 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012408 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
12409 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
12410 SourceLocation StartLoc = Locs.StartLoc;
12411 SourceLocation LParenLoc = Locs.LParenLoc;
12412 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012413 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012414 switch (Kind) {
12415 case OMPC_private:
12416 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12417 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012418 case OMPC_firstprivate:
12419 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12420 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012421 case OMPC_lastprivate:
12422 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12423 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012424 case OMPC_shared:
12425 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12426 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012427 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012428 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012429 EndLoc, ReductionOrMapperIdScopeSpec,
12430 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012431 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012432 case OMPC_task_reduction:
12433 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012434 EndLoc, ReductionOrMapperIdScopeSpec,
12435 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012436 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012437 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012438 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12439 EndLoc, ReductionOrMapperIdScopeSpec,
12440 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012441 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012442 case OMPC_linear:
12443 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012444 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012445 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012446 case OMPC_aligned:
12447 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12448 ColonLoc, EndLoc);
12449 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012450 case OMPC_copyin:
12451 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12452 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012453 case OMPC_copyprivate:
12454 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12455 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012456 case OMPC_flush:
12457 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12458 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012459 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000012460 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000012461 StartLoc, LParenLoc, EndLoc);
12462 break;
12463 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012464 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
12465 ReductionOrMapperIdScopeSpec,
12466 ReductionOrMapperId, MapType, IsMapTypeImplicit,
12467 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012468 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012469 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012470 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12471 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012472 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012473 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012474 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12475 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012476 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012477 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012478 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012479 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012480 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012481 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012482 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012483 case OMPC_allocate:
12484 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12485 ColonLoc, EndLoc);
12486 break;
Alexey Bataevb6e70842019-12-16 15:54:17 -050012487 case OMPC_nontemporal:
12488 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
12489 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012490 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012491 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012492 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012493 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012494 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012495 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012496 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012497 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012498 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012499 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012500 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012501 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012502 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012503 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012504 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012505 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012506 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012507 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012508 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012509 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012510 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012511 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012512 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012513 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012514 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012515 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012516 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012517 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012518 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012519 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012520 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012521 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012522 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012523 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012524 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012525 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012526 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012527 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012528 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012529 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012530 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012531 llvm_unreachable("Clause is not allowed.");
12532 }
12533 return Res;
12534}
12535
Alexey Bataev90c228f2016-02-08 09:29:13 +000012536ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012537 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012538 ExprResult Res = BuildDeclRefExpr(
12539 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12540 if (!Res.isUsable())
12541 return ExprError();
12542 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12543 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12544 if (!Res.isUsable())
12545 return ExprError();
12546 }
12547 if (VK != VK_LValue && Res.get()->isGLValue()) {
12548 Res = DefaultLvalueConversion(Res.get());
12549 if (!Res.isUsable())
12550 return ExprError();
12551 }
12552 return Res;
12553}
12554
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012555OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12556 SourceLocation StartLoc,
12557 SourceLocation LParenLoc,
12558 SourceLocation EndLoc) {
12559 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012560 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012561 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012562 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012563 SourceLocation ELoc;
12564 SourceRange ERange;
12565 Expr *SimpleRefExpr = RefExpr;
12566 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012567 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012568 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012569 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012570 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012571 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012572 ValueDecl *D = Res.first;
12573 if (!D)
12574 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012575
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012576 QualType Type = D->getType();
12577 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012578
12579 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12580 // A variable that appears in a private clause must not have an incomplete
12581 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012582 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012583 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012584 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012585
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012586 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12587 // A variable that is privatized must not have a const-qualified type
12588 // unless it is of class type with a mutable member. This restriction does
12589 // not apply to the firstprivate clause.
12590 //
12591 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12592 // A variable that appears in a private clause must not have a
12593 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012594 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012595 continue;
12596
Alexey Bataev758e55e2013-09-06 18:03:48 +000012597 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12598 // in a Construct]
12599 // Variables with the predetermined data-sharing attributes may not be
12600 // listed in data-sharing attributes clauses, except for the cases
12601 // listed below. For these exceptions only, listing a predetermined
12602 // variable in a data-sharing attribute clause is allowed and overrides
12603 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012604 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012605 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012606 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12607 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012608 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012609 continue;
12610 }
12611
Alexey Bataeve3727102018-04-18 15:57:46 +000012612 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012613 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012614 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012615 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012616 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12617 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012618 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012619 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012620 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012621 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012622 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012623 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012624 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012625 continue;
12626 }
12627
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012628 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12629 // A list item cannot appear in both a map clause and a data-sharing
12630 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012631 //
12632 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12633 // A list item cannot appear in both a map clause and a data-sharing
12634 // attribute clause on the same construct unless the construct is a
12635 // combined construct.
12636 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12637 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012638 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012639 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012640 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012641 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12642 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12643 ConflictKind = WhereFoundClauseKind;
12644 return true;
12645 })) {
12646 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012647 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012648 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012649 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012650 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012651 continue;
12652 }
12653 }
12654
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012655 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12656 // A variable of class type (or array thereof) that appears in a private
12657 // clause requires an accessible, unambiguous default constructor for the
12658 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012659 // Generate helper private variable and initialize it with the default
12660 // value. The address of the original variable is replaced by the address of
12661 // the new private variable in CodeGen. This new variable is not added to
12662 // IdResolver, so the code in the OpenMP region uses original variable for
12663 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012664 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012665 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012666 buildVarDecl(*this, ELoc, Type, D->getName(),
12667 D->hasAttrs() ? &D->getAttrs() : nullptr,
12668 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012669 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012670 if (VDPrivate->isInvalidDecl())
12671 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012672 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012673 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012674
Alexey Bataev90c228f2016-02-08 09:29:13 +000012675 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012676 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012677 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012678 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012679 Vars.push_back((VD || CurContext->isDependentContext())
12680 ? RefExpr->IgnoreParens()
12681 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012682 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012683 }
12684
Alexey Bataeved09d242014-05-28 05:53:51 +000012685 if (Vars.empty())
12686 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012687
Alexey Bataev03b340a2014-10-21 03:16:40 +000012688 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12689 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012690}
12691
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012692namespace {
12693class DiagsUninitializedSeveretyRAII {
12694private:
12695 DiagnosticsEngine &Diags;
12696 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012697 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012698
12699public:
12700 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12701 bool IsIgnored)
12702 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12703 if (!IsIgnored) {
12704 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12705 /*Map*/ diag::Severity::Ignored, Loc);
12706 }
12707 }
12708 ~DiagsUninitializedSeveretyRAII() {
12709 if (!IsIgnored)
12710 Diags.popMappings(SavedLoc);
12711 }
12712};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012713}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012714
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012715OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12716 SourceLocation StartLoc,
12717 SourceLocation LParenLoc,
12718 SourceLocation EndLoc) {
12719 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012720 SmallVector<Expr *, 8> PrivateCopies;
12721 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012722 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012723 bool IsImplicitClause =
12724 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012725 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012726
Alexey Bataeve3727102018-04-18 15:57:46 +000012727 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012728 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012729 SourceLocation ELoc;
12730 SourceRange ERange;
12731 Expr *SimpleRefExpr = RefExpr;
12732 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012733 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012734 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012735 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012736 PrivateCopies.push_back(nullptr);
12737 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012738 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012739 ValueDecl *D = Res.first;
12740 if (!D)
12741 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012742
Alexey Bataev60da77e2016-02-29 05:54:20 +000012743 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012744 QualType Type = D->getType();
12745 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012746
12747 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12748 // A variable that appears in a private clause must not have an incomplete
12749 // type or a reference type.
12750 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012751 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012752 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012753 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012754
12755 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12756 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012757 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012758 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012759 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012760
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012761 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012762 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012763 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012764 DSAStackTy::DSAVarData DVar =
12765 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012766 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012767 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012768 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012769 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12770 // A list item that specifies a given variable may not appear in more
12771 // than one clause on the same directive, except that a variable may be
12772 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012773 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12774 // A list item may appear in a firstprivate or lastprivate clause but not
12775 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012776 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012777 (isOpenMPDistributeDirective(CurrDir) ||
12778 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012779 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012780 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012781 << getOpenMPClauseName(DVar.CKind)
12782 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012783 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012784 continue;
12785 }
12786
12787 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12788 // in a Construct]
12789 // Variables with the predetermined data-sharing attributes may not be
12790 // listed in data-sharing attributes clauses, except for the cases
12791 // listed below. For these exceptions only, listing a predetermined
12792 // variable in a data-sharing attribute clause is allowed and overrides
12793 // the variable's predetermined data-sharing attributes.
12794 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12795 // in a Construct, C/C++, p.2]
12796 // Variables with const-qualified type having no mutable member may be
12797 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012798 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012799 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12800 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012801 << getOpenMPClauseName(DVar.CKind)
12802 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012803 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012804 continue;
12805 }
12806
12807 // OpenMP [2.9.3.4, Restrictions, p.2]
12808 // A list item that is private within a parallel region must not appear
12809 // in a firstprivate clause on a worksharing construct if any of the
12810 // worksharing regions arising from the worksharing construct ever bind
12811 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012812 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12813 // A list item that is private within a teams region must not appear in a
12814 // firstprivate clause on a distribute construct if any of the distribute
12815 // regions arising from the distribute construct ever bind to any of the
12816 // teams regions arising from the teams construct.
12817 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12818 // A list item that appears in a reduction clause of a teams construct
12819 // must not appear in a firstprivate clause on a distribute construct if
12820 // any of the distribute regions arising from the distribute construct
12821 // ever bind to any of the teams regions arising from the teams construct.
12822 if ((isOpenMPWorksharingDirective(CurrDir) ||
12823 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012824 !isOpenMPParallelDirective(CurrDir) &&
12825 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012826 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012827 if (DVar.CKind != OMPC_shared &&
12828 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012829 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012830 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012831 Diag(ELoc, diag::err_omp_required_access)
12832 << getOpenMPClauseName(OMPC_firstprivate)
12833 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012834 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012835 continue;
12836 }
12837 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012838 // OpenMP [2.9.3.4, Restrictions, p.3]
12839 // A list item that appears in a reduction clause of a parallel construct
12840 // must not appear in a firstprivate clause on a worksharing or task
12841 // construct if any of the worksharing or task regions arising from the
12842 // worksharing or task construct ever bind to any of the parallel regions
12843 // arising from the parallel construct.
12844 // OpenMP [2.9.3.4, Restrictions, p.4]
12845 // A list item that appears in a reduction clause in worksharing
12846 // construct must not appear in a firstprivate clause in a task construct
12847 // encountered during execution of any of the worksharing regions arising
12848 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012849 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012850 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012851 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12852 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012853 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012854 isOpenMPWorksharingDirective(K) ||
12855 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012856 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012857 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012858 if (DVar.CKind == OMPC_reduction &&
12859 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012860 isOpenMPWorksharingDirective(DVar.DKind) ||
12861 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012862 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12863 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012864 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012865 continue;
12866 }
12867 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012868
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012869 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12870 // A list item cannot appear in both a map clause and a data-sharing
12871 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012872 //
12873 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12874 // A list item cannot appear in both a map clause and a data-sharing
12875 // attribute clause on the same construct unless the construct is a
12876 // combined construct.
12877 if ((LangOpts.OpenMP <= 45 &&
12878 isOpenMPTargetExecutionDirective(CurrDir)) ||
12879 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012880 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012881 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012882 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012883 [&ConflictKind](
12884 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12885 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012886 ConflictKind = WhereFoundClauseKind;
12887 return true;
12888 })) {
12889 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012890 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012891 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012892 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012893 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012894 continue;
12895 }
12896 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012897 }
12898
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012899 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012900 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012901 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012902 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12903 << getOpenMPClauseName(OMPC_firstprivate) << Type
12904 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12905 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012906 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012907 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012908 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012909 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012910 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012911 continue;
12912 }
12913
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012914 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012915 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012916 buildVarDecl(*this, ELoc, Type, D->getName(),
12917 D->hasAttrs() ? &D->getAttrs() : nullptr,
12918 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012919 // Generate helper private variable and initialize it with the value of the
12920 // original variable. The address of the original variable is replaced by
12921 // the address of the new private variable in the CodeGen. This new variable
12922 // is not added to IdResolver, so the code in the OpenMP region uses
12923 // original variable for proper diagnostics and variable capturing.
12924 Expr *VDInitRefExpr = nullptr;
12925 // For arrays generate initializer for single element and replace it by the
12926 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012927 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012928 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012929 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012930 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012931 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012932 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012933 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12934 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012935 InitializedEntity Entity =
12936 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012937 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12938
12939 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12940 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12941 if (Result.isInvalid())
12942 VDPrivate->setInvalidDecl();
12943 else
12944 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012945 // Remove temp variable declaration.
12946 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012947 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012948 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12949 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012950 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12951 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012952 AddInitializerToDecl(VDPrivate,
12953 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012954 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012955 }
12956 if (VDPrivate->isInvalidDecl()) {
12957 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012958 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012959 diag::note_omp_task_predetermined_firstprivate_here);
12960 }
12961 continue;
12962 }
12963 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012964 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012965 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12966 RefExpr->getExprLoc());
12967 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012968 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012969 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012970 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012971 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012972 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012973 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012974 ExprCaptures.push_back(Ref->getDecl());
12975 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012976 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012977 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012978 Vars.push_back((VD || CurContext->isDependentContext())
12979 ? RefExpr->IgnoreParens()
12980 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012981 PrivateCopies.push_back(VDPrivateRefExpr);
12982 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012983 }
12984
Alexey Bataeved09d242014-05-28 05:53:51 +000012985 if (Vars.empty())
12986 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012987
12988 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012989 Vars, PrivateCopies, Inits,
12990 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012991}
12992
Alexander Musman1bb328c2014-06-04 13:06:39 +000012993OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12994 SourceLocation StartLoc,
12995 SourceLocation LParenLoc,
12996 SourceLocation EndLoc) {
12997 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012998 SmallVector<Expr *, 8> SrcExprs;
12999 SmallVector<Expr *, 8> DstExprs;
13000 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000013001 SmallVector<Decl *, 4> ExprCaptures;
13002 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000013003 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013004 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013005 SourceLocation ELoc;
13006 SourceRange ERange;
13007 Expr *SimpleRefExpr = RefExpr;
13008 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000013009 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013010 // It will be analyzed later.
13011 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013012 SrcExprs.push_back(nullptr);
13013 DstExprs.push_back(nullptr);
13014 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013015 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013016 ValueDecl *D = Res.first;
13017 if (!D)
13018 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013019
Alexey Bataev74caaf22016-02-20 04:09:36 +000013020 QualType Type = D->getType();
13021 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013022
13023 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
13024 // A variable that appears in a lastprivate clause must not have an
13025 // incomplete type or a reference type.
13026 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000013027 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000013028 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013029 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013030
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013031 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13032 // A variable that is privatized must not have a const-qualified type
13033 // unless it is of class type with a mutable member. This restriction does
13034 // not apply to the firstprivate clause.
13035 //
13036 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
13037 // A variable that appears in a lastprivate clause must not have a
13038 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013039 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013040 continue;
13041
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013042 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013043 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13044 // in a Construct]
13045 // Variables with the predetermined data-sharing attributes may not be
13046 // listed in data-sharing attributes clauses, except for the cases
13047 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013048 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13049 // A list item may appear in a firstprivate or lastprivate clause but not
13050 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000013051 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013052 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000013053 (isOpenMPDistributeDirective(CurrDir) ||
13054 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000013055 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
13056 Diag(ELoc, diag::err_omp_wrong_dsa)
13057 << getOpenMPClauseName(DVar.CKind)
13058 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013059 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013060 continue;
13061 }
13062
Alexey Bataevf29276e2014-06-18 04:14:57 +000013063 // OpenMP [2.14.3.5, Restrictions, p.2]
13064 // A list item that is private within a parallel region, or that appears in
13065 // the reduction clause of a parallel construct, must not appear in a
13066 // lastprivate clause on a worksharing construct if any of the corresponding
13067 // worksharing regions ever binds to any of the corresponding parallel
13068 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000013069 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000013070 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013071 !isOpenMPParallelDirective(CurrDir) &&
13072 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000013073 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013074 if (DVar.CKind != OMPC_shared) {
13075 Diag(ELoc, diag::err_omp_required_access)
13076 << getOpenMPClauseName(OMPC_lastprivate)
13077 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013078 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013079 continue;
13080 }
13081 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013082
Alexander Musman1bb328c2014-06-04 13:06:39 +000013083 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000013084 // A variable of class type (or array thereof) that appears in a
13085 // lastprivate clause requires an accessible, unambiguous default
13086 // constructor for the class type, unless the list item is also specified
13087 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000013088 // A variable of class type (or array thereof) that appears in a
13089 // lastprivate clause requires an accessible, unambiguous copy assignment
13090 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000013091 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013092 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
13093 Type.getUnqualifiedType(), ".lastprivate.src",
13094 D->hasAttrs() ? &D->getAttrs() : nullptr);
13095 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000013096 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013097 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013098 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000013099 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013100 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000013101 // For arrays generate assignment operation for single element and replace
13102 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013103 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
13104 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013105 if (AssignmentOp.isInvalid())
13106 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013107 AssignmentOp =
13108 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000013109 if (AssignmentOp.isInvalid())
13110 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013111
Alexey Bataev74caaf22016-02-20 04:09:36 +000013112 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013113 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013114 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013115 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013116 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013117 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013118 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013119 ExprCaptures.push_back(Ref->getDecl());
13120 }
13121 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013122 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013123 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013124 ExprResult RefRes = DefaultLvalueConversion(Ref);
13125 if (!RefRes.isUsable())
13126 continue;
13127 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013128 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13129 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013130 if (!PostUpdateRes.isUsable())
13131 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013132 ExprPostUpdates.push_back(
13133 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013134 }
13135 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013136 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013137 Vars.push_back((VD || CurContext->isDependentContext())
13138 ? RefExpr->IgnoreParens()
13139 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000013140 SrcExprs.push_back(PseudoSrcExpr);
13141 DstExprs.push_back(PseudoDstExpr);
13142 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000013143 }
13144
13145 if (Vars.empty())
13146 return nullptr;
13147
13148 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000013149 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013150 buildPreInits(Context, ExprCaptures),
13151 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000013152}
13153
Alexey Bataev758e55e2013-09-06 18:03:48 +000013154OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
13155 SourceLocation StartLoc,
13156 SourceLocation LParenLoc,
13157 SourceLocation EndLoc) {
13158 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013159 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013160 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013161 SourceLocation ELoc;
13162 SourceRange ERange;
13163 Expr *SimpleRefExpr = RefExpr;
13164 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013165 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000013166 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013167 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013168 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013169 ValueDecl *D = Res.first;
13170 if (!D)
13171 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013172
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013173 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013174 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13175 // in a Construct]
13176 // Variables with the predetermined data-sharing attributes may not be
13177 // listed in data-sharing attributes clauses, except for the cases
13178 // listed below. For these exceptions only, listing a predetermined
13179 // variable in a data-sharing attribute clause is allowed and overrides
13180 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000013181 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000013182 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
13183 DVar.RefExpr) {
13184 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13185 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013186 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013187 continue;
13188 }
13189
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013190 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013191 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000013192 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013193 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013194 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
13195 ? RefExpr->IgnoreParens()
13196 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013197 }
13198
Alexey Bataeved09d242014-05-28 05:53:51 +000013199 if (Vars.empty())
13200 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013201
13202 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13203}
13204
Alexey Bataevc5e02582014-06-16 07:08:35 +000013205namespace {
13206class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13207 DSAStackTy *Stack;
13208
13209public:
13210 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013211 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13212 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013213 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13214 return false;
13215 if (DVar.CKind != OMPC_unknown)
13216 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013217 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013218 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013219 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013220 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013221 }
13222 return false;
13223 }
13224 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013225 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013226 if (Child && Visit(Child))
13227 return true;
13228 }
13229 return false;
13230 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013231 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013232};
Alexey Bataev23b69422014-06-18 07:08:49 +000013233} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013234
Alexey Bataev60da77e2016-02-29 05:54:20 +000013235namespace {
13236// Transform MemberExpression for specified FieldDecl of current class to
13237// DeclRefExpr to specified OMPCapturedExprDecl.
13238class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13239 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013240 ValueDecl *Field = nullptr;
13241 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013242
13243public:
13244 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13245 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13246
13247 ExprResult TransformMemberExpr(MemberExpr *E) {
13248 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13249 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013250 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013251 return CapturedExpr;
13252 }
13253 return BaseTransform::TransformMemberExpr(E);
13254 }
13255 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13256};
13257} // namespace
13258
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013259template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013260static T filterLookupForUDReductionAndMapper(
13261 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013262 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013263 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013264 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013265 return Res;
13266 }
13267 }
13268 return T();
13269}
13270
Alexey Bataev43b90b72018-09-12 16:31:59 +000013271static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13272 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13273
13274 for (auto RD : D->redecls()) {
13275 // Don't bother with extra checks if we already know this one isn't visible.
13276 if (RD == D)
13277 continue;
13278
13279 auto ND = cast<NamedDecl>(RD);
13280 if (LookupResult::isVisible(SemaRef, ND))
13281 return ND;
13282 }
13283
13284 return nullptr;
13285}
13286
13287static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013288argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013289 SourceLocation Loc, QualType Ty,
13290 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13291 // Find all of the associated namespaces and classes based on the
13292 // arguments we have.
13293 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13294 Sema::AssociatedClassSet AssociatedClasses;
13295 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13296 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13297 AssociatedClasses);
13298
13299 // C++ [basic.lookup.argdep]p3:
13300 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13301 // and let Y be the lookup set produced by argument dependent
13302 // lookup (defined as follows). If X contains [...] then Y is
13303 // empty. Otherwise Y is the set of declarations found in the
13304 // namespaces associated with the argument types as described
13305 // below. The set of declarations found by the lookup of the name
13306 // is the union of X and Y.
13307 //
13308 // Here, we compute Y and add its members to the overloaded
13309 // candidate set.
13310 for (auto *NS : AssociatedNamespaces) {
13311 // When considering an associated namespace, the lookup is the
13312 // same as the lookup performed when the associated namespace is
13313 // used as a qualifier (3.4.3.2) except that:
13314 //
13315 // -- Any using-directives in the associated namespace are
13316 // ignored.
13317 //
13318 // -- Any namespace-scope friend functions declared in
13319 // associated classes are visible within their respective
13320 // namespaces even if they are not visible during an ordinary
13321 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013322 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013323 for (auto *D : R) {
13324 auto *Underlying = D;
13325 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13326 Underlying = USD->getTargetDecl();
13327
Michael Kruse4304e9d2019-02-19 16:38:20 +000013328 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13329 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013330 continue;
13331
13332 if (!SemaRef.isVisible(D)) {
13333 D = findAcceptableDecl(SemaRef, D);
13334 if (!D)
13335 continue;
13336 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13337 Underlying = USD->getTargetDecl();
13338 }
13339 Lookups.emplace_back();
13340 Lookups.back().addDecl(Underlying);
13341 }
13342 }
13343}
13344
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013345static ExprResult
13346buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13347 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13348 const DeclarationNameInfo &ReductionId, QualType Ty,
13349 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13350 if (ReductionIdScopeSpec.isInvalid())
13351 return ExprError();
13352 SmallVector<UnresolvedSet<8>, 4> Lookups;
13353 if (S) {
13354 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13355 Lookup.suppressDiagnostics();
13356 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013357 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013358 do {
13359 S = S->getParent();
13360 } while (S && !S->isDeclScope(D));
13361 if (S)
13362 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013363 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013364 Lookups.back().append(Lookup.begin(), Lookup.end());
13365 Lookup.clear();
13366 }
13367 } else if (auto *ULE =
13368 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13369 Lookups.push_back(UnresolvedSet<8>());
13370 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013371 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013372 if (D == PrevD)
13373 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013374 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013375 Lookups.back().addDecl(DRD);
13376 PrevD = D;
13377 }
13378 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013379 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13380 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013381 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013382 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013383 return !D->isInvalidDecl() &&
13384 (D->getType()->isDependentType() ||
13385 D->getType()->isInstantiationDependentType() ||
13386 D->getType()->containsUnexpandedParameterPack());
13387 })) {
13388 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013389 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013390 if (Set.empty())
13391 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013392 ResSet.append(Set.begin(), Set.end());
13393 // The last item marks the end of all declarations at the specified scope.
13394 ResSet.addDecl(Set[Set.size() - 1]);
13395 }
13396 return UnresolvedLookupExpr::Create(
13397 SemaRef.Context, /*NamingClass=*/nullptr,
13398 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13399 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13400 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013401 // Lookup inside the classes.
13402 // C++ [over.match.oper]p3:
13403 // For a unary operator @ with an operand of a type whose
13404 // cv-unqualified version is T1, and for a binary operator @ with
13405 // a left operand of a type whose cv-unqualified version is T1 and
13406 // a right operand of a type whose cv-unqualified version is T2,
13407 // three sets of candidate functions, designated member
13408 // candidates, non-member candidates and built-in candidates, are
13409 // constructed as follows:
13410 // -- If T1 is a complete class type or a class currently being
13411 // defined, the set of member candidates is the result of the
13412 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13413 // the set of member candidates is empty.
13414 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13415 Lookup.suppressDiagnostics();
13416 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13417 // Complete the type if it can be completed.
13418 // If the type is neither complete nor being defined, bail out now.
13419 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13420 TyRec->getDecl()->getDefinition()) {
13421 Lookup.clear();
13422 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13423 if (Lookup.empty()) {
13424 Lookups.emplace_back();
13425 Lookups.back().append(Lookup.begin(), Lookup.end());
13426 }
13427 }
13428 }
13429 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013430 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013431 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013432 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13433 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13434 if (!D->isInvalidDecl() &&
13435 SemaRef.Context.hasSameType(D->getType(), Ty))
13436 return D;
13437 return nullptr;
13438 }))
13439 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13440 VK_LValue, Loc);
13441 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013442 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13443 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13444 if (!D->isInvalidDecl() &&
13445 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13446 !Ty.isMoreQualifiedThan(D->getType()))
13447 return D;
13448 return nullptr;
13449 })) {
13450 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13451 /*DetectVirtual=*/false);
13452 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13453 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13454 VD->getType().getUnqualifiedType()))) {
13455 if (SemaRef.CheckBaseClassAccess(
13456 Loc, VD->getType(), Ty, Paths.front(),
13457 /*DiagID=*/0) != Sema::AR_inaccessible) {
13458 SemaRef.BuildBasePathArray(Paths, BasePath);
13459 return SemaRef.BuildDeclRefExpr(
13460 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13461 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013462 }
13463 }
13464 }
13465 }
13466 if (ReductionIdScopeSpec.isSet()) {
13467 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
13468 return ExprError();
13469 }
13470 return ExprEmpty();
13471}
13472
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013473namespace {
13474/// Data for the reduction-based clauses.
13475struct ReductionData {
13476 /// List of original reduction items.
13477 SmallVector<Expr *, 8> Vars;
13478 /// List of private copies of the reduction items.
13479 SmallVector<Expr *, 8> Privates;
13480 /// LHS expressions for the reduction_op expressions.
13481 SmallVector<Expr *, 8> LHSs;
13482 /// RHS expressions for the reduction_op expressions.
13483 SmallVector<Expr *, 8> RHSs;
13484 /// Reduction operation expression.
13485 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013486 /// Taskgroup descriptors for the corresponding reduction items in
13487 /// in_reduction clauses.
13488 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013489 /// List of captures for clause.
13490 SmallVector<Decl *, 4> ExprCaptures;
13491 /// List of postupdate expressions.
13492 SmallVector<Expr *, 4> ExprPostUpdates;
13493 ReductionData() = delete;
13494 /// Reserves required memory for the reduction data.
13495 ReductionData(unsigned Size) {
13496 Vars.reserve(Size);
13497 Privates.reserve(Size);
13498 LHSs.reserve(Size);
13499 RHSs.reserve(Size);
13500 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013501 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013502 ExprCaptures.reserve(Size);
13503 ExprPostUpdates.reserve(Size);
13504 }
13505 /// Stores reduction item and reduction operation only (required for dependent
13506 /// reduction item).
13507 void push(Expr *Item, Expr *ReductionOp) {
13508 Vars.emplace_back(Item);
13509 Privates.emplace_back(nullptr);
13510 LHSs.emplace_back(nullptr);
13511 RHSs.emplace_back(nullptr);
13512 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013513 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013514 }
13515 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013516 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13517 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013518 Vars.emplace_back(Item);
13519 Privates.emplace_back(Private);
13520 LHSs.emplace_back(LHS);
13521 RHSs.emplace_back(RHS);
13522 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013523 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013524 }
13525};
13526} // namespace
13527
Alexey Bataeve3727102018-04-18 15:57:46 +000013528static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013529 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13530 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13531 const Expr *Length = OASE->getLength();
13532 if (Length == nullptr) {
13533 // For array sections of the form [1:] or [:], we would need to analyze
13534 // the lower bound...
13535 if (OASE->getColonLoc().isValid())
13536 return false;
13537
13538 // This is an array subscript which has implicit length 1!
13539 SingleElement = true;
13540 ArraySizes.push_back(llvm::APSInt::get(1));
13541 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013542 Expr::EvalResult Result;
13543 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013544 return false;
13545
Fangrui Song407659a2018-11-30 23:41:18 +000013546 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013547 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13548 ArraySizes.push_back(ConstantLengthValue);
13549 }
13550
13551 // Get the base of this array section and walk up from there.
13552 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13553
13554 // We require length = 1 for all array sections except the right-most to
13555 // guarantee that the memory region is contiguous and has no holes in it.
13556 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13557 Length = TempOASE->getLength();
13558 if (Length == nullptr) {
13559 // For array sections of the form [1:] or [:], we would need to analyze
13560 // the lower bound...
13561 if (OASE->getColonLoc().isValid())
13562 return false;
13563
13564 // This is an array subscript which has implicit length 1!
13565 ArraySizes.push_back(llvm::APSInt::get(1));
13566 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013567 Expr::EvalResult Result;
13568 if (!Length->EvaluateAsInt(Result, Context))
13569 return false;
13570
13571 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13572 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013573 return false;
13574
13575 ArraySizes.push_back(ConstantLengthValue);
13576 }
13577 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13578 }
13579
13580 // If we have a single element, we don't need to add the implicit lengths.
13581 if (!SingleElement) {
13582 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13583 // Has implicit length 1!
13584 ArraySizes.push_back(llvm::APSInt::get(1));
13585 Base = TempASE->getBase()->IgnoreParenImpCasts();
13586 }
13587 }
13588
13589 // This array section can be privatized as a single value or as a constant
13590 // sized array.
13591 return true;
13592}
13593
Alexey Bataeve3727102018-04-18 15:57:46 +000013594static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013595 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13596 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13597 SourceLocation ColonLoc, SourceLocation EndLoc,
13598 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013599 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013600 DeclarationName DN = ReductionId.getName();
13601 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013602 BinaryOperatorKind BOK = BO_Comma;
13603
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013604 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013605 // OpenMP [2.14.3.6, reduction clause]
13606 // C
13607 // reduction-identifier is either an identifier or one of the following
13608 // operators: +, -, *, &, |, ^, && and ||
13609 // C++
13610 // reduction-identifier is either an id-expression or one of the following
13611 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013612 switch (OOK) {
13613 case OO_Plus:
13614 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013615 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013616 break;
13617 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013618 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013619 break;
13620 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013621 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013622 break;
13623 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013624 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013625 break;
13626 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013627 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013628 break;
13629 case OO_AmpAmp:
13630 BOK = BO_LAnd;
13631 break;
13632 case OO_PipePipe:
13633 BOK = BO_LOr;
13634 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013635 case OO_New:
13636 case OO_Delete:
13637 case OO_Array_New:
13638 case OO_Array_Delete:
13639 case OO_Slash:
13640 case OO_Percent:
13641 case OO_Tilde:
13642 case OO_Exclaim:
13643 case OO_Equal:
13644 case OO_Less:
13645 case OO_Greater:
13646 case OO_LessEqual:
13647 case OO_GreaterEqual:
13648 case OO_PlusEqual:
13649 case OO_MinusEqual:
13650 case OO_StarEqual:
13651 case OO_SlashEqual:
13652 case OO_PercentEqual:
13653 case OO_CaretEqual:
13654 case OO_AmpEqual:
13655 case OO_PipeEqual:
13656 case OO_LessLess:
13657 case OO_GreaterGreater:
13658 case OO_LessLessEqual:
13659 case OO_GreaterGreaterEqual:
13660 case OO_EqualEqual:
13661 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013662 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013663 case OO_PlusPlus:
13664 case OO_MinusMinus:
13665 case OO_Comma:
13666 case OO_ArrowStar:
13667 case OO_Arrow:
13668 case OO_Call:
13669 case OO_Subscript:
13670 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013671 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013672 case NUM_OVERLOADED_OPERATORS:
13673 llvm_unreachable("Unexpected reduction identifier");
13674 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013675 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013676 if (II->isStr("max"))
13677 BOK = BO_GT;
13678 else if (II->isStr("min"))
13679 BOK = BO_LT;
13680 }
13681 break;
13682 }
13683 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013684 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013685 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013686 else
13687 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013688 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013689
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013690 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13691 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013692 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013693 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013694 // OpenMP [2.1, C/C++]
13695 // A list item is a variable or array section, subject to the restrictions
13696 // specified in Section 2.4 on page 42 and in each of the sections
13697 // describing clauses and directives for which a list appears.
13698 // OpenMP [2.14.3.3, Restrictions, p.1]
13699 // A variable that is part of another variable (as an array or
13700 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013701 if (!FirstIter && IR != ER)
13702 ++IR;
13703 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013704 SourceLocation ELoc;
13705 SourceRange ERange;
13706 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013707 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013708 /*AllowArraySection=*/true);
13709 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013710 // Try to find 'declare reduction' corresponding construct before using
13711 // builtin/overloaded operators.
13712 QualType Type = Context.DependentTy;
13713 CXXCastPath BasePath;
13714 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013715 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013716 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013717 Expr *ReductionOp = nullptr;
13718 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013719 (DeclareReductionRef.isUnset() ||
13720 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013721 ReductionOp = DeclareReductionRef.get();
13722 // It will be analyzed later.
13723 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013724 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013725 ValueDecl *D = Res.first;
13726 if (!D)
13727 continue;
13728
Alexey Bataev88202be2017-07-27 13:20:36 +000013729 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013730 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013731 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13732 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013733 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013734 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013735 } else if (OASE) {
13736 QualType BaseType =
13737 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13738 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013739 Type = ATy->getElementType();
13740 else
13741 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013742 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013743 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013744 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013745 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013746 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013747
Alexey Bataevc5e02582014-06-16 07:08:35 +000013748 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13749 // A variable that appears in a private clause must not have an incomplete
13750 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013751 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013752 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013753 continue;
13754 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013755 // A list item that appears in a reduction clause must not be
13756 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013757 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13758 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013759 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013760
13761 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013762 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13763 // If a list-item is a reference type then it must bind to the same object
13764 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013765 if (!ASE && !OASE) {
13766 if (VD) {
13767 VarDecl *VDDef = VD->getDefinition();
13768 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13769 DSARefChecker Check(Stack);
13770 if (Check.Visit(VDDef->getInit())) {
13771 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13772 << getOpenMPClauseName(ClauseKind) << ERange;
13773 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13774 continue;
13775 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013776 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013777 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013778
Alexey Bataevbc529672018-09-28 19:33:14 +000013779 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13780 // in a Construct]
13781 // Variables with the predetermined data-sharing attributes may not be
13782 // listed in data-sharing attributes clauses, except for the cases
13783 // listed below. For these exceptions only, listing a predetermined
13784 // variable in a data-sharing attribute clause is allowed and overrides
13785 // the variable's predetermined data-sharing attributes.
13786 // OpenMP [2.14.3.6, Restrictions, p.3]
13787 // Any number of reduction clauses can be specified on the directive,
13788 // but a list item can appear only once in the reduction clauses for that
13789 // directive.
13790 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13791 if (DVar.CKind == OMPC_reduction) {
13792 S.Diag(ELoc, diag::err_omp_once_referenced)
13793 << getOpenMPClauseName(ClauseKind);
13794 if (DVar.RefExpr)
13795 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13796 continue;
13797 }
13798 if (DVar.CKind != OMPC_unknown) {
13799 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13800 << getOpenMPClauseName(DVar.CKind)
13801 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013802 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013803 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013804 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013805
13806 // OpenMP [2.14.3.6, Restrictions, p.1]
13807 // A list item that appears in a reduction clause of a worksharing
13808 // construct must be shared in the parallel regions to which any of the
13809 // worksharing regions arising from the worksharing construct bind.
13810 if (isOpenMPWorksharingDirective(CurrDir) &&
13811 !isOpenMPParallelDirective(CurrDir) &&
13812 !isOpenMPTeamsDirective(CurrDir)) {
13813 DVar = Stack->getImplicitDSA(D, true);
13814 if (DVar.CKind != OMPC_shared) {
13815 S.Diag(ELoc, diag::err_omp_required_access)
13816 << getOpenMPClauseName(OMPC_reduction)
13817 << getOpenMPClauseName(OMPC_shared);
13818 reportOriginalDsa(S, Stack, D, DVar);
13819 continue;
13820 }
13821 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013822 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013823
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013824 // Try to find 'declare reduction' corresponding construct before using
13825 // builtin/overloaded operators.
13826 CXXCastPath BasePath;
13827 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013828 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013829 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13830 if (DeclareReductionRef.isInvalid())
13831 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013832 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013833 (DeclareReductionRef.isUnset() ||
13834 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013835 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013836 continue;
13837 }
13838 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13839 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013840 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013841 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013842 << Type << ReductionIdRange;
13843 continue;
13844 }
13845
13846 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13847 // The type of a list item that appears in a reduction clause must be valid
13848 // for the reduction-identifier. For a max or min reduction in C, the type
13849 // of the list item must be an allowed arithmetic data type: char, int,
13850 // float, double, or _Bool, possibly modified with long, short, signed, or
13851 // unsigned. For a max or min reduction in C++, the type of the list item
13852 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13853 // double, or bool, possibly modified with long, short, signed, or unsigned.
13854 if (DeclareReductionRef.isUnset()) {
13855 if ((BOK == BO_GT || BOK == BO_LT) &&
13856 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013857 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13858 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013859 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013860 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013861 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13862 VarDecl::DeclarationOnly;
13863 S.Diag(D->getLocation(),
13864 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013865 << D;
13866 }
13867 continue;
13868 }
13869 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013870 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013871 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13872 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013873 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013874 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13875 VarDecl::DeclarationOnly;
13876 S.Diag(D->getLocation(),
13877 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013878 << D;
13879 }
13880 continue;
13881 }
13882 }
13883
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013884 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013885 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13886 D->hasAttrs() ? &D->getAttrs() : nullptr);
13887 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13888 D->hasAttrs() ? &D->getAttrs() : nullptr);
13889 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013890
13891 // Try if we can determine constant lengths for all array sections and avoid
13892 // the VLA.
13893 bool ConstantLengthOASE = false;
13894 if (OASE) {
13895 bool SingleElement;
13896 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013897 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013898 Context, OASE, SingleElement, ArraySizes);
13899
13900 // If we don't have a single element, we must emit a constant array type.
13901 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013902 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013903 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13904 ArrayType::Normal,
13905 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013906 }
13907 }
13908
13909 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013910 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013911 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013912 if (!Context.getTargetInfo().isVLASupported()) {
13913 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13914 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13915 S.Diag(ELoc, diag::note_vla_unsupported);
13916 } else {
13917 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13918 S.targetDiag(ELoc, diag::note_vla_unsupported);
13919 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013920 continue;
13921 }
David Majnemer9d168222016-08-05 17:44:54 +000013922 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013923 // Create pseudo array type for private copy. The size for this array will
13924 // be generated during codegen.
13925 // For array subscripts or single variables Private Ty is the same as Type
13926 // (type of the variable or single array element).
13927 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013928 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013929 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013930 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013931 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013932 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013933 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013934 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013935 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013936 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013937 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13938 D->hasAttrs() ? &D->getAttrs() : nullptr,
13939 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013940 // Add initializer for private variable.
13941 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013942 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13943 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013944 if (DeclareReductionRef.isUsable()) {
13945 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13946 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13947 if (DRD->getInitializer()) {
13948 Init = DRDRef;
13949 RHSVD->setInit(DRDRef);
13950 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013951 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013952 } else {
13953 switch (BOK) {
13954 case BO_Add:
13955 case BO_Xor:
13956 case BO_Or:
13957 case BO_LOr:
13958 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13959 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013960 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013961 break;
13962 case BO_Mul:
13963 case BO_LAnd:
13964 if (Type->isScalarType() || Type->isAnyComplexType()) {
13965 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013966 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013967 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013968 break;
13969 case BO_And: {
13970 // '&' reduction op - initializer is '~0'.
13971 QualType OrigType = Type;
13972 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13973 Type = ComplexTy->getElementType();
13974 if (Type->isRealFloatingType()) {
13975 llvm::APFloat InitValue =
13976 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13977 /*isIEEE=*/true);
13978 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13979 Type, ELoc);
13980 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013981 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013982 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13983 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13984 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13985 }
13986 if (Init && OrigType->isAnyComplexType()) {
13987 // Init = 0xFFFF + 0xFFFFi;
13988 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013989 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013990 }
13991 Type = OrigType;
13992 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013993 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013994 case BO_LT:
13995 case BO_GT: {
13996 // 'min' reduction op - initializer is 'Largest representable number in
13997 // the reduction list item type'.
13998 // 'max' reduction op - initializer is 'Least representable number in
13999 // the reduction list item type'.
14000 if (Type->isIntegerType() || Type->isPointerType()) {
14001 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014002 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014003 QualType IntTy =
14004 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
14005 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014006 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
14007 : llvm::APInt::getMinValue(Size)
14008 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
14009 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014010 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14011 if (Type->isPointerType()) {
14012 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014013 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000014014 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014015 if (CastExpr.isInvalid())
14016 continue;
14017 Init = CastExpr.get();
14018 }
14019 } else if (Type->isRealFloatingType()) {
14020 llvm::APFloat InitValue = llvm::APFloat::getLargest(
14021 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
14022 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14023 Type, ELoc);
14024 }
14025 break;
14026 }
14027 case BO_PtrMemD:
14028 case BO_PtrMemI:
14029 case BO_MulAssign:
14030 case BO_Div:
14031 case BO_Rem:
14032 case BO_Sub:
14033 case BO_Shl:
14034 case BO_Shr:
14035 case BO_LE:
14036 case BO_GE:
14037 case BO_EQ:
14038 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000014039 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014040 case BO_AndAssign:
14041 case BO_XorAssign:
14042 case BO_OrAssign:
14043 case BO_Assign:
14044 case BO_AddAssign:
14045 case BO_SubAssign:
14046 case BO_DivAssign:
14047 case BO_RemAssign:
14048 case BO_ShlAssign:
14049 case BO_ShrAssign:
14050 case BO_Comma:
14051 llvm_unreachable("Unexpected reduction operation");
14052 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014053 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014054 if (Init && DeclareReductionRef.isUnset())
14055 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
14056 else if (!Init)
14057 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014058 if (RHSVD->isInvalidDecl())
14059 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000014060 if (!RHSVD->hasInit() &&
14061 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014062 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
14063 << Type << ReductionIdRange;
14064 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14065 VarDecl::DeclarationOnly;
14066 S.Diag(D->getLocation(),
14067 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000014068 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014069 continue;
14070 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014071 // Store initializer for single element in private copy. Will be used during
14072 // codegen.
14073 PrivateVD->setInit(RHSVD->getInit());
14074 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000014075 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014076 ExprResult ReductionOp;
14077 if (DeclareReductionRef.isUsable()) {
14078 QualType RedTy = DeclareReductionRef.get()->getType();
14079 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014080 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
14081 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014082 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014083 LHS = S.DefaultLvalueConversion(LHS.get());
14084 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014085 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14086 CK_UncheckedDerivedToBase, LHS.get(),
14087 &BasePath, LHS.get()->getValueKind());
14088 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14089 CK_UncheckedDerivedToBase, RHS.get(),
14090 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014091 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014092 FunctionProtoType::ExtProtoInfo EPI;
14093 QualType Params[] = {PtrRedTy, PtrRedTy};
14094 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
14095 auto *OVE = new (Context) OpaqueValueExpr(
14096 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014097 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014098 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000014099 ReductionOp =
14100 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014101 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014102 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014103 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014104 if (ReductionOp.isUsable()) {
14105 if (BOK != BO_LT && BOK != BO_GT) {
14106 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014107 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014108 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014109 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000014110 auto *ConditionalOp = new (Context)
14111 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
14112 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014113 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014114 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014115 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014116 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014117 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014118 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
14119 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014120 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014121 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014122 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000014123 }
14124
Alexey Bataevfa312f32017-07-21 18:48:21 +000014125 // OpenMP [2.15.4.6, Restrictions, p.2]
14126 // A list item that appears in an in_reduction clause of a task construct
14127 // must appear in a task_reduction clause of a construct associated with a
14128 // taskgroup region that includes the participating task in its taskgroup
14129 // set. The construct associated with the innermost region that meets this
14130 // condition must specify the same reduction-identifier as the in_reduction
14131 // clause.
14132 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000014133 SourceRange ParentSR;
14134 BinaryOperatorKind ParentBOK;
14135 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000014136 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000014137 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014138 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
14139 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014140 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014141 Stack->getTopMostTaskgroupReductionData(
14142 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014143 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
14144 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
14145 if (!IsParentBOK && !IsParentReductionOp) {
14146 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
14147 continue;
14148 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000014149 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
14150 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
14151 IsParentReductionOp) {
14152 bool EmitError = true;
14153 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
14154 llvm::FoldingSetNodeID RedId, ParentRedId;
14155 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
14156 DeclareReductionRef.get()->Profile(RedId, Context,
14157 /*Canonical=*/true);
14158 EmitError = RedId != ParentRedId;
14159 }
14160 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014161 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000014162 diag::err_omp_reduction_identifier_mismatch)
14163 << ReductionIdRange << RefExpr->getSourceRange();
14164 S.Diag(ParentSR.getBegin(),
14165 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000014166 << ParentSR
14167 << (IsParentBOK ? ParentBOKDSA.RefExpr
14168 : ParentReductionOpDSA.RefExpr)
14169 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000014170 continue;
14171 }
14172 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014173 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
14174 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000014175 }
14176
Alexey Bataev60da77e2016-02-29 05:54:20 +000014177 DeclRefExpr *Ref = nullptr;
14178 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014179 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014180 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014181 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000014182 VarsExpr =
14183 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
14184 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000014185 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014186 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014187 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014188 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014189 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014190 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014191 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014192 if (!RefRes.isUsable())
14193 continue;
14194 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014195 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14196 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014197 if (!PostUpdateRes.isUsable())
14198 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014199 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14200 Stack->getCurrentDirective() == OMPD_taskgroup) {
14201 S.Diag(RefExpr->getExprLoc(),
14202 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014203 << RefExpr->getSourceRange();
14204 continue;
14205 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014206 RD.ExprPostUpdates.emplace_back(
14207 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014208 }
14209 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014210 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014211 // All reduction items are still marked as reduction (to do not increase
14212 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014213 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014214 if (CurrDir == OMPD_taskgroup) {
14215 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014216 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14217 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014218 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014219 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014220 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014221 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14222 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014223 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014224 return RD.Vars.empty();
14225}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014226
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014227OMPClause *Sema::ActOnOpenMPReductionClause(
14228 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14229 SourceLocation ColonLoc, SourceLocation EndLoc,
14230 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14231 ArrayRef<Expr *> UnresolvedReductions) {
14232 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014233 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014234 StartLoc, LParenLoc, ColonLoc, EndLoc,
14235 ReductionIdScopeSpec, ReductionId,
14236 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014237 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014238
Alexey Bataevc5e02582014-06-16 07:08:35 +000014239 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014240 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14241 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14242 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14243 buildPreInits(Context, RD.ExprCaptures),
14244 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014245}
14246
Alexey Bataev169d96a2017-07-18 20:17:46 +000014247OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14248 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14249 SourceLocation ColonLoc, SourceLocation EndLoc,
14250 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14251 ArrayRef<Expr *> UnresolvedReductions) {
14252 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014253 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14254 StartLoc, LParenLoc, ColonLoc, EndLoc,
14255 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014256 UnresolvedReductions, RD))
14257 return nullptr;
14258
14259 return OMPTaskReductionClause::Create(
14260 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14261 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14262 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14263 buildPreInits(Context, RD.ExprCaptures),
14264 buildPostUpdate(*this, RD.ExprPostUpdates));
14265}
14266
Alexey Bataevfa312f32017-07-21 18:48:21 +000014267OMPClause *Sema::ActOnOpenMPInReductionClause(
14268 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14269 SourceLocation ColonLoc, SourceLocation EndLoc,
14270 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14271 ArrayRef<Expr *> UnresolvedReductions) {
14272 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014273 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014274 StartLoc, LParenLoc, ColonLoc, EndLoc,
14275 ReductionIdScopeSpec, ReductionId,
14276 UnresolvedReductions, RD))
14277 return nullptr;
14278
14279 return OMPInReductionClause::Create(
14280 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14281 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014282 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014283 buildPreInits(Context, RD.ExprCaptures),
14284 buildPostUpdate(*this, RD.ExprPostUpdates));
14285}
14286
Alexey Bataevecba70f2016-04-12 11:02:11 +000014287bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14288 SourceLocation LinLoc) {
14289 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14290 LinKind == OMPC_LINEAR_unknown) {
14291 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14292 return true;
14293 }
14294 return false;
14295}
14296
Alexey Bataeve3727102018-04-18 15:57:46 +000014297bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014298 OpenMPLinearClauseKind LinKind,
14299 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014300 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014301 // A variable must not have an incomplete type or a reference type.
14302 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14303 return true;
14304 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14305 !Type->isReferenceType()) {
14306 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14307 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14308 return true;
14309 }
14310 Type = Type.getNonReferenceType();
14311
Joel E. Dennybae586f2019-01-04 22:12:13 +000014312 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14313 // A variable that is privatized must not have a const-qualified type
14314 // unless it is of class type with a mutable member. This restriction does
14315 // not apply to the firstprivate clause.
14316 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014317 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014318
14319 // A list item must be of integral or pointer type.
14320 Type = Type.getUnqualifiedType().getCanonicalType();
14321 const auto *Ty = Type.getTypePtrOrNull();
14322 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
14323 !Ty->isPointerType())) {
14324 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14325 if (D) {
14326 bool IsDecl =
14327 !VD ||
14328 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14329 Diag(D->getLocation(),
14330 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14331 << D;
14332 }
14333 return true;
14334 }
14335 return false;
14336}
14337
Alexey Bataev182227b2015-08-20 10:54:39 +000014338OMPClause *Sema::ActOnOpenMPLinearClause(
14339 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14340 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14341 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014342 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014343 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014344 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014345 SmallVector<Decl *, 4> ExprCaptures;
14346 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014347 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014348 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014349 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014350 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014351 SourceLocation ELoc;
14352 SourceRange ERange;
14353 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014354 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014355 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014356 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014357 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014358 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014359 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014360 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014361 ValueDecl *D = Res.first;
14362 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014363 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014364
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014365 QualType Type = D->getType();
14366 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014367
14368 // OpenMP [2.14.3.7, linear clause]
14369 // A list-item cannot appear in more than one linear clause.
14370 // A list-item that appears in a linear clause cannot appear in any
14371 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014372 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014373 if (DVar.RefExpr) {
14374 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14375 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014376 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014377 continue;
14378 }
14379
Alexey Bataevecba70f2016-04-12 11:02:11 +000014380 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014381 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014382 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014383
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014384 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014385 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014386 buildVarDecl(*this, ELoc, Type, D->getName(),
14387 D->hasAttrs() ? &D->getAttrs() : nullptr,
14388 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014389 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014390 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014391 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014392 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014393 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014394 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014395 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014396 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014397 ExprCaptures.push_back(Ref->getDecl());
14398 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14399 ExprResult RefRes = DefaultLvalueConversion(Ref);
14400 if (!RefRes.isUsable())
14401 continue;
14402 ExprResult PostUpdateRes =
14403 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14404 SimpleRefExpr, RefRes.get());
14405 if (!PostUpdateRes.isUsable())
14406 continue;
14407 ExprPostUpdates.push_back(
14408 IgnoredValueConversions(PostUpdateRes.get()).get());
14409 }
14410 }
14411 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014412 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014413 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014414 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014415 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014416 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014417 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014418 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014419
14420 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014421 Vars.push_back((VD || CurContext->isDependentContext())
14422 ? RefExpr->IgnoreParens()
14423 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014424 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014425 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014426 }
14427
14428 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014429 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014430
14431 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014432 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014433 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14434 !Step->isInstantiationDependent() &&
14435 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014436 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014437 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014438 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014439 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014440 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014441
Alexander Musman3276a272015-03-21 10:12:56 +000014442 // Build var to save the step value.
14443 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014444 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014445 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014446 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014447 ExprResult CalcStep =
14448 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014449 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014450
Alexander Musman8dba6642014-04-22 13:09:42 +000014451 // Warn about zero linear step (it would be probably better specified as
14452 // making corresponding variables 'const').
14453 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014454 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14455 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014456 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14457 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014458 if (!IsConstant && CalcStep.isUsable()) {
14459 // Calculate the step beforehand instead of doing this on each iteration.
14460 // (This is not used if the number of iterations may be kfold-ed).
14461 CalcStepExpr = CalcStep.get();
14462 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014463 }
14464
Alexey Bataev182227b2015-08-20 10:54:39 +000014465 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14466 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014467 StepExpr, CalcStepExpr,
14468 buildPreInits(Context, ExprCaptures),
14469 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014470}
14471
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014472static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14473 Expr *NumIterations, Sema &SemaRef,
14474 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014475 // Walk the vars and build update/final expressions for the CodeGen.
14476 SmallVector<Expr *, 8> Updates;
14477 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014478 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014479 Expr *Step = Clause.getStep();
14480 Expr *CalcStep = Clause.getCalcStep();
14481 // OpenMP [2.14.3.7, linear clause]
14482 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014483 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014484 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014485 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014486 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14487 bool HasErrors = false;
14488 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014489 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014490 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14491 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014492 SourceLocation ELoc;
14493 SourceRange ERange;
14494 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014495 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014496 ValueDecl *D = Res.first;
14497 if (Res.second || !D) {
14498 Updates.push_back(nullptr);
14499 Finals.push_back(nullptr);
14500 HasErrors = true;
14501 continue;
14502 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014503 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014504 // OpenMP [2.15.11, distribute simd Construct]
14505 // A list item may not appear in a linear clause, unless it is the loop
14506 // iteration variable.
14507 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14508 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14509 SemaRef.Diag(ELoc,
14510 diag::err_omp_linear_distribute_var_non_loop_iteration);
14511 Updates.push_back(nullptr);
14512 Finals.push_back(nullptr);
14513 HasErrors = true;
14514 continue;
14515 }
Alexander Musman3276a272015-03-21 10:12:56 +000014516 Expr *InitExpr = *CurInit;
14517
14518 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014519 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014520 Expr *CapturedRef;
14521 if (LinKind == OMPC_LINEAR_uval)
14522 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14523 else
14524 CapturedRef =
14525 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14526 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14527 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014528
14529 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014530 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014531 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014532 Update = buildCounterUpdate(
14533 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14534 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014535 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014536 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014537 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014538 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014539
14540 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014541 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014542 if (!Info.first)
14543 Final =
14544 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014545 InitExpr, NumIterations, Step, /*Subtract=*/false,
14546 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014547 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014548 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014549 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014550 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014551
Alexander Musman3276a272015-03-21 10:12:56 +000014552 if (!Update.isUsable() || !Final.isUsable()) {
14553 Updates.push_back(nullptr);
14554 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014555 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014556 HasErrors = true;
14557 } else {
14558 Updates.push_back(Update.get());
14559 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014560 if (!Info.first)
14561 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014562 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014563 ++CurInit;
14564 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014565 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014566 if (Expr *S = Clause.getStep())
14567 UsedExprs.push_back(S);
14568 // Fill the remaining part with the nullptr.
14569 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014570 Clause.setUpdates(Updates);
14571 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014572 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014573 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014574}
14575
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014576OMPClause *Sema::ActOnOpenMPAlignedClause(
14577 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14578 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014579 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014580 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014581 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14582 SourceLocation ELoc;
14583 SourceRange ERange;
14584 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014585 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014586 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014587 // It will be analyzed later.
14588 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014589 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014590 ValueDecl *D = Res.first;
14591 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014592 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014593
Alexey Bataev1efd1662016-03-29 10:59:56 +000014594 QualType QType = D->getType();
14595 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014596
14597 // OpenMP [2.8.1, simd construct, Restrictions]
14598 // The type of list items appearing in the aligned clause must be
14599 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014600 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014601 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014602 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014603 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014604 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014605 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014606 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014607 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014608 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014609 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014610 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014611 continue;
14612 }
14613
14614 // OpenMP [2.8.1, simd construct, Restrictions]
14615 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014616 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevb6e70842019-12-16 15:54:17 -050014617 Diag(ELoc, diag::err_omp_used_in_clause_twice)
14618 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014619 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14620 << getOpenMPClauseName(OMPC_aligned);
14621 continue;
14622 }
14623
Alexey Bataev1efd1662016-03-29 10:59:56 +000014624 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014625 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014626 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14627 Vars.push_back(DefaultFunctionArrayConversion(
14628 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14629 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014630 }
14631
14632 // OpenMP [2.8.1, simd construct, Description]
14633 // The parameter of the aligned clause, alignment, must be a constant
14634 // positive integer expression.
14635 // If no optional parameter is specified, implementation-defined default
14636 // alignments for SIMD instructions on the target platforms are assumed.
14637 if (Alignment != nullptr) {
14638 ExprResult AlignResult =
14639 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14640 if (AlignResult.isInvalid())
14641 return nullptr;
14642 Alignment = AlignResult.get();
14643 }
14644 if (Vars.empty())
14645 return nullptr;
14646
14647 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14648 EndLoc, Vars, Alignment);
14649}
14650
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014651OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14652 SourceLocation StartLoc,
14653 SourceLocation LParenLoc,
14654 SourceLocation EndLoc) {
14655 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014656 SmallVector<Expr *, 8> SrcExprs;
14657 SmallVector<Expr *, 8> DstExprs;
14658 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014659 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014660 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14661 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014662 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014663 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014664 SrcExprs.push_back(nullptr);
14665 DstExprs.push_back(nullptr);
14666 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014667 continue;
14668 }
14669
Alexey Bataeved09d242014-05-28 05:53:51 +000014670 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014671 // OpenMP [2.1, C/C++]
14672 // A list item is a variable name.
14673 // OpenMP [2.14.4.1, Restrictions, p.1]
14674 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014675 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014676 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014677 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14678 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014679 continue;
14680 }
14681
14682 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014683 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014684
14685 QualType Type = VD->getType();
14686 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14687 // It will be analyzed later.
14688 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014689 SrcExprs.push_back(nullptr);
14690 DstExprs.push_back(nullptr);
14691 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014692 continue;
14693 }
14694
14695 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14696 // A list item that appears in a copyin clause must be threadprivate.
14697 if (!DSAStack->isThreadPrivate(VD)) {
14698 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014699 << getOpenMPClauseName(OMPC_copyin)
14700 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014701 continue;
14702 }
14703
14704 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14705 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014706 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014707 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014708 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14709 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014710 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014711 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014712 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014713 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014714 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014715 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014716 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014717 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014718 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014719 // For arrays generate assignment operation for single element and replace
14720 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014721 ExprResult AssignmentOp =
14722 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14723 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014724 if (AssignmentOp.isInvalid())
14725 continue;
14726 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014727 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014728 if (AssignmentOp.isInvalid())
14729 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014730
14731 DSAStack->addDSA(VD, DE, OMPC_copyin);
14732 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014733 SrcExprs.push_back(PseudoSrcExpr);
14734 DstExprs.push_back(PseudoDstExpr);
14735 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014736 }
14737
Alexey Bataeved09d242014-05-28 05:53:51 +000014738 if (Vars.empty())
14739 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014740
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014741 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14742 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014743}
14744
Alexey Bataevbae9a792014-06-27 10:37:06 +000014745OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14746 SourceLocation StartLoc,
14747 SourceLocation LParenLoc,
14748 SourceLocation EndLoc) {
14749 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014750 SmallVector<Expr *, 8> SrcExprs;
14751 SmallVector<Expr *, 8> DstExprs;
14752 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014753 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014754 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14755 SourceLocation ELoc;
14756 SourceRange ERange;
14757 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014758 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014759 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014760 // It will be analyzed later.
14761 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014762 SrcExprs.push_back(nullptr);
14763 DstExprs.push_back(nullptr);
14764 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014765 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014766 ValueDecl *D = Res.first;
14767 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014768 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014769
Alexey Bataeve122da12016-03-17 10:50:17 +000014770 QualType Type = D->getType();
14771 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014772
14773 // OpenMP [2.14.4.2, Restrictions, p.2]
14774 // A list item that appears in a copyprivate clause may not appear in a
14775 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014776 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014777 DSAStackTy::DSAVarData DVar =
14778 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014779 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14780 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014781 Diag(ELoc, diag::err_omp_wrong_dsa)
14782 << getOpenMPClauseName(DVar.CKind)
14783 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014784 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014785 continue;
14786 }
14787
14788 // OpenMP [2.11.4.2, Restrictions, p.1]
14789 // All list items that appear in a copyprivate clause must be either
14790 // threadprivate or private in the enclosing context.
14791 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014792 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014793 if (DVar.CKind == OMPC_shared) {
14794 Diag(ELoc, diag::err_omp_required_access)
14795 << getOpenMPClauseName(OMPC_copyprivate)
14796 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014797 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014798 continue;
14799 }
14800 }
14801 }
14802
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014803 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014804 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014805 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014806 << getOpenMPClauseName(OMPC_copyprivate) << Type
14807 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014808 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014809 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014810 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014811 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014812 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014813 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014814 continue;
14815 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014816
Alexey Bataevbae9a792014-06-27 10:37:06 +000014817 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14818 // A variable of class type (or array thereof) that appears in a
14819 // copyin clause requires an accessible, unambiguous copy assignment
14820 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014821 Type = Context.getBaseElementType(Type.getNonReferenceType())
14822 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014823 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014824 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014825 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014826 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14827 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014828 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014829 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014830 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14831 ExprResult AssignmentOp = BuildBinOp(
14832 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014833 if (AssignmentOp.isInvalid())
14834 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014835 AssignmentOp =
14836 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014837 if (AssignmentOp.isInvalid())
14838 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014839
14840 // No need to mark vars as copyprivate, they are already threadprivate or
14841 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014842 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014843 Vars.push_back(
14844 VD ? RefExpr->IgnoreParens()
14845 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014846 SrcExprs.push_back(PseudoSrcExpr);
14847 DstExprs.push_back(PseudoDstExpr);
14848 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014849 }
14850
14851 if (Vars.empty())
14852 return nullptr;
14853
Alexey Bataeva63048e2015-03-23 06:18:07 +000014854 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14855 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014856}
14857
Alexey Bataev6125da92014-07-21 11:26:11 +000014858OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14859 SourceLocation StartLoc,
14860 SourceLocation LParenLoc,
14861 SourceLocation EndLoc) {
14862 if (VarList.empty())
14863 return nullptr;
14864
14865 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14866}
Alexey Bataevdea47612014-07-23 07:46:59 +000014867
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014868OMPClause *
14869Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14870 SourceLocation DepLoc, SourceLocation ColonLoc,
14871 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14872 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014873 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014874 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014875 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014876 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014877 return nullptr;
14878 }
14879 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014880 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14881 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014882 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014883 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014884 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14885 /*Last=*/OMPC_DEPEND_unknown, Except)
14886 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014887 return nullptr;
14888 }
14889 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014890 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014891 llvm::APSInt DepCounter(/*BitWidth=*/32);
14892 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014893 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14894 if (const Expr *OrderedCountExpr =
14895 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014896 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14897 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014898 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014899 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014900 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014901 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14902 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14903 // It will be analyzed later.
14904 Vars.push_back(RefExpr);
14905 continue;
14906 }
14907
14908 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014909 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014910 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014911 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014912 DepCounter >= TotalDepCount) {
14913 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14914 continue;
14915 }
14916 ++DepCounter;
14917 // OpenMP [2.13.9, Summary]
14918 // depend(dependence-type : vec), where dependence-type is:
14919 // 'sink' and where vec is the iteration vector, which has the form:
14920 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14921 // where n is the value specified by the ordered clause in the loop
14922 // directive, xi denotes the loop iteration variable of the i-th nested
14923 // loop associated with the loop directive, and di is a constant
14924 // non-negative integer.
14925 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014926 // It will be analyzed later.
14927 Vars.push_back(RefExpr);
14928 continue;
14929 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014930 SimpleExpr = SimpleExpr->IgnoreImplicit();
14931 OverloadedOperatorKind OOK = OO_None;
14932 SourceLocation OOLoc;
14933 Expr *LHS = SimpleExpr;
14934 Expr *RHS = nullptr;
14935 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14936 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14937 OOLoc = BO->getOperatorLoc();
14938 LHS = BO->getLHS()->IgnoreParenImpCasts();
14939 RHS = BO->getRHS()->IgnoreParenImpCasts();
14940 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14941 OOK = OCE->getOperator();
14942 OOLoc = OCE->getOperatorLoc();
14943 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14944 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14945 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14946 OOK = MCE->getMethodDecl()
14947 ->getNameInfo()
14948 .getName()
14949 .getCXXOverloadedOperator();
14950 OOLoc = MCE->getCallee()->getExprLoc();
14951 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14952 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014953 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014954 SourceLocation ELoc;
14955 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014956 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014957 if (Res.second) {
14958 // It will be analyzed later.
14959 Vars.push_back(RefExpr);
14960 }
14961 ValueDecl *D = Res.first;
14962 if (!D)
14963 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014964
Alexey Bataev17daedf2018-02-15 22:42:57 +000014965 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14966 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14967 continue;
14968 }
14969 if (RHS) {
14970 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14971 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14972 if (RHSRes.isInvalid())
14973 continue;
14974 }
14975 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014976 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014977 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014978 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014979 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014980 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014981 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14982 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014983 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014984 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014985 continue;
14986 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014987 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014988 } else {
14989 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14990 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14991 (ASE &&
14992 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14993 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14994 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14995 << RefExpr->getSourceRange();
14996 continue;
14997 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014998
14999 ExprResult Res;
15000 {
15001 Sema::TentativeAnalysisScope Trap(*this);
15002 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
15003 RefExpr->IgnoreParenImpCasts());
15004 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015005 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
15006 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15007 << RefExpr->getSourceRange();
15008 continue;
15009 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015010 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015011 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015012 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015013
15014 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
15015 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015016 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015017 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
15018 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
15019 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
15020 }
15021 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
15022 Vars.empty())
15023 return nullptr;
15024
Alexey Bataev8b427062016-05-25 12:36:08 +000015025 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000015026 DepKind, DepLoc, ColonLoc, Vars,
15027 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000015028 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
15029 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000015030 DSAStack->addDoacrossDependClause(C, OpsOffs);
15031 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015032}
Michael Wonge710d542015-08-07 16:16:36 +000015033
15034OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
15035 SourceLocation LParenLoc,
15036 SourceLocation EndLoc) {
15037 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015038 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000015039
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015040 // OpenMP [2.9.1, Restrictions]
15041 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015042 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000015043 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015044 return nullptr;
15045
Alexey Bataev931e19b2017-10-02 16:32:39 +000015046 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015047 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050015048 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000015049 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015050 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015051 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015052 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15053 HelperValStmt = buildPreInits(Context, Captures);
15054 }
15055
Alexey Bataev8451efa2018-01-15 19:06:12 +000015056 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
15057 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000015058}
Kelvin Li0bff7af2015-11-23 05:32:03 +000015059
Alexey Bataeve3727102018-04-18 15:57:46 +000015060static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000015061 DSAStackTy *Stack, QualType QTy,
15062 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000015063 NamedDecl *ND;
15064 if (QTy->isIncompleteType(&ND)) {
15065 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
15066 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015067 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000015068 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
Jonas Hahnfeld071dca22019-12-07 13:31:46 +010015069 !QTy.isTriviallyCopyableType(SemaRef.Context))
Alexey Bataev95c23e72018-02-27 21:31:11 +000015070 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015071 return true;
15072}
15073
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000015074/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015075/// (array section or array subscript) does NOT specify the whole size of the
15076/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015077static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015078 const Expr *E,
15079 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015080 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015081
15082 // If this is an array subscript, it refers to the whole size if the size of
15083 // the dimension is constant and equals 1. Also, an array section assumes the
15084 // format of an array subscript if no colon is used.
15085 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015086 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015087 return ATy->getSize().getSExtValue() != 1;
15088 // Size can't be evaluated statically.
15089 return false;
15090 }
15091
15092 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015093 const Expr *LowerBound = OASE->getLowerBound();
15094 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015095
15096 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000015097 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015098 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000015099 Expr::EvalResult Result;
15100 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015101 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000015102
15103 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015104 if (ConstLowerBound.getSExtValue())
15105 return true;
15106 }
15107
15108 // If we don't have a length we covering the whole dimension.
15109 if (!Length)
15110 return false;
15111
15112 // If the base is a pointer, we don't have a way to get the size of the
15113 // pointee.
15114 if (BaseQTy->isPointerType())
15115 return false;
15116
15117 // We can only check if the length is the same as the size of the dimension
15118 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000015119 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015120 if (!CATy)
15121 return false;
15122
Fangrui Song407659a2018-11-30 23:41:18 +000015123 Expr::EvalResult Result;
15124 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015125 return false; // Can't get the integer value as a constant.
15126
Fangrui Song407659a2018-11-30 23:41:18 +000015127 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015128 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
15129}
15130
15131// Return true if it can be proven that the provided array expression (array
15132// section or array subscript) does NOT specify a single element of the array
15133// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015134static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000015135 const Expr *E,
15136 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015137 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015138
15139 // An array subscript always refer to a single element. Also, an array section
15140 // assumes the format of an array subscript if no colon is used.
15141 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
15142 return false;
15143
15144 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015145 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015146
15147 // If we don't have a length we have to check if the array has unitary size
15148 // for this dimension. Also, we should always expect a length if the base type
15149 // is pointer.
15150 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015151 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015152 return ATy->getSize().getSExtValue() != 1;
15153 // We cannot assume anything.
15154 return false;
15155 }
15156
15157 // Check if the length evaluates to 1.
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 ConstLength.getSExtValue() != 1;
15164}
15165
Samuel Antao661c0902016-05-26 17:39:58 +000015166// Return the expression of the base of the mappable expression or null if it
15167// cannot be determined and do all the necessary checks to see if the expression
15168// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000015169// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015170static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000015171 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000015172 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015173 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015174 SourceLocation ELoc = E->getExprLoc();
15175 SourceRange ERange = E->getSourceRange();
15176
15177 // The base of elements of list in a map clause have to be either:
15178 // - a reference to variable or field.
15179 // - a member expression.
15180 // - an array expression.
15181 //
15182 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
15183 // reference to 'r'.
15184 //
15185 // If we have:
15186 //
15187 // struct SS {
15188 // Bla S;
15189 // foo() {
15190 // #pragma omp target map (S.Arr[:12]);
15191 // }
15192 // }
15193 //
15194 // We want to retrieve the member expression 'this->S';
15195
Alexey Bataeve3727102018-04-18 15:57:46 +000015196 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015197
Samuel Antao5de996e2016-01-22 20:21:36 +000015198 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15199 // If a list item is an array section, it must specify contiguous storage.
15200 //
15201 // For this restriction it is sufficient that we make sure only references
15202 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015203 // exist except in the rightmost expression (unless they cover the whole
15204 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015205 //
15206 // r.ArrS[3:5].Arr[6:7]
15207 //
15208 // r.ArrS[3:5].x
15209 //
15210 // but these would be valid:
15211 // r.ArrS[3].Arr[6:7]
15212 //
15213 // r.ArrS[3].x
15214
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015215 bool AllowUnitySizeArraySection = true;
15216 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015217
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015218 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015219 E = E->IgnoreParenImpCasts();
15220
15221 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15222 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015223 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015224
15225 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015226
15227 // If we got a reference to a declaration, we should not expect any array
15228 // section before that.
15229 AllowUnitySizeArraySection = false;
15230 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015231
15232 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015233 CurComponents.emplace_back(CurE, CurE->getDecl());
15234 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015235 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015236
15237 if (isa<CXXThisExpr>(BaseE))
15238 // We found a base expression: this->Val.
15239 RelevantExpr = CurE;
15240 else
15241 E = BaseE;
15242
15243 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015244 if (!NoDiagnose) {
15245 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15246 << CurE->getSourceRange();
15247 return nullptr;
15248 }
15249 if (RelevantExpr)
15250 return nullptr;
15251 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015252 }
15253
15254 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15255
15256 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15257 // A bit-field cannot appear in a map clause.
15258 //
15259 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015260 if (!NoDiagnose) {
15261 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15262 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15263 return nullptr;
15264 }
15265 if (RelevantExpr)
15266 return nullptr;
15267 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015268 }
15269
15270 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15271 // If the type of a list item is a reference to a type T then the type
15272 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015273 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015274
15275 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15276 // A list item cannot be a variable that is a member of a structure with
15277 // a union type.
15278 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015279 if (CurType->isUnionType()) {
15280 if (!NoDiagnose) {
15281 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15282 << CurE->getSourceRange();
15283 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015284 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015285 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015286 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015287
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015288 // If we got a member expression, we should not expect any array section
15289 // before that:
15290 //
15291 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15292 // If a list item is an element of a structure, only the rightmost symbol
15293 // of the variable reference can be an array section.
15294 //
15295 AllowUnitySizeArraySection = false;
15296 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015297
15298 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015299 CurComponents.emplace_back(CurE, FD);
15300 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015301 E = CurE->getBase()->IgnoreParenImpCasts();
15302
15303 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015304 if (!NoDiagnose) {
15305 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15306 << 0 << CurE->getSourceRange();
15307 return nullptr;
15308 }
15309 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015310 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015311
15312 // If we got an array subscript that express the whole dimension we
15313 // can have any array expressions before. If it only expressing part of
15314 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015315 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015316 E->getType()))
15317 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015318
Patrick Lystere13b1e32019-01-02 19:28:48 +000015319 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15320 Expr::EvalResult Result;
15321 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15322 if (!Result.Val.getInt().isNullValue()) {
15323 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15324 diag::err_omp_invalid_map_this_expr);
15325 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15326 diag::note_omp_invalid_subscript_on_this_ptr_map);
15327 }
15328 }
15329 RelevantExpr = TE;
15330 }
15331
Samuel Antao90927002016-04-26 14:54:23 +000015332 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015333 CurComponents.emplace_back(CurE, nullptr);
15334 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015335 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015336 E = CurE->getBase()->IgnoreParenImpCasts();
15337
Alexey Bataev27041fa2017-12-05 15:22:49 +000015338 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015339 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15340
Samuel Antao5de996e2016-01-22 20:21:36 +000015341 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15342 // If the type of a list item is a reference to a type T then the type
15343 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015344 if (CurType->isReferenceType())
15345 CurType = CurType->getPointeeType();
15346
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015347 bool IsPointer = CurType->isAnyPointerType();
15348
15349 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015350 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15351 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015352 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015353 }
15354
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015355 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015356 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015357 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015358 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015359
Samuel Antaodab51bb2016-07-18 23:22:11 +000015360 if (AllowWholeSizeArraySection) {
15361 // Any array section is currently allowed. Allowing a whole size array
15362 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015363 //
15364 // If this array section refers to the whole dimension we can still
15365 // accept other array sections before this one, except if the base is a
15366 // pointer. Otherwise, only unitary sections are accepted.
15367 if (NotWhole || IsPointer)
15368 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015369 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015370 // A unity or whole array section is not allowed and that is not
15371 // compatible with the properties of the current array section.
15372 SemaRef.Diag(
15373 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15374 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015375 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015376 }
Samuel Antao90927002016-04-26 14:54:23 +000015377
Patrick Lystere13b1e32019-01-02 19:28:48 +000015378 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15379 Expr::EvalResult ResultR;
15380 Expr::EvalResult ResultL;
15381 if (CurE->getLength()->EvaluateAsInt(ResultR,
15382 SemaRef.getASTContext())) {
15383 if (!ResultR.Val.getInt().isOneValue()) {
15384 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15385 diag::err_omp_invalid_map_this_expr);
15386 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15387 diag::note_omp_invalid_length_on_this_ptr_mapping);
15388 }
15389 }
15390 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15391 ResultL, SemaRef.getASTContext())) {
15392 if (!ResultL.Val.getInt().isNullValue()) {
15393 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15394 diag::err_omp_invalid_map_this_expr);
15395 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15396 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15397 }
15398 }
15399 RelevantExpr = TE;
15400 }
15401
Samuel Antao90927002016-04-26 14:54:23 +000015402 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015403 CurComponents.emplace_back(CurE, nullptr);
15404 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015405 if (!NoDiagnose) {
15406 // If nothing else worked, this is not a valid map clause expression.
15407 SemaRef.Diag(
15408 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15409 << ERange;
15410 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015411 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015412 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015413 }
15414
15415 return RelevantExpr;
15416}
15417
15418// Return true if expression E associated with value VD has conflicts with other
15419// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015420static bool checkMapConflicts(
15421 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015422 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015423 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15424 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015425 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015426 SourceLocation ELoc = E->getExprLoc();
15427 SourceRange ERange = E->getSourceRange();
15428
15429 // In order to easily check the conflicts we need to match each component of
15430 // the expression under test with the components of the expressions that are
15431 // already in the stack.
15432
Samuel Antao5de996e2016-01-22 20:21:36 +000015433 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015434 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015435 "Map clause expression with unexpected base!");
15436
15437 // Variables to help detecting enclosing problems in data environment nests.
15438 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015439 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015440
Samuel Antao90927002016-04-26 14:54:23 +000015441 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15442 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015443 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15444 ERange, CKind, &EnclosingExpr,
15445 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15446 StackComponents,
15447 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015448 assert(!StackComponents.empty() &&
15449 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015450 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015451 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015452 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015453
Samuel Antao90927002016-04-26 14:54:23 +000015454 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015455 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015456
Samuel Antao5de996e2016-01-22 20:21:36 +000015457 // Expressions must start from the same base. Here we detect at which
15458 // point both expressions diverge from each other and see if we can
15459 // detect if the memory referred to both expressions is contiguous and
15460 // do not overlap.
15461 auto CI = CurComponents.rbegin();
15462 auto CE = CurComponents.rend();
15463 auto SI = StackComponents.rbegin();
15464 auto SE = StackComponents.rend();
15465 for (; CI != CE && SI != SE; ++CI, ++SI) {
15466
15467 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15468 // At most one list item can be an array item derived from a given
15469 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015470 if (CurrentRegionOnly &&
15471 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15472 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15473 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15474 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15475 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015476 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015477 << CI->getAssociatedExpression()->getSourceRange();
15478 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15479 diag::note_used_here)
15480 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015481 return true;
15482 }
15483
15484 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015485 if (CI->getAssociatedExpression()->getStmtClass() !=
15486 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015487 break;
15488
15489 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015490 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015491 break;
15492 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015493 // Check if the extra components of the expressions in the enclosing
15494 // data environment are redundant for the current base declaration.
15495 // If they are, the maps completely overlap, which is legal.
15496 for (; SI != SE; ++SI) {
15497 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015498 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015499 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015500 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015501 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015502 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015503 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015504 Type =
15505 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15506 }
15507 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015508 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015509 SemaRef, SI->getAssociatedExpression(), Type))
15510 break;
15511 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015512
15513 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15514 // List items of map clauses in the same construct must not share
15515 // original storage.
15516 //
15517 // If the expressions are exactly the same or one is a subset of the
15518 // other, it means they are sharing storage.
15519 if (CI == CE && SI == SE) {
15520 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015521 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015522 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015523 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015524 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015525 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15526 << ERange;
15527 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015528 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15529 << RE->getSourceRange();
15530 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015531 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015532 // If we find the same expression in the enclosing data environment,
15533 // that is legal.
15534 IsEnclosedByDataEnvironmentExpr = true;
15535 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015536 }
15537
Samuel Antao90927002016-04-26 14:54:23 +000015538 QualType DerivedType =
15539 std::prev(CI)->getAssociatedDeclaration()->getType();
15540 SourceLocation DerivedLoc =
15541 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015542
15543 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15544 // If the type of a list item is a reference to a type T then the type
15545 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015546 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015547
15548 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15549 // A variable for which the type is pointer and an array section
15550 // derived from that variable must not appear as list items of map
15551 // clauses of the same construct.
15552 //
15553 // Also, cover one of the cases in:
15554 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15555 // If any part of the original storage of a list item has corresponding
15556 // storage in the device data environment, all of the original storage
15557 // must have corresponding storage in the device data environment.
15558 //
15559 if (DerivedType->isAnyPointerType()) {
15560 if (CI == CE || SI == SE) {
15561 SemaRef.Diag(
15562 DerivedLoc,
15563 diag::err_omp_pointer_mapped_along_with_derived_section)
15564 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015565 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15566 << RE->getSourceRange();
15567 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015568 }
15569 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015570 SI->getAssociatedExpression()->getStmtClass() ||
15571 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15572 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015573 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015574 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015575 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015576 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15577 << RE->getSourceRange();
15578 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015579 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015580 }
15581
15582 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15583 // List items of map clauses in the same construct must not share
15584 // original storage.
15585 //
15586 // An expression is a subset of the other.
15587 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015588 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015589 if (CI != CE || SI != SE) {
15590 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15591 // a pointer.
15592 auto Begin =
15593 CI != CE ? CurComponents.begin() : StackComponents.begin();
15594 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15595 auto It = Begin;
15596 while (It != End && !It->getAssociatedDeclaration())
15597 std::advance(It, 1);
15598 assert(It != End &&
15599 "Expected at least one component with the declaration.");
15600 if (It != Begin && It->getAssociatedDeclaration()
15601 ->getType()
15602 .getCanonicalType()
15603 ->isAnyPointerType()) {
15604 IsEnclosedByDataEnvironmentExpr = false;
15605 EnclosingExpr = nullptr;
15606 return false;
15607 }
15608 }
Samuel Antao661c0902016-05-26 17:39:58 +000015609 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015610 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015611 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015612 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15613 << ERange;
15614 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015615 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15616 << RE->getSourceRange();
15617 return true;
15618 }
15619
15620 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015621 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015622 if (!CurrentRegionOnly && SI != SE)
15623 EnclosingExpr = RE;
15624
15625 // The current expression is a subset of the expression in the data
15626 // environment.
15627 IsEnclosedByDataEnvironmentExpr |=
15628 (!CurrentRegionOnly && CI != CE && SI == SE);
15629
15630 return false;
15631 });
15632
15633 if (CurrentRegionOnly)
15634 return FoundError;
15635
15636 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15637 // If any part of the original storage of a list item has corresponding
15638 // storage in the device data environment, all of the original storage must
15639 // have corresponding storage in the device data environment.
15640 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15641 // If a list item is an element of a structure, and a different element of
15642 // the structure has a corresponding list item in the device data environment
15643 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015644 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015645 // data environment prior to the task encountering the construct.
15646 //
15647 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15648 SemaRef.Diag(ELoc,
15649 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15650 << ERange;
15651 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15652 << EnclosingExpr->getSourceRange();
15653 return true;
15654 }
15655
15656 return FoundError;
15657}
15658
Michael Kruse4304e9d2019-02-19 16:38:20 +000015659// Look up the user-defined mapper given the mapper name and mapped type, and
15660// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015661static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15662 CXXScopeSpec &MapperIdScopeSpec,
15663 const DeclarationNameInfo &MapperId,
15664 QualType Type,
15665 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015666 if (MapperIdScopeSpec.isInvalid())
15667 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015668 // Get the actual type for the array type.
15669 if (Type->isArrayType()) {
15670 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15671 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15672 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015673 // Find all user-defined mappers with the given MapperId.
15674 SmallVector<UnresolvedSet<8>, 4> Lookups;
15675 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15676 Lookup.suppressDiagnostics();
15677 if (S) {
15678 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15679 NamedDecl *D = Lookup.getRepresentativeDecl();
15680 while (S && !S->isDeclScope(D))
15681 S = S->getParent();
15682 if (S)
15683 S = S->getParent();
15684 Lookups.emplace_back();
15685 Lookups.back().append(Lookup.begin(), Lookup.end());
15686 Lookup.clear();
15687 }
15688 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15689 // Extract the user-defined mappers with the given MapperId.
15690 Lookups.push_back(UnresolvedSet<8>());
15691 for (NamedDecl *D : ULE->decls()) {
15692 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15693 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15694 Lookups.back().addDecl(DMD);
15695 }
15696 }
15697 // Defer the lookup for dependent types. The results will be passed through
15698 // UnresolvedMapper on instantiation.
15699 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15700 Type->isInstantiationDependentType() ||
15701 Type->containsUnexpandedParameterPack() ||
15702 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15703 return !D->isInvalidDecl() &&
15704 (D->getType()->isDependentType() ||
15705 D->getType()->isInstantiationDependentType() ||
15706 D->getType()->containsUnexpandedParameterPack());
15707 })) {
15708 UnresolvedSet<8> URS;
15709 for (const UnresolvedSet<8> &Set : Lookups) {
15710 if (Set.empty())
15711 continue;
15712 URS.append(Set.begin(), Set.end());
15713 }
15714 return UnresolvedLookupExpr::Create(
15715 SemaRef.Context, /*NamingClass=*/nullptr,
15716 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15717 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15718 }
Michael Kruse945249b2019-09-26 22:53:01 +000015719 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015720 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15721 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015722 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15723 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15724 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15725 return ExprError();
15726 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015727 // Perform argument dependent lookup.
15728 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15729 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15730 // Return the first user-defined mapper with the desired type.
15731 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15732 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15733 if (!D->isInvalidDecl() &&
15734 SemaRef.Context.hasSameType(D->getType(), Type))
15735 return D;
15736 return nullptr;
15737 }))
15738 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15739 // Find the first user-defined mapper with a type derived from the desired
15740 // type.
15741 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15742 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15743 if (!D->isInvalidDecl() &&
15744 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15745 !Type.isMoreQualifiedThan(D->getType()))
15746 return D;
15747 return nullptr;
15748 })) {
15749 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15750 /*DetectVirtual=*/false);
15751 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15752 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15753 VD->getType().getUnqualifiedType()))) {
15754 if (SemaRef.CheckBaseClassAccess(
15755 Loc, VD->getType(), Type, Paths.front(),
15756 /*DiagID=*/0) != Sema::AR_inaccessible) {
15757 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15758 }
15759 }
15760 }
15761 }
15762 // Report error if a mapper is specified, but cannot be found.
15763 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15764 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15765 << Type << MapperId.getName();
15766 return ExprError();
15767 }
15768 return ExprEmpty();
15769}
15770
Samuel Antao661c0902016-05-26 17:39:58 +000015771namespace {
15772// Utility struct that gathers all the related lists associated with a mappable
15773// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015774struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015775 // The list of expressions.
15776 ArrayRef<Expr *> VarList;
15777 // The list of processed expressions.
15778 SmallVector<Expr *, 16> ProcessedVarList;
15779 // The mappble components for each expression.
15780 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15781 // The base declaration of the variable.
15782 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015783 // The reference to the user-defined mapper associated with every expression.
15784 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015785
15786 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15787 // We have a list of components and base declarations for each entry in the
15788 // variable list.
15789 VarComponents.reserve(VarList.size());
15790 VarBaseDeclarations.reserve(VarList.size());
15791 }
15792};
15793}
15794
15795// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015796// \a CKind. In the check process the valid expressions, mappable expression
15797// components, variables, and user-defined mappers are extracted and used to
15798// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15799// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15800// and \a MapperId are expected to be valid if the clause kind is 'map'.
15801static void checkMappableExpressionList(
15802 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15803 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015804 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15805 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015806 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015807 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015808 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15809 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015810 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015811
15812 // If the identifier of user-defined mapper is not specified, it is "default".
15813 // We do not change the actual name in this clause to distinguish whether a
15814 // mapper is specified explicitly, i.e., it is not explicitly specified when
15815 // MapperId.getName() is empty.
15816 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15817 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15818 MapperId.setName(DeclNames.getIdentifier(
15819 &SemaRef.getASTContext().Idents.get("default")));
15820 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015821
15822 // Iterators to find the current unresolved mapper expression.
15823 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15824 bool UpdateUMIt = false;
15825 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015826
Samuel Antao90927002016-04-26 14:54:23 +000015827 // Keep track of the mappable components and base declarations in this clause.
15828 // Each entry in the list is going to have a list of components associated. We
15829 // record each set of the components so that we can build the clause later on.
15830 // In the end we should have the same amount of declarations and component
15831 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015832
Alexey Bataeve3727102018-04-18 15:57:46 +000015833 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015834 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015835 SourceLocation ELoc = RE->getExprLoc();
15836
Michael Kruse4304e9d2019-02-19 16:38:20 +000015837 // Find the current unresolved mapper expression.
15838 if (UpdateUMIt && UMIt != UMEnd) {
15839 UMIt++;
15840 assert(
15841 UMIt != UMEnd &&
15842 "Expect the size of UnresolvedMappers to match with that of VarList");
15843 }
15844 UpdateUMIt = true;
15845 if (UMIt != UMEnd)
15846 UnresolvedMapper = *UMIt;
15847
Alexey Bataeve3727102018-04-18 15:57:46 +000015848 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015849
15850 if (VE->isValueDependent() || VE->isTypeDependent() ||
15851 VE->isInstantiationDependent() ||
15852 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015853 // Try to find the associated user-defined mapper.
15854 ExprResult ER = buildUserDefinedMapperRef(
15855 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15856 VE->getType().getCanonicalType(), UnresolvedMapper);
15857 if (ER.isInvalid())
15858 continue;
15859 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015860 // We can only analyze this information once the missing information is
15861 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015862 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015863 continue;
15864 }
15865
Alexey Bataeve3727102018-04-18 15:57:46 +000015866 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015867
Samuel Antao5de996e2016-01-22 20:21:36 +000015868 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015869 SemaRef.Diag(ELoc,
15870 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015871 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015872 continue;
15873 }
15874
Samuel Antao90927002016-04-26 14:54:23 +000015875 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15876 ValueDecl *CurDeclaration = nullptr;
15877
15878 // Obtain the array or member expression bases if required. Also, fill the
15879 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015880 const Expr *BE = checkMapClauseExpressionBase(
15881 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015882 if (!BE)
15883 continue;
15884
Samuel Antao90927002016-04-26 14:54:23 +000015885 assert(!CurComponents.empty() &&
15886 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015887
Patrick Lystere13b1e32019-01-02 19:28:48 +000015888 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15889 // Add store "this" pointer to class in DSAStackTy for future checking
15890 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015891 // Try to find the associated user-defined mapper.
15892 ExprResult ER = buildUserDefinedMapperRef(
15893 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15894 VE->getType().getCanonicalType(), UnresolvedMapper);
15895 if (ER.isInvalid())
15896 continue;
15897 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015898 // Skip restriction checking for variable or field declarations
15899 MVLI.ProcessedVarList.push_back(RE);
15900 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15901 MVLI.VarComponents.back().append(CurComponents.begin(),
15902 CurComponents.end());
15903 MVLI.VarBaseDeclarations.push_back(nullptr);
15904 continue;
15905 }
15906
Samuel Antao90927002016-04-26 14:54:23 +000015907 // For the following checks, we rely on the base declaration which is
15908 // expected to be associated with the last component. The declaration is
15909 // expected to be a variable or a field (if 'this' is being mapped).
15910 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15911 assert(CurDeclaration && "Null decl on map clause.");
15912 assert(
15913 CurDeclaration->isCanonicalDecl() &&
15914 "Expecting components to have associated only canonical declarations.");
15915
15916 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015917 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015918
15919 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015920 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015921
15922 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015923 // threadprivate variables cannot appear in a map clause.
15924 // OpenMP 4.5 [2.10.5, target update Construct]
15925 // threadprivate variables cannot appear in a from clause.
15926 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015927 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015928 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15929 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015930 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015931 continue;
15932 }
15933
Samuel Antao5de996e2016-01-22 20:21:36 +000015934 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15935 // A list item cannot appear in both a map clause and a data-sharing
15936 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015937
Samuel Antao5de996e2016-01-22 20:21:36 +000015938 // Check conflicts with other map clause expressions. We check the conflicts
15939 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015940 // environment, because the restrictions are different. We only have to
15941 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015942 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015943 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015944 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015945 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015946 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015947 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015948 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015949
Samuel Antao661c0902016-05-26 17:39:58 +000015950 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015951 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15952 // If the type of a list item is a reference to a type T then the type will
15953 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015954 auto I = llvm::find_if(
15955 CurComponents,
15956 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15957 return MC.getAssociatedDeclaration();
15958 });
15959 assert(I != CurComponents.end() && "Null decl on map clause.");
15960 QualType Type =
15961 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015962
Samuel Antao661c0902016-05-26 17:39:58 +000015963 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15964 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000015965 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000015966 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000015967 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000015968 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000015969 continue;
15970
Samuel Antao661c0902016-05-26 17:39:58 +000015971 if (CKind == OMPC_map) {
15972 // target enter data
15973 // OpenMP [2.10.2, Restrictions, p. 99]
15974 // A map-type must be specified in all map clauses and must be either
15975 // to or alloc.
15976 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15977 if (DKind == OMPD_target_enter_data &&
15978 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15979 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15980 << (IsMapTypeImplicit ? 1 : 0)
15981 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15982 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015983 continue;
15984 }
Samuel Antao661c0902016-05-26 17:39:58 +000015985
15986 // target exit_data
15987 // OpenMP [2.10.3, Restrictions, p. 102]
15988 // A map-type must be specified in all map clauses and must be either
15989 // from, release, or delete.
15990 if (DKind == OMPD_target_exit_data &&
15991 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15992 MapType == OMPC_MAP_delete)) {
15993 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15994 << (IsMapTypeImplicit ? 1 : 0)
15995 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15996 << getOpenMPDirectiveName(DKind);
15997 continue;
15998 }
15999
16000 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16001 // A list item cannot appear in both a map clause and a data-sharing
16002 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000016003 //
16004 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16005 // A list item cannot appear in both a map clause and a data-sharing
16006 // attribute clause on the same construct unless the construct is a
16007 // combined construct.
16008 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
16009 isOpenMPTargetExecutionDirective(DKind)) ||
16010 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016011 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016012 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000016013 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000016014 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000016015 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000016016 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016017 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000016018 continue;
16019 }
16020 }
Michael Kruse01f670d2019-02-22 22:29:42 +000016021 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016022
Michael Kruse01f670d2019-02-22 22:29:42 +000016023 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000016024 ExprResult ER = buildUserDefinedMapperRef(
16025 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16026 Type.getCanonicalType(), UnresolvedMapper);
16027 if (ER.isInvalid())
16028 continue;
16029 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016030
Samuel Antao90927002016-04-26 14:54:23 +000016031 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000016032 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000016033
16034 // Store the components in the stack so that they can be used to check
16035 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000016036 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
16037 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000016038
16039 // Save the components and declaration to create the clause. For purposes of
16040 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000016041 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000016042 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16043 MVLI.VarComponents.back().append(CurComponents.begin(),
16044 CurComponents.end());
16045 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
16046 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016047 }
Samuel Antao661c0902016-05-26 17:39:58 +000016048}
16049
Michael Kruse4304e9d2019-02-19 16:38:20 +000016050OMPClause *Sema::ActOnOpenMPMapClause(
16051 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16052 ArrayRef<SourceLocation> MapTypeModifiersLoc,
16053 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
16054 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
16055 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
16056 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
16057 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
16058 OMPC_MAP_MODIFIER_unknown,
16059 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000016060 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
16061
16062 // Process map-type-modifiers, flag errors for duplicate modifiers.
16063 unsigned Count = 0;
16064 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
16065 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
16066 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
16067 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
16068 continue;
16069 }
16070 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000016071 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000016072 Modifiers[Count] = MapTypeModifiers[I];
16073 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
16074 ++Count;
16075 }
16076
Michael Kruse4304e9d2019-02-19 16:38:20 +000016077 MappableVarListInfo MVLI(VarList);
16078 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016079 MapperIdScopeSpec, MapperId, UnresolvedMappers,
16080 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000016081
Samuel Antao5de996e2016-01-22 20:21:36 +000016082 // We need to produce a map clause even if we don't have variables so that
16083 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000016084 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
16085 MVLI.VarBaseDeclarations, MVLI.VarComponents,
16086 MVLI.UDMapperList, Modifiers, ModifiersLoc,
16087 MapperIdScopeSpec.getWithLocInContext(Context),
16088 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016089}
Kelvin Li099bb8c2015-11-24 20:50:12 +000016090
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016091QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
16092 TypeResult ParsedType) {
16093 assert(ParsedType.isUsable());
16094
16095 QualType ReductionType = GetTypeFromParser(ParsedType.get());
16096 if (ReductionType.isNull())
16097 return QualType();
16098
16099 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
16100 // A type name in a declare reduction directive cannot be a function type, an
16101 // array type, a reference type, or a type qualified with const, volatile or
16102 // restrict.
16103 if (ReductionType.hasQualifiers()) {
16104 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
16105 return QualType();
16106 }
16107
16108 if (ReductionType->isFunctionType()) {
16109 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
16110 return QualType();
16111 }
16112 if (ReductionType->isReferenceType()) {
16113 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
16114 return QualType();
16115 }
16116 if (ReductionType->isArrayType()) {
16117 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
16118 return QualType();
16119 }
16120 return ReductionType;
16121}
16122
16123Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
16124 Scope *S, DeclContext *DC, DeclarationName Name,
16125 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
16126 AccessSpecifier AS, Decl *PrevDeclInScope) {
16127 SmallVector<Decl *, 8> Decls;
16128 Decls.reserve(ReductionTypes.size());
16129
16130 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000016131 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016132 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
16133 // A reduction-identifier may not be re-declared in the current scope for the
16134 // same type or for a type that is compatible according to the base language
16135 // rules.
16136 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16137 OMPDeclareReductionDecl *PrevDRD = nullptr;
16138 bool InCompoundScope = true;
16139 if (S != nullptr) {
16140 // Find previous declaration with the same name not referenced in other
16141 // declarations.
16142 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16143 InCompoundScope =
16144 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16145 LookupName(Lookup, S);
16146 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16147 /*AllowInlineNamespace=*/false);
16148 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000016149 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016150 while (Filter.hasNext()) {
16151 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
16152 if (InCompoundScope) {
16153 auto I = UsedAsPrevious.find(PrevDecl);
16154 if (I == UsedAsPrevious.end())
16155 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000016156 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016157 UsedAsPrevious[D] = true;
16158 }
16159 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16160 PrevDecl->getLocation();
16161 }
16162 Filter.done();
16163 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016164 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016165 if (!PrevData.second) {
16166 PrevDRD = PrevData.first;
16167 break;
16168 }
16169 }
16170 }
16171 } else if (PrevDeclInScope != nullptr) {
16172 auto *PrevDRDInScope = PrevDRD =
16173 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
16174 do {
16175 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
16176 PrevDRDInScope->getLocation();
16177 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
16178 } while (PrevDRDInScope != nullptr);
16179 }
Alexey Bataeve3727102018-04-18 15:57:46 +000016180 for (const auto &TyData : ReductionTypes) {
16181 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016182 bool Invalid = false;
16183 if (I != PreviousRedeclTypes.end()) {
16184 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
16185 << TyData.first;
16186 Diag(I->second, diag::note_previous_definition);
16187 Invalid = true;
16188 }
16189 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
16190 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
16191 Name, TyData.first, PrevDRD);
16192 DC->addDecl(DRD);
16193 DRD->setAccess(AS);
16194 Decls.push_back(DRD);
16195 if (Invalid)
16196 DRD->setInvalidDecl();
16197 else
16198 PrevDRD = DRD;
16199 }
16200
16201 return DeclGroupPtrTy::make(
16202 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16203}
16204
16205void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16206 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16207
16208 // Enter new function scope.
16209 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016210 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016211 getCurFunction()->setHasOMPDeclareReductionCombiner();
16212
16213 if (S != nullptr)
16214 PushDeclContext(S, DRD);
16215 else
16216 CurContext = DRD;
16217
Faisal Valid143a0c2017-04-01 21:30:49 +000016218 PushExpressionEvaluationContext(
16219 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016220
16221 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016222 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16223 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16224 // uses semantics of argument handles by value, but it should be passed by
16225 // reference. C lang does not support references, so pass all parameters as
16226 // pointers.
16227 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016228 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016229 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016230 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16231 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16232 // uses semantics of argument handles by value, but it should be passed by
16233 // reference. C lang does not support references, so pass all parameters as
16234 // pointers.
16235 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016236 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016237 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16238 if (S != nullptr) {
16239 PushOnScopeChains(OmpInParm, S);
16240 PushOnScopeChains(OmpOutParm, S);
16241 } else {
16242 DRD->addDecl(OmpInParm);
16243 DRD->addDecl(OmpOutParm);
16244 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016245 Expr *InE =
16246 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16247 Expr *OutE =
16248 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16249 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016250}
16251
16252void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16253 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16254 DiscardCleanupsInEvaluationContext();
16255 PopExpressionEvaluationContext();
16256
16257 PopDeclContext();
16258 PopFunctionScopeInfo();
16259
16260 if (Combiner != nullptr)
16261 DRD->setCombiner(Combiner);
16262 else
16263 DRD->setInvalidDecl();
16264}
16265
Alexey Bataev070f43a2017-09-06 14:49:58 +000016266VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016267 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16268
16269 // Enter new function scope.
16270 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016271 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016272
16273 if (S != nullptr)
16274 PushDeclContext(S, DRD);
16275 else
16276 CurContext = DRD;
16277
Faisal Valid143a0c2017-04-01 21:30:49 +000016278 PushExpressionEvaluationContext(
16279 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016280
16281 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016282 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16283 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16284 // uses semantics of argument handles by value, but it should be passed by
16285 // reference. C lang does not support references, so pass all parameters as
16286 // pointers.
16287 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016288 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016289 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016290 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16291 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16292 // uses semantics of argument handles by value, but it should be passed by
16293 // reference. C lang does not support references, so pass all parameters as
16294 // pointers.
16295 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016296 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016297 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016298 if (S != nullptr) {
16299 PushOnScopeChains(OmpPrivParm, S);
16300 PushOnScopeChains(OmpOrigParm, S);
16301 } else {
16302 DRD->addDecl(OmpPrivParm);
16303 DRD->addDecl(OmpOrigParm);
16304 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016305 Expr *OrigE =
16306 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16307 Expr *PrivE =
16308 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16309 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016310 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016311}
16312
Alexey Bataev070f43a2017-09-06 14:49:58 +000016313void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16314 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016315 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16316 DiscardCleanupsInEvaluationContext();
16317 PopExpressionEvaluationContext();
16318
16319 PopDeclContext();
16320 PopFunctionScopeInfo();
16321
Alexey Bataev070f43a2017-09-06 14:49:58 +000016322 if (Initializer != nullptr) {
16323 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16324 } else if (OmpPrivParm->hasInit()) {
16325 DRD->setInitializer(OmpPrivParm->getInit(),
16326 OmpPrivParm->isDirectInit()
16327 ? OMPDeclareReductionDecl::DirectInit
16328 : OMPDeclareReductionDecl::CopyInit);
16329 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016330 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016331 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016332}
16333
16334Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16335 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016336 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016337 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016338 if (S)
16339 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16340 /*AddToContext=*/false);
16341 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016342 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016343 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016344 }
16345 return DeclReductions;
16346}
16347
Michael Kruse251e1482019-02-01 20:25:04 +000016348TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16349 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16350 QualType T = TInfo->getType();
16351 if (D.isInvalidType())
16352 return true;
16353
16354 if (getLangOpts().CPlusPlus) {
16355 // Check that there are no default arguments (C++ only).
16356 CheckExtraCXXDefaultArguments(D);
16357 }
16358
16359 return CreateParsedType(T, TInfo);
16360}
16361
16362QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16363 TypeResult ParsedType) {
16364 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16365
16366 QualType MapperType = GetTypeFromParser(ParsedType.get());
16367 assert(!MapperType.isNull() && "Expect valid mapper type");
16368
16369 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16370 // The type must be of struct, union or class type in C and C++
16371 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16372 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16373 return QualType();
16374 }
16375 return MapperType;
16376}
16377
16378OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16379 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16380 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16381 Decl *PrevDeclInScope) {
16382 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16383 forRedeclarationInCurContext());
16384 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16385 // A mapper-identifier may not be redeclared in the current scope for the
16386 // same type or for a type that is compatible according to the base language
16387 // rules.
16388 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16389 OMPDeclareMapperDecl *PrevDMD = nullptr;
16390 bool InCompoundScope = true;
16391 if (S != nullptr) {
16392 // Find previous declaration with the same name not referenced in other
16393 // declarations.
16394 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16395 InCompoundScope =
16396 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16397 LookupName(Lookup, S);
16398 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16399 /*AllowInlineNamespace=*/false);
16400 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16401 LookupResult::Filter Filter = Lookup.makeFilter();
16402 while (Filter.hasNext()) {
16403 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16404 if (InCompoundScope) {
16405 auto I = UsedAsPrevious.find(PrevDecl);
16406 if (I == UsedAsPrevious.end())
16407 UsedAsPrevious[PrevDecl] = false;
16408 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16409 UsedAsPrevious[D] = true;
16410 }
16411 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16412 PrevDecl->getLocation();
16413 }
16414 Filter.done();
16415 if (InCompoundScope) {
16416 for (const auto &PrevData : UsedAsPrevious) {
16417 if (!PrevData.second) {
16418 PrevDMD = PrevData.first;
16419 break;
16420 }
16421 }
16422 }
16423 } else if (PrevDeclInScope) {
16424 auto *PrevDMDInScope = PrevDMD =
16425 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16426 do {
16427 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16428 PrevDMDInScope->getLocation();
16429 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16430 } while (PrevDMDInScope != nullptr);
16431 }
16432 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16433 bool Invalid = false;
16434 if (I != PreviousRedeclTypes.end()) {
16435 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16436 << MapperType << Name;
16437 Diag(I->second, diag::note_previous_definition);
16438 Invalid = true;
16439 }
16440 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16441 MapperType, VN, PrevDMD);
16442 DC->addDecl(DMD);
16443 DMD->setAccess(AS);
16444 if (Invalid)
16445 DMD->setInvalidDecl();
16446
16447 // Enter new function scope.
16448 PushFunctionScope();
16449 setFunctionHasBranchProtectedScope();
16450
16451 CurContext = DMD;
16452
16453 return DMD;
16454}
16455
16456void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16457 Scope *S,
16458 QualType MapperType,
16459 SourceLocation StartLoc,
16460 DeclarationName VN) {
16461 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16462 if (S)
16463 PushOnScopeChains(VD, S);
16464 else
16465 DMD->addDecl(VD);
16466 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16467 DMD->setMapperVarRef(MapperVarRefExpr);
16468}
16469
16470Sema::DeclGroupPtrTy
16471Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16472 ArrayRef<OMPClause *> ClauseList) {
16473 PopDeclContext();
16474 PopFunctionScopeInfo();
16475
16476 if (D) {
16477 if (S)
16478 PushOnScopeChains(D, S, /*AddToContext=*/false);
16479 D->CreateClauses(Context, ClauseList);
16480 }
16481
16482 return DeclGroupPtrTy::make(DeclGroupRef(D));
16483}
16484
David Majnemer9d168222016-08-05 17:44:54 +000016485OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016486 SourceLocation StartLoc,
16487 SourceLocation LParenLoc,
16488 SourceLocation EndLoc) {
16489 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016490 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016491
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016492 // OpenMP [teams Constrcut, Restrictions]
16493 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016494 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016495 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016496 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016497
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016498 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016499 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016500 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016501 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016502 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016503 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016504 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16505 HelperValStmt = buildPreInits(Context, Captures);
16506 }
16507
16508 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16509 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016510}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016511
16512OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16513 SourceLocation StartLoc,
16514 SourceLocation LParenLoc,
16515 SourceLocation EndLoc) {
16516 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016517 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016518
16519 // OpenMP [teams Constrcut, Restrictions]
16520 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016521 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016522 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016523 return nullptr;
16524
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016525 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016526 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16527 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016528 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016529 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016530 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016531 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16532 HelperValStmt = buildPreInits(Context, Captures);
16533 }
16534
16535 return new (Context) OMPThreadLimitClause(
16536 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016537}
Alexey Bataeva0569352015-12-01 10:17:31 +000016538
16539OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16540 SourceLocation StartLoc,
16541 SourceLocation LParenLoc,
16542 SourceLocation EndLoc) {
16543 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016544 Stmt *HelperValStmt = nullptr;
16545 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016546
16547 // OpenMP [2.9.1, task Constrcut]
16548 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016549 if (!isNonNegativeIntegerValue(
16550 ValExpr, *this, OMPC_priority,
16551 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16552 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016553 return nullptr;
16554
Alexey Bataev31ba4762019-10-16 18:09:37 +000016555 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16556 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016557}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016558
16559OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16560 SourceLocation StartLoc,
16561 SourceLocation LParenLoc,
16562 SourceLocation EndLoc) {
16563 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016564 Stmt *HelperValStmt = nullptr;
16565 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016566
16567 // OpenMP [2.9.2, taskloop Constrcut]
16568 // The parameter of the grainsize clause must be a positive integer
16569 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016570 if (!isNonNegativeIntegerValue(
16571 ValExpr, *this, OMPC_grainsize,
16572 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16573 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016574 return nullptr;
16575
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016576 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16577 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016578}
Alexey Bataev382967a2015-12-08 12:06:20 +000016579
16580OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16581 SourceLocation StartLoc,
16582 SourceLocation LParenLoc,
16583 SourceLocation EndLoc) {
16584 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016585 Stmt *HelperValStmt = nullptr;
16586 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016587
16588 // OpenMP [2.9.2, taskloop Constrcut]
16589 // The parameter of the num_tasks clause must be a positive integer
16590 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016591 if (!isNonNegativeIntegerValue(
16592 ValExpr, *this, OMPC_num_tasks,
16593 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16594 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016595 return nullptr;
16596
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016597 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16598 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016599}
16600
Alexey Bataev28c75412015-12-15 08:19:24 +000016601OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16602 SourceLocation LParenLoc,
16603 SourceLocation EndLoc) {
16604 // OpenMP [2.13.2, critical construct, Description]
16605 // ... where hint-expression is an integer constant expression that evaluates
16606 // to a valid lock hint.
16607 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16608 if (HintExpr.isInvalid())
16609 return nullptr;
16610 return new (Context)
16611 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16612}
16613
Carlo Bertollib4adf552016-01-15 18:50:31 +000016614OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16615 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16616 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16617 SourceLocation EndLoc) {
16618 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16619 std::string Values;
16620 Values += "'";
16621 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16622 Values += "'";
16623 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16624 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16625 return nullptr;
16626 }
16627 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016628 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016629 if (ChunkSize) {
16630 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16631 !ChunkSize->isInstantiationDependent() &&
16632 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016633 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016634 ExprResult Val =
16635 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16636 if (Val.isInvalid())
16637 return nullptr;
16638
16639 ValExpr = Val.get();
16640
16641 // OpenMP [2.7.1, Restrictions]
16642 // chunk_size must be a loop invariant integer expression with a positive
16643 // value.
16644 llvm::APSInt Result;
16645 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16646 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16647 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16648 << "dist_schedule" << ChunkSize->getSourceRange();
16649 return nullptr;
16650 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016651 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016652 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16653 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016654 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016655 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016656 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016657 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16658 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016659 }
16660 }
16661 }
16662
16663 return new (Context)
16664 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016665 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016666}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016667
16668OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16669 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16670 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16671 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016672 if (getLangOpts().OpenMP < 50) {
16673 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16674 Kind != OMPC_DEFAULTMAP_scalar) {
16675 std::string Value;
16676 SourceLocation Loc;
16677 Value += "'";
16678 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16679 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16680 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16681 Loc = MLoc;
16682 } else {
16683 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16684 OMPC_DEFAULTMAP_scalar);
16685 Loc = KindLoc;
16686 }
16687 Value += "'";
16688 Diag(Loc, diag::err_omp_unexpected_clause_value)
16689 << Value << getOpenMPClauseName(OMPC_defaultmap);
16690 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016691 }
cchene06f3e02019-11-15 13:02:06 -050016692 } else {
16693 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16694 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16695 if (!isDefaultmapKind || !isDefaultmapModifier) {
16696 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16697 "'firstprivate', 'none', 'default'";
16698 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16699 if (!isDefaultmapKind && isDefaultmapModifier) {
16700 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16701 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16702 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16703 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16704 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16705 } else {
16706 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16707 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16708 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16709 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16710 }
16711 return nullptr;
16712 }
16713
16714 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
16715 // At most one defaultmap clause for each category can appear on the
16716 // directive.
16717 if (DSAStack->checkDefaultmapCategory(Kind)) {
16718 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
16719 return nullptr;
16720 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016721 }
cchene06f3e02019-11-15 13:02:06 -050016722 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016723
16724 return new (Context)
16725 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16726}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016727
16728bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16729 DeclContext *CurLexicalContext = getCurLexicalContext();
16730 if (!CurLexicalContext->isFileContext() &&
16731 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016732 !CurLexicalContext->isExternCXXContext() &&
16733 !isa<CXXRecordDecl>(CurLexicalContext) &&
16734 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16735 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16736 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016737 Diag(Loc, diag::err_omp_region_not_file_context);
16738 return false;
16739 }
Kelvin Libc38e632018-09-10 02:07:09 +000016740 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016741 return true;
16742}
16743
16744void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016745 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016746 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016747 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016748}
16749
Alexey Bataev729e2422019-08-23 16:11:14 +000016750NamedDecl *
16751Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16752 const DeclarationNameInfo &Id,
16753 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016754 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16755 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16756
16757 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016758 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016759 Lookup.suppressDiagnostics();
16760
16761 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016762 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016763 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016764 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016765 CTK_ErrorRecovery)) {
16766 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16767 << Id.getName());
16768 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016769 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016770 }
16771
16772 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016773 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016774 }
16775
16776 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016777 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16778 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016779 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016780 return nullptr;
16781 }
16782 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16783 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16784 return ND;
16785}
16786
16787void Sema::ActOnOpenMPDeclareTargetName(
16788 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16789 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16790 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16791 isa<FunctionTemplateDecl>(ND)) &&
16792 "Expected variable, function or function template.");
16793
16794 // Diagnose marking after use as it may lead to incorrect diagnosis and
16795 // codegen.
16796 if (LangOpts.OpenMP >= 50 &&
16797 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16798 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16799
16800 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16801 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16802 if (DevTy.hasValue() && *DevTy != DT) {
16803 Diag(Loc, diag::err_omp_device_type_mismatch)
16804 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16805 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16806 return;
16807 }
16808 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16809 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16810 if (!Res) {
16811 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16812 SourceRange(Loc, Loc));
16813 ND->addAttr(A);
16814 if (ASTMutationListener *ML = Context.getASTMutationListener())
16815 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16816 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16817 } else if (*Res != MT) {
16818 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016819 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016820}
16821
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016822static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16823 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016824 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016825 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016826 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016827 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16828 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16829 if (SemaRef.LangOpts.OpenMP >= 50 &&
16830 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16831 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16832 VD->hasGlobalStorage()) {
16833 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16834 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16835 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16836 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16837 // If a lambda declaration and definition appears between a
16838 // declare target directive and the matching end declare target
16839 // directive, all variables that are captured by the lambda
16840 // expression must also appear in a to clause.
16841 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016842 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016843 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16844 << VD << 0 << SR;
16845 return;
16846 }
16847 }
16848 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016849 return;
16850 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16851 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016852}
16853
16854static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16855 Sema &SemaRef, DSAStackTy *Stack,
16856 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016857 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016858 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16859 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016860}
16861
Kelvin Li1ce87c72017-12-12 20:08:12 +000016862void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16863 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016864 if (!D || D->isInvalidDecl())
16865 return;
16866 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016867 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016868 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016869 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016870 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16871 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016872 return;
16873 // 2.10.6: threadprivate variable cannot appear in a declare target
16874 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016875 if (DSAStack->isThreadPrivate(VD)) {
16876 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016877 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016878 return;
16879 }
16880 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016881 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16882 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016883 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016884 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16885 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016886 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016887 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16888 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16889 return;
16890 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016891 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016892 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16893 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16894 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16895 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016896 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016897 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16898 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16899 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016900 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016901 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16902 // Problem if any with var declared with incomplete type will be reported
16903 // as normal, so no need to check it here.
16904 if ((E || !VD->getType()->isIncompleteType()) &&
16905 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16906 return;
16907 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16908 // Checking declaration inside declare target region.
16909 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16910 isa<FunctionTemplateDecl>(D)) {
16911 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016912 Context, OMPDeclareTargetDeclAttr::MT_To,
16913 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000016914 D->addAttr(A);
16915 if (ASTMutationListener *ML = Context.getASTMutationListener())
16916 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16917 }
16918 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016919 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016920 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016921 if (!E)
16922 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016923 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16924}
Samuel Antao661c0902016-05-26 17:39:58 +000016925
16926OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000016927 CXXScopeSpec &MapperIdScopeSpec,
16928 DeclarationNameInfo &MapperId,
16929 const OMPVarListLocTy &Locs,
16930 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000016931 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016932 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
16933 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000016934 if (MVLI.ProcessedVarList.empty())
16935 return nullptr;
16936
Michael Kruse01f670d2019-02-22 22:29:42 +000016937 return OMPToClause::Create(
16938 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16939 MVLI.VarComponents, MVLI.UDMapperList,
16940 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000016941}
Samuel Antaoec172c62016-05-26 17:49:04 +000016942
16943OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000016944 CXXScopeSpec &MapperIdScopeSpec,
16945 DeclarationNameInfo &MapperId,
16946 const OMPVarListLocTy &Locs,
16947 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016948 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016949 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
16950 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000016951 if (MVLI.ProcessedVarList.empty())
16952 return nullptr;
16953
Michael Kruse0336c752019-02-25 20:34:15 +000016954 return OMPFromClause::Create(
16955 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16956 MVLI.VarComponents, MVLI.UDMapperList,
16957 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016958}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016959
16960OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016961 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016962 MappableVarListInfo MVLI(VarList);
16963 SmallVector<Expr *, 8> PrivateCopies;
16964 SmallVector<Expr *, 8> Inits;
16965
Alexey Bataeve3727102018-04-18 15:57:46 +000016966 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016967 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
16968 SourceLocation ELoc;
16969 SourceRange ERange;
16970 Expr *SimpleRefExpr = RefExpr;
16971 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16972 if (Res.second) {
16973 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000016974 MVLI.ProcessedVarList.push_back(RefExpr);
16975 PrivateCopies.push_back(nullptr);
16976 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016977 }
16978 ValueDecl *D = Res.first;
16979 if (!D)
16980 continue;
16981
16982 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000016983 Type = Type.getNonReferenceType().getUnqualifiedType();
16984
16985 auto *VD = dyn_cast<VarDecl>(D);
16986
16987 // Item should be a pointer or reference to pointer.
16988 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016989 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16990 << 0 << RefExpr->getSourceRange();
16991 continue;
16992 }
Samuel Antaocc10b852016-07-28 14:23:26 +000016993
16994 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000016995 auto VDPrivate =
16996 buildVarDecl(*this, ELoc, Type, D->getName(),
16997 D->hasAttrs() ? &D->getAttrs() : nullptr,
16998 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000016999 if (VDPrivate->isInvalidDecl())
17000 continue;
17001
17002 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000017003 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000017004 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
17005
17006 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000017007 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000017008 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000017009 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
17010 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000017011 AddInitializerToDecl(VDPrivate,
17012 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000017013 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000017014
17015 // If required, build a capture to implement the privatization initialized
17016 // with the current list item value.
17017 DeclRefExpr *Ref = nullptr;
17018 if (!VD)
17019 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17020 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
17021 PrivateCopies.push_back(VDPrivateRefExpr);
17022 Inits.push_back(VDInitRefExpr);
17023
17024 // We need to add a data sharing attribute for this variable to make sure it
17025 // is correctly captured. A variable that shows up in a use_device_ptr has
17026 // similar properties of a first private variable.
17027 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
17028
17029 // Create a mappable component for the list item. List items in this clause
17030 // only need a component.
17031 MVLI.VarBaseDeclarations.push_back(D);
17032 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17033 MVLI.VarComponents.back().push_back(
17034 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000017035 }
17036
Samuel Antaocc10b852016-07-28 14:23:26 +000017037 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000017038 return nullptr;
17039
Samuel Antaocc10b852016-07-28 14:23:26 +000017040 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000017041 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
17042 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017043}
Carlo Bertolli70594e92016-07-13 17:16:49 +000017044
17045OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017046 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000017047 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000017048 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000017049 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000017050 SourceLocation ELoc;
17051 SourceRange ERange;
17052 Expr *SimpleRefExpr = RefExpr;
17053 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17054 if (Res.second) {
17055 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000017056 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017057 }
17058 ValueDecl *D = Res.first;
17059 if (!D)
17060 continue;
17061
17062 QualType Type = D->getType();
17063 // item should be a pointer or array or reference to pointer or array
17064 if (!Type.getNonReferenceType()->isPointerType() &&
17065 !Type.getNonReferenceType()->isArrayType()) {
17066 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
17067 << 0 << RefExpr->getSourceRange();
17068 continue;
17069 }
Samuel Antao6890b092016-07-28 14:25:09 +000017070
17071 // Check if the declaration in the clause does not show up in any data
17072 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000017073 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000017074 if (isOpenMPPrivate(DVar.CKind)) {
17075 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17076 << getOpenMPClauseName(DVar.CKind)
17077 << getOpenMPClauseName(OMPC_is_device_ptr)
17078 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000017079 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000017080 continue;
17081 }
17082
Alexey Bataeve3727102018-04-18 15:57:46 +000017083 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000017084 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000017085 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000017086 [&ConflictExpr](
17087 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
17088 OpenMPClauseKind) -> bool {
17089 ConflictExpr = R.front().getAssociatedExpression();
17090 return true;
17091 })) {
17092 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
17093 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
17094 << ConflictExpr->getSourceRange();
17095 continue;
17096 }
17097
17098 // Store the components in the stack so that they can be used to check
17099 // against other clauses later on.
17100 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
17101 DSAStack->addMappableExpressionComponents(
17102 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
17103
17104 // Record the expression we've just processed.
17105 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
17106
17107 // Create a mappable component for the list item. List items in this clause
17108 // only need a component. We use a null declaration to signal fields in
17109 // 'this'.
17110 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
17111 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
17112 "Unexpected device pointer expression!");
17113 MVLI.VarBaseDeclarations.push_back(
17114 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
17115 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17116 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017117 }
17118
Samuel Antao6890b092016-07-28 14:25:09 +000017119 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000017120 return nullptr;
17121
Michael Kruse4304e9d2019-02-19 16:38:20 +000017122 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
17123 MVLI.VarBaseDeclarations,
17124 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017125}
Alexey Bataeve04483e2019-03-27 14:14:31 +000017126
17127OMPClause *Sema::ActOnOpenMPAllocateClause(
17128 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17129 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
17130 if (Allocator) {
17131 // OpenMP [2.11.4 allocate Clause, Description]
17132 // allocator is an expression of omp_allocator_handle_t type.
17133 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
17134 return nullptr;
17135
17136 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
17137 if (AllocatorRes.isInvalid())
17138 return nullptr;
17139 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
17140 DSAStack->getOMPAllocatorHandleT(),
17141 Sema::AA_Initializing,
17142 /*AllowExplicit=*/true);
17143 if (AllocatorRes.isInvalid())
17144 return nullptr;
17145 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000017146 } else {
17147 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
17148 // allocate clauses that appear on a target construct or on constructs in a
17149 // target region must specify an allocator expression unless a requires
17150 // directive with the dynamic_allocators clause is present in the same
17151 // compilation unit.
17152 if (LangOpts.OpenMPIsDevice &&
17153 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
17154 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017155 }
17156 // Analyze and build list of variables.
17157 SmallVector<Expr *, 8> Vars;
17158 for (Expr *RefExpr : VarList) {
17159 assert(RefExpr && "NULL expr in OpenMP private clause.");
17160 SourceLocation ELoc;
17161 SourceRange ERange;
17162 Expr *SimpleRefExpr = RefExpr;
17163 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17164 if (Res.second) {
17165 // It will be analyzed later.
17166 Vars.push_back(RefExpr);
17167 }
17168 ValueDecl *D = Res.first;
17169 if (!D)
17170 continue;
17171
17172 auto *VD = dyn_cast<VarDecl>(D);
17173 DeclRefExpr *Ref = nullptr;
17174 if (!VD && !CurContext->isDependentContext())
17175 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17176 Vars.push_back((VD || CurContext->isDependentContext())
17177 ? RefExpr->IgnoreParens()
17178 : Ref);
17179 }
17180
17181 if (Vars.empty())
17182 return nullptr;
17183
17184 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
17185 ColonLoc, EndLoc, Vars);
17186}
Alexey Bataevb6e70842019-12-16 15:54:17 -050017187
17188OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
17189 SourceLocation StartLoc,
17190 SourceLocation LParenLoc,
17191 SourceLocation EndLoc) {
17192 SmallVector<Expr *, 8> Vars;
17193 for (Expr *RefExpr : VarList) {
17194 assert(RefExpr && "NULL expr in OpenMP nontemporal 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 ValueDecl *D = Res.first;
17203 if (!D)
17204 continue;
17205
Alexey Bataevb6e70842019-12-16 15:54:17 -050017206 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
17207 // A list-item cannot appear in more than one nontemporal clause.
17208 if (const Expr *PrevRef =
17209 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
17210 Diag(ELoc, diag::err_omp_used_in_clause_twice)
17211 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
17212 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17213 << getOpenMPClauseName(OMPC_nontemporal);
17214 continue;
17215 }
17216
Alexey Bataev0860db92019-12-19 10:01:10 -050017217 Vars.push_back(RefExpr);
Alexey Bataevb6e70842019-12-16 15:54:17 -050017218 }
17219
17220 if (Vars.empty())
17221 return nullptr;
17222
17223 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17224 Vars);
17225}