blob: 832f03b93942e90863de41c3e7b66ccb56a95caa [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//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
44/// \brief Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000046 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000048 DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
49};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Alexey Bataev758e55e2013-09-06 18:03:48 +000057/// \brief Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000059class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataeve3727102018-04-18 15:57:46 +000061 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000062 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000064 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000071 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000073 };
Alexey Bataeve3727102018-04-18 15:57:46 +000074 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey 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>;
86 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
87 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>>;
100 using DoacrossDependMapTy =
101 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
Alexey Bataeve3727102018-04-18 15:57:46 +0000119 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000121 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000122 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000123 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000124 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000129 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000137 /// \brief first argument (Expr *) contains optional argument of the
138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
Alexey Bataeve3727102018-04-18 15:57:46 +0000140 llvm::PointerIntPair<const Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000141 bool NowaitRegion = false;
142 bool CancelRegion = false;
143 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000144 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000145 /// Reference to the taskgroup task_reduction reference expression.
146 Expr *TaskgroupReductionRef = nullptr;
Alexey Bataeved09d242014-05-28 05:53:51 +0000147 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000148 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000149 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
150 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000151 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000152 };
153
Alexey Bataeve3727102018-04-18 15:57:46 +0000154 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000155
156 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000157 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000158 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
159 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000160 /// \brief true, if check for DSA must be from parent directive, false, if
161 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000162 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000163 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000164 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000165 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000166
Alexey Bataeve3727102018-04-18 15:57:46 +0000167 using iterator = StackTy::const_reverse_iterator;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000168
Alexey Bataeve3727102018-04-18 15:57:46 +0000169 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
Alexey Bataevec3da872014-01-31 05:15:34 +0000170
171 /// \brief Checks if the variable is a local for OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000172 bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
Alexey Bataeved09d242014-05-28 05:53:51 +0000173
Alexey Bataev4b465392017-04-26 15:06:24 +0000174 bool isStackEmpty() const {
175 return Stack.empty() ||
176 Stack.back().second != CurrentNonCapturingFunctionScope ||
177 Stack.back().first.empty();
178 }
179
Alexey Bataev758e55e2013-09-06 18:03:48 +0000180public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000181 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000182
Alexey Bataevaac108a2015-06-23 04:51:00 +0000183 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000184 OpenMPClauseKind getClauseParsingMode() const {
185 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
186 return ClauseKindMode;
187 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000188 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000189
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000190 bool isForceVarCapturing() const { return ForceCapturing; }
191 void setForceVarCapturing(bool V) { ForceCapturing = V; }
192
Alexey Bataev758e55e2013-09-06 18:03:48 +0000193 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000194 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000195 if (Stack.empty() ||
196 Stack.back().second != CurrentNonCapturingFunctionScope)
197 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
198 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
199 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000200 }
201
202 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000203 assert(!Stack.back().first.empty() &&
204 "Data-sharing attributes stack is empty!");
205 Stack.back().first.pop_back();
206 }
207
208 /// Start new OpenMP region stack in new non-capturing function.
209 void pushFunction() {
210 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
211 assert(!isa<CapturingScopeInfo>(CurFnScope));
212 CurrentNonCapturingFunctionScope = CurFnScope;
213 }
214 /// Pop region stack for non-capturing function.
215 void popFunction(const FunctionScopeInfo *OldFSI) {
216 if (!Stack.empty() && Stack.back().second == OldFSI) {
217 assert(Stack.back().first.empty());
218 Stack.pop_back();
219 }
220 CurrentNonCapturingFunctionScope = nullptr;
221 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
222 if (!isa<CapturingScopeInfo>(FSI)) {
223 CurrentNonCapturingFunctionScope = FSI;
224 break;
225 }
226 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000227 }
228
Alexey Bataeve3727102018-04-18 15:57:46 +0000229 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000230 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000231 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000232 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000233 getCriticalWithHint(const DeclarationNameInfo &Name) const {
234 auto I = Criticals.find(Name.getAsString());
235 if (I != Criticals.end())
236 return I->second;
237 return std::make_pair(nullptr, llvm::APSInt());
238 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000239 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000240 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000241 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000242 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000243
Alexey Bataev9c821032015-04-30 04:23:23 +0000244 /// \brief Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000245 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000246 /// \brief Check if the specified variable is a loop control variable for
247 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000248 /// \return The index of the loop control variable in the list of associated
249 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000250 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000251 /// \brief Check if the specified variable is a loop control variable for
252 /// parent region.
253 /// \return The index of the loop control variable in the list of associated
254 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000255 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000256 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
257 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000258 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000259
Alexey Bataev758e55e2013-09-06 18:03:48 +0000260 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000261 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000262 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000263
Alexey Bataevfa312f32017-07-21 18:48:21 +0000264 /// Adds additional information for the reduction items with the reduction id
265 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000266 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000267 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000268 /// Adds additional information for the reduction items with the reduction id
269 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000270 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000271 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000272 /// Returns the location and reduction operation from the innermost parent
273 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000274 const DSAVarData
275 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
276 BinaryOperatorKind &BOK,
277 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000278 /// Returns the location and reduction operation from the innermost parent
279 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000280 const DSAVarData
281 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
282 const Expr *&ReductionRef,
283 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000284 /// Return reduction reference expression for the current taskgroup.
285 Expr *getTaskgroupReductionRef() const {
286 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
287 "taskgroup reference expression requested for non taskgroup "
288 "directive.");
289 return Stack.back().first.back().TaskgroupReductionRef;
290 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000291 /// Checks if the given \p VD declaration is actually a taskgroup reduction
292 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000293 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Alexey Bataev88202be2017-07-27 13:20:36 +0000294 return Stack.back().first[Level].TaskgroupReductionRef &&
295 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
296 ->getDecl() == VD;
297 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000298
Alexey Bataev758e55e2013-09-06 18:03:48 +0000299 /// \brief Returns data sharing attributes from top of the stack for the
300 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000301 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000302 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000303 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Alexey Bataevf29276e2014-06-18 04:14:57 +0000304 /// \brief Checks if the specified variables has data-sharing attributes which
305 /// match specified \a CPred predicate in any directive which matches \a DPred
306 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000307 const DSAVarData
308 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
309 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
310 bool FromParent) const;
Alexey Bataevf29276e2014-06-18 04:14:57 +0000311 /// \brief Checks if the specified variables has data-sharing attributes which
312 /// match specified \a CPred predicate in any innermost directive which
313 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000314 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000315 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000316 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
317 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000318 bool FromParent) const;
Alexey Bataevaac108a2015-06-23 04:51:00 +0000319 /// \brief Checks if the specified variables has explicit data-sharing
320 /// attributes which match specified \a CPred predicate at the specified
321 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000322 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000323 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000324 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000325
326 /// \brief Returns true if the directive at level \Level matches in the
327 /// specified \a DPred predicate.
328 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000329 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000330 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000331
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000332 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000333 bool hasDirective(
334 const llvm::function_ref<bool(
335 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
336 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000337 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000338
Alexey Bataev758e55e2013-09-06 18:03:48 +0000339 /// \brief Returns currently analyzed directive.
340 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000341 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000342 }
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000343 /// \brief Returns directive kind at specified level.
344 OpenMPDirectiveKind getDirective(unsigned Level) const {
345 assert(!isStackEmpty() && "No directive at specified level.");
346 return Stack.back().first[Level].Directive;
347 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000348 /// \brief Returns parent directive.
349 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000350 if (isStackEmpty() || Stack.back().first.size() == 1)
351 return OMPD_unknown;
352 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000353 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000354
355 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000356 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000357 assert(!isStackEmpty());
358 Stack.back().first.back().DefaultAttr = DSA_none;
359 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000360 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000361 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000362 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000363 assert(!isStackEmpty());
364 Stack.back().first.back().DefaultAttr = DSA_shared;
365 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000366 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000367 /// Set default data mapping attribute to 'tofrom:scalar'.
368 void setDefaultDMAToFromScalar(SourceLocation Loc) {
369 assert(!isStackEmpty());
370 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
371 Stack.back().first.back().DefaultMapAttrLoc = Loc;
372 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000373
374 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000375 return isStackEmpty() ? DSA_unspecified
376 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000377 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000378 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000379 return isStackEmpty() ? SourceLocation()
380 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000381 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000382 DefaultMapAttributes getDefaultDMA() const {
383 return isStackEmpty() ? DMA_unspecified
384 : Stack.back().first.back().DefaultMapAttr;
385 }
386 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
387 return Stack.back().first[Level].DefaultMapAttr;
388 }
389 SourceLocation getDefaultDMALocation() const {
390 return isStackEmpty() ? SourceLocation()
391 : Stack.back().first.back().DefaultMapAttrLoc;
392 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000393
Alexey Bataevf29276e2014-06-18 04:14:57 +0000394 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000395 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000396 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000397 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000398 }
399
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000400 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataeve3727102018-04-18 15:57:46 +0000401 void setOrderedRegion(bool IsOrdered, const Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000402 assert(!isStackEmpty());
403 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
404 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000405 }
406 /// \brief Returns true, if parent region is ordered (has associated
407 /// 'ordered' clause), false - otherwise.
408 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000409 if (isStackEmpty() || Stack.back().first.size() == 1)
410 return false;
411 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000412 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000413 /// \brief Returns optional parameter for the ordered region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000414 const Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000415 if (isStackEmpty() || Stack.back().first.size() == 1)
416 return nullptr;
417 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000418 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000419 /// \brief Marks current region as nowait (it has a 'nowait' clause).
420 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000421 assert(!isStackEmpty());
422 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000423 }
424 /// \brief Returns true, if parent region is nowait (has associated
425 /// 'nowait' clause), false - otherwise.
426 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000427 if (isStackEmpty() || Stack.back().first.size() == 1)
428 return false;
429 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000430 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000431 /// \brief Marks parent region as cancel region.
432 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000433 if (!isStackEmpty() && Stack.back().first.size() > 1) {
434 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
435 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
436 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000437 }
438 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000439 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000440 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000441 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000442
Alexey Bataev9c821032015-04-30 04:23:23 +0000443 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000444 void setAssociatedLoops(unsigned Val) {
445 assert(!isStackEmpty());
446 Stack.back().first.back().AssociatedLoops = Val;
447 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000448 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000449 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000450 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000451 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000452
Alexey Bataev13314bf2014-10-09 04:18:56 +0000453 /// \brief Marks current target region as one with closely nested teams
454 /// region.
455 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000456 if (!isStackEmpty() && Stack.back().first.size() > 1) {
457 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
458 TeamsRegionLoc;
459 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000460 }
461 /// \brief Returns true, if current region has closely nested teams region.
462 bool hasInnerTeamsRegion() const {
463 return getInnerTeamsRegionLoc().isValid();
464 }
465 /// \brief Returns location of the nested teams region (if any).
466 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000467 return isStackEmpty() ? SourceLocation()
468 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000469 }
470
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000471 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000472 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000473 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000474 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000475 return isStackEmpty() ? SourceLocation()
476 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000477 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000478
Samuel Antao4c8035b2016-12-12 18:00:20 +0000479 /// Do the check specified in \a Check to all component lists and return true
480 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000481 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000482 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000483 const llvm::function_ref<
484 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000485 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000486 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000487 if (isStackEmpty())
488 return false;
489 auto SI = Stack.back().first.rbegin();
490 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000491
492 if (SI == SE)
493 return false;
494
Alexey Bataeve3727102018-04-18 15:57:46 +0000495 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000496 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000497 else
498 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000499
500 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000501 auto MI = SI->MappedExprComponents.find(VD);
502 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000503 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
504 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000505 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000506 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000507 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000508 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000509 }
510
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000511 /// Do the check specified in \a Check to all component lists at a given level
512 /// and return true if any issue is found.
513 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000514 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000515 const llvm::function_ref<
516 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000517 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000518 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000519 if (isStackEmpty())
520 return false;
521
522 auto StartI = Stack.back().first.begin();
523 auto EndI = Stack.back().first.end();
524 if (std::distance(StartI, EndI) <= (int)Level)
525 return false;
526 std::advance(StartI, Level);
527
528 auto MI = StartI->MappedExprComponents.find(VD);
529 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000530 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
531 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000532 if (Check(L, MI->second.Kind))
533 return true;
534 return false;
535 }
536
Samuel Antao4c8035b2016-12-12 18:00:20 +0000537 /// Create a new mappable expression component list associated with a given
538 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000539 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000540 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000541 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
542 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000543 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000544 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000545 MappedExprComponentTy &MEC =
546 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000547 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000548 MEC.Components.resize(MEC.Components.size() + 1);
549 MEC.Components.back().append(Components.begin(), Components.end());
550 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000551 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000552
553 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000554 assert(!isStackEmpty());
555 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000556 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000557 void addDoacrossDependClause(OMPDependClause *C,
558 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000559 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000560 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000561 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000562 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000563 }
564 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
565 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000566 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000567 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000568 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000569 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000570 return llvm::make_range(Ref.begin(), Ref.end());
571 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000572 return llvm::make_range(StackElem.DoacrossDepends.end(),
573 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000574 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000575};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000576bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000577 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
578 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000579}
Alexey Bataeve3727102018-04-18 15:57:46 +0000580
Alexey Bataeved09d242014-05-28 05:53:51 +0000581} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000582
Alexey Bataeve3727102018-04-18 15:57:46 +0000583static const Expr *getExprAsWritten(const Expr *E) {
584 if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000585 E = ExprTemp->getSubExpr();
586
Alexey Bataeve3727102018-04-18 15:57:46 +0000587 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000588 E = MTE->GetTemporaryExpr();
589
Alexey Bataeve3727102018-04-18 15:57:46 +0000590 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000591 E = Binder->getSubExpr();
592
Alexey Bataeve3727102018-04-18 15:57:46 +0000593 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000594 E = ICE->getSubExprAsWritten();
595 return E->IgnoreParens();
596}
597
Alexey Bataeve3727102018-04-18 15:57:46 +0000598static Expr *getExprAsWritten(Expr *E) {
599 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
600}
601
602static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
603 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
604 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000605 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000606 const auto *VD = dyn_cast<VarDecl>(D);
607 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000608 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000609 VD = VD->getCanonicalDecl();
610 D = VD;
611 } else {
612 assert(FD);
613 FD = FD->getCanonicalDecl();
614 D = FD;
615 }
616 return D;
617}
618
Alexey Bataeve3727102018-04-18 15:57:46 +0000619static ValueDecl *getCanonicalDecl(ValueDecl *D) {
620 return const_cast<ValueDecl *>(
621 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
622}
623
624DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
625 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000626 D = getCanonicalDecl(D);
627 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000628 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000629 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000630 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000631 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
632 // in a region but not in construct]
633 // File-scope or namespace-scope variables referenced in called routines
634 // in the region are shared unless they appear in a threadprivate
635 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000636 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000637 DVar.CKind = OMPC_shared;
638
639 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
640 // in a region but not in construct]
641 // Variables with static storage duration that are declared in called
642 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000643 if (VD && VD->hasGlobalStorage())
644 DVar.CKind = OMPC_shared;
645
646 // Non-static data members are shared by default.
647 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000648 DVar.CKind = OMPC_shared;
649
Alexey Bataev758e55e2013-09-06 18:03:48 +0000650 return DVar;
651 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000652
Alexey Bataevec3da872014-01-31 05:15:34 +0000653 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
654 // in a Construct, C/C++, predetermined, p.1]
655 // Variables with automatic storage duration that are declared in a scope
656 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
658 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000659 DVar.CKind = OMPC_private;
660 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000661 }
662
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000663 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000664 // Explicitly specified attributes and local variables with predetermined
665 // attributes.
666 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000667 const DSAInfo &Data = Iter->SharingMap.lookup(D);
668 DVar.RefExpr = Data.RefExpr.getPointer();
669 DVar.PrivateCopy = Data.PrivateCopy;
670 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000671 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000672 return DVar;
673 }
674
675 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
676 // in a Construct, C/C++, implicitly determined, p.1]
677 // In a parallel or task construct, the data-sharing attributes of these
678 // variables are determined by the default clause, if present.
679 switch (Iter->DefaultAttr) {
680 case DSA_shared:
681 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000682 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000683 return DVar;
684 case DSA_none:
685 return DVar;
686 case DSA_unspecified:
687 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
688 // in a Construct, implicitly determined, p.2]
689 // In a parallel construct, if no default clause is present, these
690 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000691 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000692 if (isOpenMPParallelDirective(DVar.DKind) ||
693 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 DVar.CKind = OMPC_shared;
695 return DVar;
696 }
697
698 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
699 // in a Construct, implicitly determined, p.4]
700 // In a task construct, if no default clause is present, a variable that in
701 // the enclosing context is determined to be shared by all implicit tasks
702 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000703 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000704 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000705 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000706 do {
707 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000708 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000709 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000710 // In a task construct, if no default clause is present, a variable
711 // whose data-sharing attribute is not determined by the rules above is
712 // firstprivate.
713 DVarTemp = getDSA(I, D);
714 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000715 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000717 return DVar;
718 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000719 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000720 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000721 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000722 return DVar;
723 }
724 }
725 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
726 // in a Construct, implicitly determined, p.3]
727 // For constructs other than task, if no default clause is present, these
728 // variables inherit their data-sharing attributes from the enclosing
729 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000730 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000731}
732
Alexey Bataeve3727102018-04-18 15:57:46 +0000733const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
734 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000735 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000736 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000737 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000738 auto It = StackElem.AlignedMap.find(D);
739 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000740 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000741 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000742 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000743 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000744 assert(It->second && "Unexpected nullptr expr in the aligned map");
745 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000746}
747
Alexey Bataeve3727102018-04-18 15:57:46 +0000748void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000749 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000750 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000751 SharingMapTy &StackElem = Stack.back().first.back();
752 StackElem.LCVMap.try_emplace(
753 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000754}
755
Alexey Bataeve3727102018-04-18 15:57:46 +0000756const DSAStackTy::LCDeclInfo
757DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000758 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000759 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000760 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000761 auto It = StackElem.LCVMap.find(D);
762 if (It != StackElem.LCVMap.end())
763 return It->second;
764 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000765}
766
Alexey Bataeve3727102018-04-18 15:57:46 +0000767const DSAStackTy::LCDeclInfo
768DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000769 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
770 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000771 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000772 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000773 auto It = StackElem.LCVMap.find(D);
774 if (It != StackElem.LCVMap.end())
775 return It->second;
776 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000777}
778
Alexey Bataeve3727102018-04-18 15:57:46 +0000779const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000780 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
781 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000782 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000783 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000784 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000785 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000786 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000787 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000788 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000789}
790
Alexey Bataeve3727102018-04-18 15:57:46 +0000791void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000792 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000794 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000795 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000796 Data.Attributes = A;
797 Data.RefExpr.setPointer(E);
798 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000799 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000800 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000801 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000802 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
803 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
804 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
805 (isLoopControlVariable(D).first && A == OMPC_private));
806 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
807 Data.RefExpr.setInt(/*IntVal=*/true);
808 return;
809 }
810 const bool IsLastprivate =
811 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
812 Data.Attributes = A;
813 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
814 Data.PrivateCopy = PrivateCopy;
815 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000816 DSAInfo &Data =
817 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000818 Data.Attributes = A;
819 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
820 Data.PrivateCopy = nullptr;
821 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000822 }
823}
824
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000825/// \brief Build a variable declaration for OpenMP loop iteration variable.
826static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000827 StringRef Name, const AttrVec *Attrs = nullptr,
828 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000829 DeclContext *DC = SemaRef.CurContext;
830 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
831 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +0000832 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000833 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
834 if (Attrs) {
835 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
836 I != E; ++I)
837 Decl->addAttr(*I);
838 }
839 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000840 if (OrigRef) {
841 Decl->addAttr(
842 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
843 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000844 return Decl;
845}
846
847static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
848 SourceLocation Loc,
849 bool RefersToCapture = false) {
850 D->setReferenced();
851 D->markUsed(S.Context);
852 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
853 SourceLocation(), D, RefersToCapture, Loc, Ty,
854 VK_LValue);
855}
856
Alexey Bataeve3727102018-04-18 15:57:46 +0000857void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000858 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000859 D = getCanonicalDecl(D);
860 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000861 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000862 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000863 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000864 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000865 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000866 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000867 "Additional reduction info may be specified only once for reduction "
868 "items.");
869 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000870 Expr *&TaskgroupReductionRef =
871 Stack.back().first.back().TaskgroupReductionRef;
872 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000873 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
874 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000875 TaskgroupReductionRef =
876 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000877 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000878}
879
Alexey Bataeve3727102018-04-18 15:57:46 +0000880void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000881 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000882 D = getCanonicalDecl(D);
883 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000884 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000885 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000886 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000887 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000888 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000889 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000890 "Additional reduction info may be specified only once for reduction "
891 "items.");
892 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000893 Expr *&TaskgroupReductionRef =
894 Stack.back().first.back().TaskgroupReductionRef;
895 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000896 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
897 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000898 TaskgroupReductionRef =
899 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000900 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000901}
902
Alexey Bataeve3727102018-04-18 15:57:46 +0000903const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
904 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
905 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000906 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000907 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
908 if (Stack.back().first.empty())
909 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +0000910 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
911 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000912 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000913 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000914 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000915 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +0000916 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000917 if (!ReductionData.ReductionOp ||
918 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000919 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000920 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000921 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000922 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
923 "expression for the descriptor is not "
924 "set.");
925 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000926 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
927 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000928 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000929 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000930}
931
Alexey Bataeve3727102018-04-18 15:57:46 +0000932const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
933 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
934 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000935 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000936 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
937 if (Stack.back().first.empty())
938 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +0000939 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
940 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000941 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000942 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000943 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000944 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +0000945 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000946 if (!ReductionData.ReductionOp ||
947 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000948 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000949 SR = ReductionData.ReductionRange;
950 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000951 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
952 "expression for the descriptor is not "
953 "set.");
954 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000955 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
956 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000957 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000958 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000959}
960
Alexey Bataeve3727102018-04-18 15:57:46 +0000961bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000962 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +0000963 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000964 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000965 Scope *TopScope = nullptr;
Alexey Bataev852525d2018-03-02 17:17:12 +0000966 while (I != E && !isParallelOrTaskRegion(I->Directive) &&
967 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000968 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000969 if (I == E)
970 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000971 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000972 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000973 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000974 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000975 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000976 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000977 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000978}
979
Alexey Bataeve3727102018-04-18 15:57:46 +0000980const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
981 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000982 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000983 DSAVarData DVar;
984
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000985 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000986 auto TI = Threadprivates.find(D);
987 if (TI != Threadprivates.end()) {
988 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000989 DVar.CKind = OMPC_threadprivate;
990 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +0000991 }
992 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +0000993 DVar.RefExpr = buildDeclRefExpr(
994 SemaRef, VD, D->getType().getNonReferenceType(),
995 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
996 DVar.CKind = OMPC_threadprivate;
997 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +0000998 return DVar;
999 }
1000 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1001 // in a Construct, C/C++, predetermined, p.1]
1002 // Variables appearing in threadprivate directives are threadprivate.
1003 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1004 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1005 SemaRef.getLangOpts().OpenMPUseTLS &&
1006 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1007 (VD && VD->getStorageClass() == SC_Register &&
1008 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1009 DVar.RefExpr = buildDeclRefExpr(
1010 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1011 DVar.CKind = OMPC_threadprivate;
1012 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1013 return DVar;
1014 }
1015 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1016 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1017 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001018 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001019 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1020 [](const SharingMapTy &Data) {
1021 return isOpenMPTargetExecutionDirective(Data.Directive);
1022 });
1023 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001024 iterator ParentIterTarget = std::next(IterTarget, 1);
1025 for (iterator Iter = Stack.back().first.rbegin();
1026 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001027 if (isOpenMPLocal(VD, Iter)) {
1028 DVar.RefExpr =
1029 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1030 D->getLocation());
1031 DVar.CKind = OMPC_threadprivate;
1032 return DVar;
1033 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001034 }
1035 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1036 auto DSAIter = IterTarget->SharingMap.find(D);
1037 if (DSAIter != IterTarget->SharingMap.end() &&
1038 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1039 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1040 DVar.CKind = OMPC_threadprivate;
1041 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001042 }
1043 iterator End = Stack.back().first.rend();
1044 if (!SemaRef.isOpenMPCapturedByRef(
1045 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001046 DVar.RefExpr =
1047 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1048 IterTarget->ConstructLoc);
1049 DVar.CKind = OMPC_threadprivate;
1050 return DVar;
1051 }
1052 }
1053 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054 }
1055
Alexey Bataev4b465392017-04-26 15:06:24 +00001056 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001057 // Not in OpenMP execution region and top scope was already checked.
1058 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001059
Alexey Bataev758e55e2013-09-06 18:03:48 +00001060 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001061 // in a Construct, C/C++, predetermined, p.4]
1062 // Static data members are shared.
1063 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1064 // in a Construct, C/C++, predetermined, p.7]
1065 // Variables with static storage duration that are declared in a scope
1066 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001067 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001068 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001069 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001070 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001071 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001072
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001073 DVar.CKind = OMPC_shared;
1074 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001075 }
1076
1077 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00001078 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1079 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001080 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1081 // in a Construct, C/C++, predetermined, p.6]
1082 // Variables with const qualified type having no mutable member are
1083 // shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001084 const CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001085 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00001086 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1087 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001088 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001089 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001090 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1091 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001092 // Variables with const-qualified type having no mutable member may be
1093 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataeve3727102018-04-18 15:57:46 +00001094 DSAVarData DVarTemp =
1095 hasDSA(D, [](OpenMPClauseKind C) { return C == OMPC_firstprivate; },
1096 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001097 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
Alexey Bataev9a757382018-02-16 19:16:54 +00001098 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001099
Alexey Bataev758e55e2013-09-06 18:03:48 +00001100 DVar.CKind = OMPC_shared;
1101 return DVar;
1102 }
1103
Alexey Bataev758e55e2013-09-06 18:03:48 +00001104 // Explicitly specified attributes and local variables with predetermined
1105 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001106 iterator I = Stack.back().first.rbegin();
1107 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001108 if (FromParent && I != EndI)
1109 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001110 auto It = I->SharingMap.find(D);
1111 if (It != I->SharingMap.end()) {
1112 const DSAInfo &Data = It->getSecond();
1113 DVar.RefExpr = Data.RefExpr.getPointer();
1114 DVar.PrivateCopy = Data.PrivateCopy;
1115 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001116 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001117 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001118 }
1119
1120 return DVar;
1121}
1122
Alexey Bataeve3727102018-04-18 15:57:46 +00001123const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1124 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001125 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001126 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001127 return getDSA(I, D);
1128 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001129 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001130 iterator StartI = Stack.back().first.rbegin();
1131 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001132 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001133 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001134 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001135}
1136
Alexey Bataeve3727102018-04-18 15:57:46 +00001137const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001138DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001139 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1140 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001141 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001142 if (isStackEmpty())
1143 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001144 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001145 iterator I = Stack.back().first.rbegin();
1146 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001147 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001148 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001149 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001150 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001151 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001152 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001153 DSAVarData DVar = getDSA(NewI, D);
1154 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001155 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001156 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001157 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001158}
1159
Alexey Bataeve3727102018-04-18 15:57:46 +00001160const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001161 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1162 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001163 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001164 if (isStackEmpty())
1165 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001166 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001167 iterator StartI = Stack.back().first.rbegin();
1168 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001169 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001170 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001171 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001172 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001173 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001174 DSAVarData DVar = getDSA(NewI, D);
1175 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001176}
1177
Alexey Bataevaac108a2015-06-23 04:51:00 +00001178bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001179 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1180 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001181 if (isStackEmpty())
1182 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001183 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001184 auto StartI = Stack.back().first.begin();
1185 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001186 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001187 return false;
1188 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001189 auto I = StartI->SharingMap.find(D);
1190 return (I != StartI->SharingMap.end()) &&
1191 I->getSecond().RefExpr.getPointer() &&
1192 CPred(I->getSecond().Attributes) &&
1193 (!NotLastprivate || !I->getSecond().RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001194}
1195
Samuel Antao4be30e92015-10-02 17:14:03 +00001196bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001197 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1198 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001199 if (isStackEmpty())
1200 return false;
1201 auto StartI = Stack.back().first.begin();
1202 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001203 if (std::distance(StartI, EndI) <= (int)Level)
1204 return false;
1205 std::advance(StartI, Level);
1206 return DPred(StartI->Directive);
1207}
1208
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001209bool DSAStackTy::hasDirective(
1210 const llvm::function_ref<bool(OpenMPDirectiveKind,
1211 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001212 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001213 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001214 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001215 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001216 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001217 auto StartI = std::next(Stack.back().first.rbegin());
1218 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001219 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001220 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001221 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1222 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1223 return true;
1224 }
1225 return false;
1226}
1227
Alexey Bataev758e55e2013-09-06 18:03:48 +00001228void Sema::InitDataSharingAttributesStack() {
1229 VarDataSharingAttributesStack = new DSAStackTy(*this);
1230}
1231
1232#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1233
Alexey Bataev4b465392017-04-26 15:06:24 +00001234void Sema::pushOpenMPFunctionRegion() {
1235 DSAStack->pushFunction();
1236}
1237
1238void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1239 DSAStack->popFunction(OldFSI);
1240}
1241
Alexey Bataev92327c52018-03-26 16:40:55 +00001242static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
1243isDeclareTargetDeclaration(const ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001244 for (const Decl *D : VD->redecls()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00001245 if (!D->hasAttrs())
1246 continue;
1247 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
1248 return Attr->getMapType();
1249 }
1250 return llvm::None;
1251}
1252
Alexey Bataeve3727102018-04-18 15:57:46 +00001253bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001254 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1255
Alexey Bataeve3727102018-04-18 15:57:46 +00001256 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001257 bool IsByRef = true;
1258
1259 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001260 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001261 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001262
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001263 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001264 // This table summarizes how a given variable should be passed to the device
1265 // given its type and the clauses where it appears. This table is based on
1266 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1267 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1268 //
1269 // =========================================================================
1270 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1271 // | |(tofrom:scalar)| | pvt | | | |
1272 // =========================================================================
1273 // | scl | | | | - | | bycopy|
1274 // | scl | | - | x | - | - | bycopy|
1275 // | scl | | x | - | - | - | null |
1276 // | scl | x | | | - | | byref |
1277 // | scl | x | - | x | - | - | bycopy|
1278 // | scl | x | x | - | - | - | null |
1279 // | scl | | - | - | - | x | byref |
1280 // | scl | x | - | - | - | x | byref |
1281 //
1282 // | agg | n.a. | | | - | | byref |
1283 // | agg | n.a. | - | x | - | - | byref |
1284 // | agg | n.a. | x | - | - | - | null |
1285 // | agg | n.a. | - | - | - | x | byref |
1286 // | agg | n.a. | - | - | - | x[] | byref |
1287 //
1288 // | ptr | n.a. | | | - | | bycopy|
1289 // | ptr | n.a. | - | x | - | - | bycopy|
1290 // | ptr | n.a. | x | - | - | - | null |
1291 // | ptr | n.a. | - | - | - | x | byref |
1292 // | ptr | n.a. | - | - | - | x[] | bycopy|
1293 // | ptr | n.a. | - | - | x | | bycopy|
1294 // | ptr | n.a. | - | - | x | x | bycopy|
1295 // | ptr | n.a. | - | - | x | x[] | bycopy|
1296 // =========================================================================
1297 // Legend:
1298 // scl - scalar
1299 // ptr - pointer
1300 // agg - aggregate
1301 // x - applies
1302 // - - invalid in this combination
1303 // [] - mapped with an array section
1304 // byref - should be mapped by reference
1305 // byval - should be mapped by value
1306 // null - initialize a local variable to null on the device
1307 //
1308 // Observations:
1309 // - All scalar declarations that show up in a map clause have to be passed
1310 // by reference, because they may have been mapped in the enclosing data
1311 // environment.
1312 // - If the scalar value does not fit the size of uintptr, it has to be
1313 // passed by reference, regardless the result in the table above.
1314 // - For pointers mapped by value that have either an implicit map or an
1315 // array section, the runtime library may pass the NULL value to the
1316 // device instead of the value passed to it by the compiler.
1317
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001318 if (Ty->isReferenceType())
1319 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001320
1321 // Locate map clauses and see if the variable being captured is referred to
1322 // in any of those clauses. Here we only care about variables, not fields,
1323 // because fields are part of aggregates.
1324 bool IsVariableUsedInMapClause = false;
1325 bool IsVariableAssociatedWithSection = false;
1326
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001327 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001328 D, Level,
1329 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1330 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001331 MapExprComponents,
1332 OpenMPClauseKind WhereFoundClauseKind) {
1333 // Only the map clause information influences how a variable is
1334 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001335 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001336 if (WhereFoundClauseKind != OMPC_map)
1337 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001338
1339 auto EI = MapExprComponents.rbegin();
1340 auto EE = MapExprComponents.rend();
1341
1342 assert(EI != EE && "Invalid map expression!");
1343
1344 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1345 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1346
1347 ++EI;
1348 if (EI == EE)
1349 return false;
1350
1351 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1352 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1353 isa<MemberExpr>(EI->getAssociatedExpression())) {
1354 IsVariableAssociatedWithSection = true;
1355 // There is nothing more we need to know about this variable.
1356 return true;
1357 }
1358
1359 // Keep looking for more map info.
1360 return false;
1361 });
1362
1363 if (IsVariableUsedInMapClause) {
1364 // If variable is identified in a map clause it is always captured by
1365 // reference except if it is a pointer that is dereferenced somehow.
1366 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1367 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001368 // By default, all the data that has a scalar type is mapped by copy
1369 // (except for reduction variables).
1370 IsByRef =
1371 !Ty->isScalarType() ||
1372 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1373 DSAStack->hasExplicitDSA(
1374 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001375 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001376 }
1377
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001378 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001379 IsByRef =
1380 !DSAStack->hasExplicitDSA(
1381 D,
1382 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1383 Level, /*NotLastprivate=*/true) &&
1384 // If the variable is artificial and must be captured by value - try to
1385 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001386 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1387 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001388 }
1389
Samuel Antao86ace552016-04-27 22:40:57 +00001390 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001391 // and alignment, because the runtime library only deals with uintptr types.
1392 // If it does not fit the uintptr size, we need to pass the data by reference
1393 // instead.
1394 if (!IsByRef &&
1395 (Ctx.getTypeSizeInChars(Ty) >
1396 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001397 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001398 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001399 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001400
1401 return IsByRef;
1402}
1403
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001404unsigned Sema::getOpenMPNestingLevel() const {
1405 assert(getLangOpts().OpenMP);
1406 return DSAStack->getNestingLevel();
1407}
1408
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001409bool Sema::isInOpenMPTargetExecutionDirective() const {
1410 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1411 !DSAStack->isClauseParsingMode()) ||
1412 DSAStack->hasDirective(
1413 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1414 SourceLocation) -> bool {
1415 return isOpenMPTargetExecutionDirective(K);
1416 },
1417 false);
1418}
1419
Alexey Bataeve3727102018-04-18 15:57:46 +00001420VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) const {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001421 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001422 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001423
1424 // If we are attempting to capture a global variable in a directive with
1425 // 'target' we return true so that this global is also mapped to the device.
1426 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001427 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001428 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective()) {
1429 // If the declaration is enclosed in a 'declare target' directive,
1430 // then it should not be captured.
1431 //
Alexey Bataev92327c52018-03-26 16:40:55 +00001432 if (isDeclareTargetDeclaration(VD))
1433 return nullptr;
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001434 return VD;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001435 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001436
Alexey Bataev48977c32015-08-04 08:10:48 +00001437 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1438 (!DSAStack->isClauseParsingMode() ||
1439 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001440 auto &&Info = DSAStack->isLoopControlVariable(D);
1441 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001443 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001445 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001446 DSAStackTy::DSAVarData DVarPrivate =
1447 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001448 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001449 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001450 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1451 [](OpenMPDirectiveKind) { return true; },
1452 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001453 if (DVarPrivate.CKind != OMPC_unknown)
1454 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001455 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001456 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001457}
1458
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001459void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1460 unsigned Level) const {
1461 SmallVector<OpenMPDirectiveKind, 4> Regions;
1462 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1463 FunctionScopesIndex -= Regions.size();
1464}
1465
Alexey Bataeve3727102018-04-18 15:57:46 +00001466bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001467 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1468 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001469 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001470 (DSAStack->isClauseParsingMode() &&
1471 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001472 // Consider taskgroup reduction descriptor variable a private to avoid
1473 // possible capture in the region.
1474 (DSAStack->hasExplicitDirective(
1475 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1476 Level) &&
1477 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001478}
1479
Alexey Bataeve3727102018-04-18 15:57:46 +00001480void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1481 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001482 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1483 D = getCanonicalDecl(D);
1484 OpenMPClauseKind OMPC = OMPC_unknown;
1485 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1486 const unsigned NewLevel = I - 1;
1487 if (DSAStack->hasExplicitDSA(D,
1488 [&OMPC](const OpenMPClauseKind K) {
1489 if (isOpenMPPrivate(K)) {
1490 OMPC = K;
1491 return true;
1492 }
1493 return false;
1494 },
1495 NewLevel))
1496 break;
1497 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1498 D, NewLevel,
1499 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1500 OpenMPClauseKind) { return true; })) {
1501 OMPC = OMPC_map;
1502 break;
1503 }
1504 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1505 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001506 OMPC = OMPC_map;
1507 if (D->getType()->isScalarType() &&
1508 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1509 DefaultMapAttributes::DMA_tofrom_scalar)
1510 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001511 break;
1512 }
1513 }
1514 if (OMPC != OMPC_unknown)
1515 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1516}
1517
Alexey Bataeve3727102018-04-18 15:57:46 +00001518bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1519 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001520 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1521 // Return true if the current level is no longer enclosed in a target region.
1522
Alexey Bataeve3727102018-04-18 15:57:46 +00001523 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001525 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1526 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001527}
1528
Alexey Bataeved09d242014-05-28 05:53:51 +00001529void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001530
1531void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1532 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001533 Scope *CurScope, SourceLocation Loc) {
1534 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001535 PushExpressionEvaluationContext(
1536 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001537}
1538
Alexey Bataevaac108a2015-06-23 04:51:00 +00001539void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1540 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001541}
1542
Alexey Bataevaac108a2015-06-23 04:51:00 +00001543void Sema::EndOpenMPClause() {
1544 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001545}
1546
Alexey Bataev758e55e2013-09-06 18:03:48 +00001547void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001548 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1549 // A variable of class type (or array thereof) that appears in a lastprivate
1550 // clause requires an accessible, unambiguous default constructor for the
1551 // class type, unless the list item is also specified in a firstprivate
1552 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001553 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1554 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001555 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1556 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001557 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001558 if (DE->isValueDependent() || DE->isTypeDependent()) {
1559 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001560 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001561 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001562 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001563 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001564 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001565 const DSAStackTy::DSAVarData DVar =
1566 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001567 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001568 // Generate helper private variable and initialize it with the
1569 // default value. The address of the original variable is replaced
1570 // by the address of the new private variable in CodeGen. This new
1571 // variable is not added to IdResolver, so the code in the OpenMP
1572 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001573 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001574 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001575 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001576 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001577 if (VDPrivate->isInvalidDecl())
1578 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001579 PrivateCopies.push_back(buildDeclRefExpr(
1580 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001581 } else {
1582 // The variable is also a firstprivate, so initialization sequence
1583 // for private copy is generated already.
1584 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001585 }
1586 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001587 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001588 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001589 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001590 }
1591 }
1592 }
1593
Alexey Bataev758e55e2013-09-06 18:03:48 +00001594 DSAStack->pop();
1595 DiscardCleanupsInEvaluationContext();
1596 PopExpressionEvaluationContext();
1597}
1598
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001599static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1600 Expr *NumIterations, Sema &SemaRef,
1601 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001602
Alexey Bataeva769e072013-03-22 06:34:35 +00001603namespace {
1604
Alexey Bataeve3727102018-04-18 15:57:46 +00001605class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001606private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001607 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001608
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001609public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001610 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001611 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001612 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001613 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001614 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001615 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1616 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001617 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001618 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001619 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001620};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001621
Alexey Bataeve3727102018-04-18 15:57:46 +00001622class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001623private:
1624 Sema &SemaRef;
1625
1626public:
1627 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1628 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1629 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001630 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001631 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1632 SemaRef.getCurScope());
1633 }
1634 return false;
1635 }
1636};
1637
Alexey Bataeved09d242014-05-28 05:53:51 +00001638} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001639
1640ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1641 CXXScopeSpec &ScopeSpec,
1642 const DeclarationNameInfo &Id) {
1643 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1644 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1645
1646 if (Lookup.isAmbiguous())
1647 return ExprError();
1648
1649 VarDecl *VD;
1650 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001651 if (TypoCorrection Corrected = CorrectTypo(
1652 Id, LookupOrdinaryName, CurScope, nullptr,
1653 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001654 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001655 PDiag(Lookup.empty()
1656 ? diag::err_undeclared_var_use_suggest
1657 : diag::err_omp_expected_var_arg_suggest)
1658 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001659 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001660 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001661 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1662 : diag::err_omp_expected_var_arg)
1663 << Id.getName();
1664 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001665 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001666 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1667 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1668 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1669 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001670 }
1671 Lookup.suppressDiagnostics();
1672
1673 // OpenMP [2.9.2, Syntax, C/C++]
1674 // Variables must be file-scope, namespace-scope, or static block-scope.
1675 if (!VD->hasGlobalStorage()) {
1676 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001677 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1678 bool IsDecl =
1679 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001680 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001681 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1682 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001683 return ExprError();
1684 }
1685
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001686 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001687 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001688 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1689 // A threadprivate directive for file-scope variables must appear outside
1690 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001691 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1692 !getCurLexicalContext()->isTranslationUnit()) {
1693 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001694 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1695 bool IsDecl =
1696 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1697 Diag(VD->getLocation(),
1698 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1699 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001700 return ExprError();
1701 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001702 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1703 // A threadprivate directive for static class member variables must appear
1704 // in the class definition, in the same scope in which the member
1705 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001706 if (CanonicalVD->isStaticDataMember() &&
1707 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1708 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001709 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1710 bool IsDecl =
1711 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1712 Diag(VD->getLocation(),
1713 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1714 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001715 return ExprError();
1716 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001717 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1718 // A threadprivate directive for namespace-scope variables must appear
1719 // outside any definition or declaration other than the namespace
1720 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001721 if (CanonicalVD->getDeclContext()->isNamespace() &&
1722 (!getCurLexicalContext()->isFileContext() ||
1723 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1724 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001725 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1726 bool IsDecl =
1727 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1728 Diag(VD->getLocation(),
1729 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1730 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001731 return ExprError();
1732 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001733 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1734 // A threadprivate directive for static block-scope variables must appear
1735 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001736 if (CanonicalVD->isStaticLocal() && CurScope &&
1737 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001738 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001739 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1740 bool IsDecl =
1741 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1742 Diag(VD->getLocation(),
1743 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1744 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001745 return ExprError();
1746 }
1747
1748 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1749 // A threadprivate directive must lexically precede all references to any
1750 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001751 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001752 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001753 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001754 return ExprError();
1755 }
1756
1757 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001758 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1759 SourceLocation(), VD,
1760 /*RefersToEnclosingVariableOrCapture=*/false,
1761 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001762}
1763
Alexey Bataeved09d242014-05-28 05:53:51 +00001764Sema::DeclGroupPtrTy
1765Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1766 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001767 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001768 CurContext->addDecl(D);
1769 return DeclGroupPtrTy::make(DeclGroupRef(D));
1770 }
David Blaikie0403cb12016-01-15 23:43:25 +00001771 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001772}
1773
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001774namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00001775class LocalVarRefChecker final
1776 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001777 Sema &SemaRef;
1778
1779public:
1780 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001781 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001782 if (VD->hasLocalStorage()) {
1783 SemaRef.Diag(E->getLocStart(),
1784 diag::err_omp_local_var_in_threadprivate_init)
1785 << E->getSourceRange();
1786 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1787 << VD << VD->getSourceRange();
1788 return true;
1789 }
1790 }
1791 return false;
1792 }
1793 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001794 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001795 if (Child && Visit(Child))
1796 return true;
1797 }
1798 return false;
1799 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001800 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001801};
1802} // namespace
1803
Alexey Bataeved09d242014-05-28 05:53:51 +00001804OMPThreadPrivateDecl *
1805Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001806 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00001807 for (Expr *RefExpr : VarList) {
1808 auto *DE = cast<DeclRefExpr>(RefExpr);
1809 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001810 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001811
Alexey Bataev376b4a42016-02-09 09:41:09 +00001812 // Mark variable as used.
1813 VD->setReferenced();
1814 VD->markUsed(Context);
1815
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001816 QualType QType = VD->getType();
1817 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1818 // It will be analyzed later.
1819 Vars.push_back(DE);
1820 continue;
1821 }
1822
Alexey Bataeva769e072013-03-22 06:34:35 +00001823 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1824 // A threadprivate variable must not have an incomplete type.
1825 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001826 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001827 continue;
1828 }
1829
1830 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1831 // A threadprivate variable must not have a reference type.
1832 if (VD->getType()->isReferenceType()) {
1833 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001834 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1835 bool IsDecl =
1836 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1837 Diag(VD->getLocation(),
1838 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1839 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001840 continue;
1841 }
1842
Samuel Antaof8b50122015-07-13 22:54:53 +00001843 // Check if this is a TLS variable. If TLS is not being supported, produce
1844 // the corresponding diagnostic.
1845 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1846 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1847 getLangOpts().OpenMPUseTLS &&
1848 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001849 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1850 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001851 Diag(ILoc, diag::err_omp_var_thread_local)
1852 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001853 bool IsDecl =
1854 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1855 Diag(VD->getLocation(),
1856 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1857 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001858 continue;
1859 }
1860
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001861 // Check if initial value of threadprivate variable reference variable with
1862 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00001863 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001864 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001865 if (Checker.Visit(Init))
1866 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001867 }
1868
Alexey Bataeved09d242014-05-28 05:53:51 +00001869 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001870 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001871 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1872 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00001873 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00001874 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001875 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001876 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001877 if (!Vars.empty()) {
1878 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1879 Vars);
1880 D->setAccess(AS_public);
1881 }
1882 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001883}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001884
Alexey Bataeve3727102018-04-18 15:57:46 +00001885static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
1886 const ValueDecl *D,
1887 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001888 bool IsLoopIterVar = false) {
1889 if (DVar.RefExpr) {
1890 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1891 << getOpenMPClauseName(DVar.CKind);
1892 return;
1893 }
1894 enum {
1895 PDSA_StaticMemberShared,
1896 PDSA_StaticLocalVarShared,
1897 PDSA_LoopIterVarPrivate,
1898 PDSA_LoopIterVarLinear,
1899 PDSA_LoopIterVarLastprivate,
1900 PDSA_ConstVarShared,
1901 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001902 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001903 PDSA_LocalVarPrivate,
1904 PDSA_Implicit
1905 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001906 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001907 auto ReportLoc = D->getLocation();
1908 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001909 if (IsLoopIterVar) {
1910 if (DVar.CKind == OMPC_private)
1911 Reason = PDSA_LoopIterVarPrivate;
1912 else if (DVar.CKind == OMPC_lastprivate)
1913 Reason = PDSA_LoopIterVarLastprivate;
1914 else
1915 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001916 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1917 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001918 Reason = PDSA_TaskVarFirstprivate;
1919 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001920 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001921 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001922 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001923 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001924 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001925 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001926 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001927 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001928 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001929 ReportHint = true;
1930 Reason = PDSA_LocalVarPrivate;
1931 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001932 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001933 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001934 << Reason << ReportHint
1935 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1936 } else if (DVar.ImplicitDSALoc.isValid()) {
1937 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1938 << getOpenMPClauseName(DVar.CKind);
1939 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001940}
1941
Alexey Bataev758e55e2013-09-06 18:03:48 +00001942namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00001943class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001944 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001945 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00001946 bool ErrorFound = false;
1947 CapturedStmt *CS = nullptr;
1948 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
1949 llvm::SmallVector<Expr *, 4> ImplicitMap;
1950 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
1951 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001952
Alexey Bataev758e55e2013-09-06 18:03:48 +00001953public:
1954 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001955 if (E->isTypeDependent() || E->isValueDependent() ||
1956 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1957 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001958 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001959 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001960 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001961 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001962 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001963
Alexey Bataeve3727102018-04-18 15:57:46 +00001964 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001965 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001966 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001967 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001968
Alexey Bataevafe50572017-10-06 17:00:28 +00001969 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00001970 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
1971 isDeclareTargetDeclaration(VD);
1972 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
1973 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00001974 return;
1975
Alexey Bataeve3727102018-04-18 15:57:46 +00001976 SourceLocation ELoc = E->getExprLoc();
1977 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001978 // The default(none) clause requires that each variable that is referenced
1979 // in the construct, and does not have a predetermined data-sharing
1980 // attribute, must have its data-sharing attribute explicitly determined
1981 // by being listed in a data-sharing attribute clause.
1982 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001983 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001984 VarsWithInheritedDSA.count(VD) == 0) {
1985 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001986 return;
1987 }
1988
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001989 if (isOpenMPTargetExecutionDirective(DKind) &&
1990 !Stack->isLoopControlVariable(VD).first) {
1991 if (!Stack->checkMappableExprComponentListsForDecl(
1992 VD, /*CurrentRegionOnly=*/true,
1993 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1994 StackComponents,
1995 OpenMPClauseKind) {
1996 // Variable is used if it has been marked as an array, array
1997 // section or the variable iself.
1998 return StackComponents.size() == 1 ||
1999 std::all_of(
2000 std::next(StackComponents.rbegin()),
2001 StackComponents.rend(),
2002 [](const OMPClauseMappableExprCommon::
2003 MappableComponent &MC) {
2004 return MC.getAssociatedDeclaration() ==
2005 nullptr &&
2006 (isa<OMPArraySectionExpr>(
2007 MC.getAssociatedExpression()) ||
2008 isa<ArraySubscriptExpr>(
2009 MC.getAssociatedExpression()));
2010 });
2011 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002012 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002013 // By default lambdas are captured as firstprivates.
2014 if (const auto *RD =
2015 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002016 IsFirstprivate = RD->isLambda();
2017 IsFirstprivate =
2018 IsFirstprivate ||
2019 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002020 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002021 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002022 ImplicitFirstprivate.emplace_back(E);
2023 else
2024 ImplicitMap.emplace_back(E);
2025 return;
2026 }
2027 }
2028
Alexey Bataev758e55e2013-09-06 18:03:48 +00002029 // OpenMP [2.9.3.6, Restrictions, p.2]
2030 // A list item that appears in a reduction clause of the innermost
2031 // enclosing worksharing or parallel construct may not be accessed in an
2032 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002033 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002034 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2035 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002036 return isOpenMPParallelDirective(K) ||
2037 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2038 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002039 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002040 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002041 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002042 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002043 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002044 return;
2045 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002046
2047 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002048 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002049 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2050 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002051 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002052 }
2053 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002054 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002055 if (E->isTypeDependent() || E->isValueDependent() ||
2056 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2057 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002058 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002059 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002060 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002061 if (!FD)
2062 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002063 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002064 // Check if the variable has explicit DSA set and stop analysis if it
2065 // so.
2066 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2067 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002068
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002069 if (isOpenMPTargetExecutionDirective(DKind) &&
2070 !Stack->isLoopControlVariable(FD).first &&
2071 !Stack->checkMappableExprComponentListsForDecl(
2072 FD, /*CurrentRegionOnly=*/true,
2073 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2074 StackComponents,
2075 OpenMPClauseKind) {
2076 return isa<CXXThisExpr>(
2077 cast<MemberExpr>(
2078 StackComponents.back().getAssociatedExpression())
2079 ->getBase()
2080 ->IgnoreParens());
2081 })) {
2082 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2083 // A bit-field cannot appear in a map clause.
2084 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002085 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002086 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002087 ImplicitMap.emplace_back(E);
2088 return;
2089 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002090
Alexey Bataeve3727102018-04-18 15:57:46 +00002091 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002092 // OpenMP [2.9.3.6, Restrictions, p.2]
2093 // A list item that appears in a reduction clause of the innermost
2094 // enclosing worksharing or parallel construct may not be accessed in
2095 // an explicit task.
2096 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002097 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2098 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002099 return isOpenMPParallelDirective(K) ||
2100 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2101 },
2102 /*FromParent=*/true);
2103 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2104 ErrorFound = true;
2105 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002106 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002107 return;
2108 }
2109
2110 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002111 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002112 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2113 !Stack->isLoopControlVariable(FD).first)
2114 ImplicitFirstprivate.push_back(E);
2115 return;
2116 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002117 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002118 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002119 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002120 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002121 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002122 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002123 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2124 if (!Stack->checkMappableExprComponentListsForDecl(
2125 VD, /*CurrentRegionOnly=*/true,
2126 [&CurComponents](
2127 OMPClauseMappableExprCommon::MappableExprComponentListRef
2128 StackComponents,
2129 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002130 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002131 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002132 for (const auto &SC : llvm::reverse(StackComponents)) {
2133 // Do both expressions have the same kind?
2134 if (CCI->getAssociatedExpression()->getStmtClass() !=
2135 SC.getAssociatedExpression()->getStmtClass())
2136 if (!(isa<OMPArraySectionExpr>(
2137 SC.getAssociatedExpression()) &&
2138 isa<ArraySubscriptExpr>(
2139 CCI->getAssociatedExpression())))
2140 return false;
2141
Alexey Bataeve3727102018-04-18 15:57:46 +00002142 const Decl *CCD = CCI->getAssociatedDeclaration();
2143 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002144 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2145 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2146 if (SCD != CCD)
2147 return false;
2148 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002149 if (CCI == CCE)
2150 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002151 }
2152 return true;
2153 })) {
2154 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002155 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002156 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002157 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002158 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002159 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002160 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002161 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002162 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002163 // for task|target directives.
2164 // Skip analysis of arguments of implicitly defined map clause for target
2165 // directives.
2166 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2167 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002168 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002169 if (CC)
2170 Visit(CC);
2171 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002172 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002173 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002174 }
2175 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002176 for (Stmt *C : S->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002177 if (C && !isa<OMPExecutableDirective>(C))
2178 Visit(C);
2179 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002180 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002181
Alexey Bataeve3727102018-04-18 15:57:46 +00002182 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002183 ArrayRef<Expr *> getImplicitFirstprivate() const {
2184 return ImplicitFirstprivate;
2185 }
2186 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002187 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002188 return VarsWithInheritedDSA;
2189 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002190
Alexey Bataev7ff55242014-06-19 09:13:45 +00002191 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2192 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002193};
Alexey Bataeved09d242014-05-28 05:53:51 +00002194} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002195
Alexey Bataevbae9a792014-06-27 10:37:06 +00002196void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002197 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002198 case OMPD_parallel:
2199 case OMPD_parallel_for:
2200 case OMPD_parallel_for_simd:
2201 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002202 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002203 case OMPD_teams_distribute:
2204 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002205 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002206 QualType KmpInt32PtrTy =
2207 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002208 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002209 std::make_pair(".global_tid.", KmpInt32PtrTy),
2210 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2211 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002212 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002213 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2214 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002215 break;
2216 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002217 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002218 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002219 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002220 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002221 case OMPD_target_teams_distribute:
2222 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002223 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2224 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2225 QualType KmpInt32PtrTy =
2226 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2227 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002228 FunctionProtoType::ExtProtoInfo EPI;
2229 EPI.Variadic = true;
2230 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2231 Sema::CapturedParamNameType Params[] = {
2232 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002233 std::make_pair(".part_id.", KmpInt32PtrTy),
2234 std::make_pair(".privates.", VoidPtrTy),
2235 std::make_pair(
2236 ".copy_fn.",
2237 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002238 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2239 std::make_pair(StringRef(), QualType()) // __context with shared vars
2240 };
2241 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2242 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002243 // Mark this captured region as inlined, because we don't use outlined
2244 // function directly.
2245 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2246 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002247 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002248 Sema::CapturedParamNameType ParamsTarget[] = {
2249 std::make_pair(StringRef(), QualType()) // __context with shared vars
2250 };
2251 // Start a captured region for 'target' with no implicit parameters.
2252 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2253 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002254 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002255 std::make_pair(".global_tid.", KmpInt32PtrTy),
2256 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2257 std::make_pair(StringRef(), QualType()) // __context with shared vars
2258 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002259 // Start a captured region for 'teams' or 'parallel'. Both regions have
2260 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002261 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002262 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002263 break;
2264 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002265 case OMPD_target:
2266 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002267 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2268 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2269 QualType KmpInt32PtrTy =
2270 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2271 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002272 FunctionProtoType::ExtProtoInfo EPI;
2273 EPI.Variadic = true;
2274 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2275 Sema::CapturedParamNameType Params[] = {
2276 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002277 std::make_pair(".part_id.", KmpInt32PtrTy),
2278 std::make_pair(".privates.", VoidPtrTy),
2279 std::make_pair(
2280 ".copy_fn.",
2281 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002282 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2283 std::make_pair(StringRef(), QualType()) // __context with shared vars
2284 };
2285 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2286 Params);
2287 // Mark this captured region as inlined, because we don't use outlined
2288 // function directly.
2289 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2290 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002291 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002292 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2293 std::make_pair(StringRef(), QualType()));
2294 break;
2295 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002296 case OMPD_simd:
2297 case OMPD_for:
2298 case OMPD_for_simd:
2299 case OMPD_sections:
2300 case OMPD_section:
2301 case OMPD_single:
2302 case OMPD_master:
2303 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002304 case OMPD_taskgroup:
2305 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002306 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002307 case OMPD_ordered:
2308 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002309 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002310 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002311 std::make_pair(StringRef(), QualType()) // __context with shared vars
2312 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002313 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2314 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002315 break;
2316 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002317 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002318 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2319 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2320 QualType KmpInt32PtrTy =
2321 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2322 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002323 FunctionProtoType::ExtProtoInfo EPI;
2324 EPI.Variadic = true;
2325 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002326 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002327 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002328 std::make_pair(".part_id.", KmpInt32PtrTy),
2329 std::make_pair(".privates.", VoidPtrTy),
2330 std::make_pair(
2331 ".copy_fn.",
2332 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002333 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002334 std::make_pair(StringRef(), QualType()) // __context with shared vars
2335 };
2336 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2337 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002338 // Mark this captured region as inlined, because we don't use outlined
2339 // function directly.
2340 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2341 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002342 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002343 break;
2344 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002345 case OMPD_taskloop:
2346 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002347 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002348 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2349 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002350 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002351 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2352 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002353 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002354 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2355 .withConst();
2356 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2357 QualType KmpInt32PtrTy =
2358 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2359 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002360 FunctionProtoType::ExtProtoInfo EPI;
2361 EPI.Variadic = true;
2362 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002363 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002364 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002365 std::make_pair(".part_id.", KmpInt32PtrTy),
2366 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002367 std::make_pair(
2368 ".copy_fn.",
2369 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2370 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2371 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002372 std::make_pair(".ub.", KmpUInt64Ty),
2373 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002374 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002375 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002376 std::make_pair(StringRef(), QualType()) // __context with shared vars
2377 };
2378 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2379 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002380 // Mark this captured region as inlined, because we don't use outlined
2381 // function directly.
2382 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2383 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002384 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002385 break;
2386 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002387 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002388 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002389 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002390 QualType KmpInt32PtrTy =
2391 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2392 Sema::CapturedParamNameType Params[] = {
2393 std::make_pair(".global_tid.", KmpInt32PtrTy),
2394 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002395 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2396 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002397 std::make_pair(StringRef(), QualType()) // __context with shared vars
2398 };
2399 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2400 Params);
2401 break;
2402 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002403 case OMPD_target_teams_distribute_parallel_for:
2404 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002405 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002406 QualType KmpInt32PtrTy =
2407 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002408 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002409
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002410 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002411 FunctionProtoType::ExtProtoInfo EPI;
2412 EPI.Variadic = true;
2413 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2414 Sema::CapturedParamNameType Params[] = {
2415 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002416 std::make_pair(".part_id.", KmpInt32PtrTy),
2417 std::make_pair(".privates.", VoidPtrTy),
2418 std::make_pair(
2419 ".copy_fn.",
2420 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002421 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2422 std::make_pair(StringRef(), QualType()) // __context with shared vars
2423 };
2424 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2425 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002426 // Mark this captured region as inlined, because we don't use outlined
2427 // function directly.
2428 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2429 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002430 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002431 Sema::CapturedParamNameType ParamsTarget[] = {
2432 std::make_pair(StringRef(), QualType()) // __context with shared vars
2433 };
2434 // Start a captured region for 'target' with no implicit parameters.
2435 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2436 ParamsTarget);
2437
2438 Sema::CapturedParamNameType ParamsTeams[] = {
2439 std::make_pair(".global_tid.", KmpInt32PtrTy),
2440 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2441 std::make_pair(StringRef(), QualType()) // __context with shared vars
2442 };
2443 // Start a captured region for 'target' with no implicit parameters.
2444 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2445 ParamsTeams);
2446
2447 Sema::CapturedParamNameType ParamsParallel[] = {
2448 std::make_pair(".global_tid.", KmpInt32PtrTy),
2449 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002450 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2451 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00002452 std::make_pair(StringRef(), QualType()) // __context with shared vars
2453 };
2454 // Start a captured region for 'teams' or 'parallel'. Both regions have
2455 // the same implicit parameters.
2456 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2457 ParamsParallel);
2458 break;
2459 }
2460
Alexey Bataev46506272017-12-05 17:41:34 +00002461 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002462 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002463 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00002464 QualType KmpInt32PtrTy =
2465 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2466
2467 Sema::CapturedParamNameType ParamsTeams[] = {
2468 std::make_pair(".global_tid.", KmpInt32PtrTy),
2469 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2470 std::make_pair(StringRef(), QualType()) // __context with shared vars
2471 };
2472 // Start a captured region for 'target' with no implicit parameters.
2473 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2474 ParamsTeams);
2475
2476 Sema::CapturedParamNameType ParamsParallel[] = {
2477 std::make_pair(".global_tid.", KmpInt32PtrTy),
2478 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002479 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2480 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00002481 std::make_pair(StringRef(), QualType()) // __context with shared vars
2482 };
2483 // Start a captured region for 'teams' or 'parallel'. Both regions have
2484 // the same implicit parameters.
2485 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2486 ParamsParallel);
2487 break;
2488 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002489 case OMPD_target_update:
2490 case OMPD_target_enter_data:
2491 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002492 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2493 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2494 QualType KmpInt32PtrTy =
2495 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2496 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00002497 FunctionProtoType::ExtProtoInfo EPI;
2498 EPI.Variadic = true;
2499 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2500 Sema::CapturedParamNameType Params[] = {
2501 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002502 std::make_pair(".part_id.", KmpInt32PtrTy),
2503 std::make_pair(".privates.", VoidPtrTy),
2504 std::make_pair(
2505 ".copy_fn.",
2506 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00002507 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2508 std::make_pair(StringRef(), QualType()) // __context with shared vars
2509 };
2510 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2511 Params);
2512 // Mark this captured region as inlined, because we don't use outlined
2513 // function directly.
2514 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2515 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002516 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00002517 break;
2518 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002519 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002520 case OMPD_taskyield:
2521 case OMPD_barrier:
2522 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002523 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002524 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002525 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002526 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002527 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002528 case OMPD_declare_target:
2529 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002530 llvm_unreachable("OpenMP Directive is not allowed");
2531 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002532 llvm_unreachable("Unknown OpenMP directive");
2533 }
2534}
2535
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002536int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2537 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2538 getOpenMPCaptureRegions(CaptureRegions, DKind);
2539 return CaptureRegions.size();
2540}
2541
Alexey Bataev3392d762016-02-16 11:18:12 +00002542static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002543 Expr *CaptureExpr, bool WithInit,
2544 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002545 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002546 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002547 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002548 QualType Ty = Init->getType();
2549 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002550 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002551 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002552 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002553 Ty = C.getPointerType(Ty);
2554 ExprResult Res =
2555 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2556 if (!Res.isUsable())
2557 return nullptr;
2558 Init = Res.get();
2559 }
Alexey Bataev61205072016-03-02 04:57:40 +00002560 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002561 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002562 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2563 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002564 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00002565 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00002566 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002567 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002568 return CED;
2569}
2570
Alexey Bataev61205072016-03-02 04:57:40 +00002571static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2572 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002573 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00002574 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002575 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00002576 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002577 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2578 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002579 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002580 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002581}
2582
Alexey Bataev5a3af132016-03-29 08:58:54 +00002583static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002584 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002585 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002586 OMPCapturedExprDecl *CD = buildCaptureDecl(
2587 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2588 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002589 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2590 CaptureExpr->getExprLoc());
2591 }
2592 ExprResult Res = Ref;
2593 if (!S.getLangOpts().CPlusPlus &&
2594 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002595 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002596 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002597 if (!Res.isUsable())
2598 return ExprError();
2599 }
2600 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002601}
2602
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002603namespace {
2604// OpenMP directives parsed in this section are represented as a
2605// CapturedStatement with an associated statement. If a syntax error
2606// is detected during the parsing of the associated statement, the
2607// compiler must abort processing and close the CapturedStatement.
2608//
2609// Combined directives such as 'target parallel' have more than one
2610// nested CapturedStatements. This RAII ensures that we unwind out
2611// of all the nested CapturedStatements when an error is found.
2612class CaptureRegionUnwinderRAII {
2613private:
2614 Sema &S;
2615 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00002616 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002617
2618public:
2619 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2620 OpenMPDirectiveKind DKind)
2621 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2622 ~CaptureRegionUnwinderRAII() {
2623 if (ErrorFound) {
2624 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2625 while (--ThisCaptureLevel >= 0)
2626 S.ActOnCapturedRegionError();
2627 }
2628 }
2629};
2630} // namespace
2631
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002632StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2633 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002634 bool ErrorFound = false;
2635 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2636 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002637 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002638 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002639 return StmtError();
2640 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002641
Alexey Bataev2ba67042017-11-28 21:11:44 +00002642 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2643 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002644 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002645 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00002646 SmallVector<const OMPLinearClause *, 4> LCs;
2647 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002648 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00002649 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002650 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2651 Clause->getClauseKind() == OMPC_in_reduction) {
2652 // Capture taskgroup task_reduction descriptors inside the tasking regions
2653 // with the corresponding in_reduction items.
2654 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00002655 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00002656 if (E)
2657 MarkDeclarationsReferencedInExpr(E);
2658 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002659 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002660 Clause->getClauseKind() == OMPC_copyprivate ||
2661 (getLangOpts().OpenMPUseTLS &&
2662 getASTContext().getTargetInfo().isTLSSupported() &&
2663 Clause->getClauseKind() == OMPC_copyin)) {
2664 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002665 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00002666 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002667 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002668 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002669 }
2670 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002671 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002672 } else if (CaptureRegions.size() > 1 ||
2673 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002674 if (auto *C = OMPClauseWithPreInit::get(Clause))
2675 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002676 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002677 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00002678 MarkDeclarationsReferencedInExpr(E);
2679 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002680 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002681 if (Clause->getClauseKind() == OMPC_schedule)
2682 SC = cast<OMPScheduleClause>(Clause);
2683 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002684 OC = cast<OMPOrderedClause>(Clause);
2685 else if (Clause->getClauseKind() == OMPC_linear)
2686 LCs.push_back(cast<OMPLinearClause>(Clause));
2687 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002688 // OpenMP, 2.7.1 Loop Construct, Restrictions
2689 // The nonmonotonic modifier cannot be specified if an ordered clause is
2690 // specified.
2691 if (SC &&
2692 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2693 SC->getSecondScheduleModifier() ==
2694 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2695 OC) {
2696 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2697 ? SC->getFirstScheduleModifierLoc()
2698 : SC->getSecondScheduleModifierLoc(),
2699 diag::err_omp_schedule_nonmonotonic_ordered)
2700 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2701 ErrorFound = true;
2702 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002703 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002704 for (const OMPLinearClause *C : LCs) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002705 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2706 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2707 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002708 ErrorFound = true;
2709 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002710 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2711 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2712 OC->getNumForLoops()) {
2713 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2714 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2715 ErrorFound = true;
2716 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002717 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002718 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002719 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002720 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00002721 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002722 // Mark all variables in private list clauses as used in inner region.
2723 // Required for proper codegen of combined directives.
2724 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00002725 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002726 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002727 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2728 // Find the particular capture region for the clause if the
2729 // directive is a combined one with multiple capture regions.
2730 // If the directive is not a combined one, the capture region
2731 // associated with the clause is OMPD_unknown and is generated
2732 // only once.
2733 if (CaptureRegion == ThisCaptureRegion ||
2734 CaptureRegion == OMPD_unknown) {
2735 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002736 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002737 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2738 }
2739 }
2740 }
2741 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002742 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002743 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002744 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002745}
2746
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002747static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2748 OpenMPDirectiveKind CancelRegion,
2749 SourceLocation StartLoc) {
2750 // CancelRegion is only needed for cancel and cancellation_point.
2751 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2752 return false;
2753
2754 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2755 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2756 return false;
2757
2758 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2759 << getOpenMPDirectiveName(CancelRegion);
2760 return true;
2761}
2762
Alexey Bataeve3727102018-04-18 15:57:46 +00002763static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002764 OpenMPDirectiveKind CurrentRegion,
2765 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002766 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002767 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002768 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002769 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
2770 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002771 bool NestingProhibited = false;
2772 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002773 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002774 enum {
2775 NoRecommend,
2776 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002777 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002778 ShouldBeInTargetRegion,
2779 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002780 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002781 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002782 // OpenMP [2.16, Nesting of Regions]
2783 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002784 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002785 // An ordered construct with the simd clause is the only OpenMP
2786 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002787 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002788 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2789 // message.
2790 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2791 ? diag::err_omp_prohibited_region_simd
2792 : diag::warn_omp_nesting_simd);
2793 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002794 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002795 if (ParentRegion == OMPD_atomic) {
2796 // OpenMP [2.16, Nesting of Regions]
2797 // OpenMP constructs may not be nested inside an atomic region.
2798 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2799 return true;
2800 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002801 if (CurrentRegion == OMPD_section) {
2802 // OpenMP [2.7.2, sections Construct, Restrictions]
2803 // Orphaned section directives are prohibited. That is, the section
2804 // directives must appear within the sections construct and must not be
2805 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002806 if (ParentRegion != OMPD_sections &&
2807 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002808 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2809 << (ParentRegion != OMPD_unknown)
2810 << getOpenMPDirectiveName(ParentRegion);
2811 return true;
2812 }
2813 return false;
2814 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002815 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002816 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002817 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002818 if (ParentRegion == OMPD_unknown &&
2819 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002820 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002821 if (CurrentRegion == OMPD_cancellation_point ||
2822 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002823 // OpenMP [2.16, Nesting of Regions]
2824 // A cancellation point construct for which construct-type-clause is
2825 // taskgroup must be nested inside a task construct. A cancellation
2826 // point construct for which construct-type-clause is not taskgroup must
2827 // be closely nested inside an OpenMP construct that matches the type
2828 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002829 // A cancel construct for which construct-type-clause is taskgroup must be
2830 // nested inside a task construct. A cancel construct for which
2831 // construct-type-clause is not taskgroup must be closely nested inside an
2832 // OpenMP construct that matches the type specified in
2833 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002834 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002835 !((CancelRegion == OMPD_parallel &&
2836 (ParentRegion == OMPD_parallel ||
2837 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002838 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002839 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002840 ParentRegion == OMPD_target_parallel_for ||
2841 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00002842 ParentRegion == OMPD_teams_distribute_parallel_for ||
2843 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002844 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2845 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002846 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2847 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002848 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002849 // OpenMP [2.16, Nesting of Regions]
2850 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002851 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002852 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002853 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002854 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2855 // OpenMP [2.16, Nesting of Regions]
2856 // A critical region may not be nested (closely or otherwise) inside a
2857 // critical region with the same name. Note that this restriction is not
2858 // sufficient to prevent deadlock.
2859 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002860 bool DeadLock = Stack->hasDirective(
2861 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2862 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00002863 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00002864 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2865 PreviousCriticalLoc = Loc;
2866 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00002867 }
2868 return false;
David Majnemer9d168222016-08-05 17:44:54 +00002869 },
2870 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002871 if (DeadLock) {
2872 SemaRef.Diag(StartLoc,
2873 diag::err_omp_prohibited_region_critical_same_name)
2874 << CurrentName.getName();
2875 if (PreviousCriticalLoc.isValid())
2876 SemaRef.Diag(PreviousCriticalLoc,
2877 diag::note_omp_previous_critical_region);
2878 return true;
2879 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002880 } else if (CurrentRegion == OMPD_barrier) {
2881 // OpenMP [2.16, Nesting of Regions]
2882 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002883 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002884 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2885 isOpenMPTaskingDirective(ParentRegion) ||
2886 ParentRegion == OMPD_master ||
2887 ParentRegion == OMPD_critical ||
2888 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002889 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002890 !isOpenMPParallelDirective(CurrentRegion) &&
2891 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002892 // OpenMP [2.16, Nesting of Regions]
2893 // A worksharing region may not be closely nested inside a worksharing,
2894 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002895 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2896 isOpenMPTaskingDirective(ParentRegion) ||
2897 ParentRegion == OMPD_master ||
2898 ParentRegion == OMPD_critical ||
2899 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002900 Recommend = ShouldBeInParallelRegion;
2901 } else if (CurrentRegion == OMPD_ordered) {
2902 // OpenMP [2.16, Nesting of Regions]
2903 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002904 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002905 // An ordered region must be closely nested inside a loop region (or
2906 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002907 // OpenMP [2.8.1,simd Construct, Restrictions]
2908 // An ordered construct with the simd clause is the only OpenMP construct
2909 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002910 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002911 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002912 !(isOpenMPSimdDirective(ParentRegion) ||
2913 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002914 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002915 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002916 // OpenMP [2.16, Nesting of Regions]
2917 // If specified, a teams construct must be contained within a target
2918 // construct.
2919 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002920 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002921 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002922 }
Kelvin Libf594a52016-12-17 05:48:59 +00002923 if (!NestingProhibited &&
2924 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2925 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2926 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002927 // OpenMP [2.16, Nesting of Regions]
2928 // distribute, parallel, parallel sections, parallel workshare, and the
2929 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2930 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002931 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2932 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002933 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002934 }
David Majnemer9d168222016-08-05 17:44:54 +00002935 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002936 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002937 // OpenMP 4.5 [2.17 Nesting of Regions]
2938 // The region associated with the distribute construct must be strictly
2939 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002940 NestingProhibited =
2941 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002942 Recommend = ShouldBeInTeamsRegion;
2943 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002944 if (!NestingProhibited &&
2945 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2946 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2947 // OpenMP 4.5 [2.17 Nesting of Regions]
2948 // If a target, target update, target data, target enter data, or
2949 // target exit data construct is encountered during execution of a
2950 // target region, the behavior is unspecified.
2951 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002952 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00002953 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002954 if (isOpenMPTargetExecutionDirective(K)) {
2955 OffendingRegion = K;
2956 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00002957 }
2958 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002959 },
2960 false /* don't skip top directive */);
2961 CloseNesting = false;
2962 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002963 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002964 if (OrphanSeen) {
2965 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2966 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2967 } else {
2968 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2969 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2970 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2971 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002972 return true;
2973 }
2974 }
2975 return false;
2976}
2977
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002978static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2979 ArrayRef<OMPClause *> Clauses,
2980 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2981 bool ErrorFound = false;
2982 unsigned NamedModifiersNumber = 0;
2983 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2984 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002985 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00002986 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002987 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2988 // At most one if clause without a directive-name-modifier can appear on
2989 // the directive.
2990 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2991 if (FoundNameModifiers[CurNM]) {
2992 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2993 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2994 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2995 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002996 } else if (CurNM != OMPD_unknown) {
2997 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002998 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002999 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003000 FoundNameModifiers[CurNM] = IC;
3001 if (CurNM == OMPD_unknown)
3002 continue;
3003 // Check if the specified name modifier is allowed for the current
3004 // directive.
3005 // At most one if clause with the particular directive-name-modifier can
3006 // appear on the directive.
3007 bool MatchFound = false;
3008 for (auto NM : AllowedNameModifiers) {
3009 if (CurNM == NM) {
3010 MatchFound = true;
3011 break;
3012 }
3013 }
3014 if (!MatchFound) {
3015 S.Diag(IC->getNameModifierLoc(),
3016 diag::err_omp_wrong_if_directive_name_modifier)
3017 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3018 ErrorFound = true;
3019 }
3020 }
3021 }
3022 // If any if clause on the directive includes a directive-name-modifier then
3023 // all if clauses on the directive must include a directive-name-modifier.
3024 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3025 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3026 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
3027 diag::err_omp_no_more_if_clause);
3028 } else {
3029 std::string Values;
3030 std::string Sep(", ");
3031 unsigned AllowedCnt = 0;
3032 unsigned TotalAllowedNum =
3033 AllowedNameModifiers.size() - NamedModifiersNumber;
3034 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3035 ++Cnt) {
3036 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3037 if (!FoundNameModifiers[NM]) {
3038 Values += "'";
3039 Values += getOpenMPDirectiveName(NM);
3040 Values += "'";
3041 if (AllowedCnt + 2 == TotalAllowedNum)
3042 Values += " or ";
3043 else if (AllowedCnt + 1 != TotalAllowedNum)
3044 Values += Sep;
3045 ++AllowedCnt;
3046 }
3047 }
3048 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
3049 diag::err_omp_unnamed_if_clause)
3050 << (TotalAllowedNum > 1) << Values;
3051 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003052 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003053 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3054 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003055 ErrorFound = true;
3056 }
3057 return ErrorFound;
3058}
3059
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003060StmtResult Sema::ActOnOpenMPExecutableDirective(
3061 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3062 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3063 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003064 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003065 // First check CancelRegion which is then used in checkNestingOfRegions.
3066 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3067 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003068 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003069 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003070
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003071 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003072 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003073 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003074 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003075 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003076 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3077
3078 // Check default data sharing attributes for referenced variables.
3079 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003080 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3081 Stmt *S = AStmt;
3082 while (--ThisCaptureLevel >= 0)
3083 S = cast<CapturedStmt>(S)->getCapturedStmt();
3084 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003085 if (DSAChecker.isErrorFound())
3086 return StmtError();
3087 // Generate list of implicitly defined firstprivate variables.
3088 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003089
Alexey Bataev88202be2017-07-27 13:20:36 +00003090 SmallVector<Expr *, 4> ImplicitFirstprivates(
3091 DSAChecker.getImplicitFirstprivate().begin(),
3092 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003093 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3094 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003095 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003096 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003097 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003098 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003099 if (E)
3100 ImplicitFirstprivates.emplace_back(E);
3101 }
3102 }
3103 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003104 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003105 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3106 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003107 ClausesWithImplicit.push_back(Implicit);
3108 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003109 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003110 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003111 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003112 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003113 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003114 if (!ImplicitMaps.empty()) {
3115 if (OMPClause *Implicit = ActOnOpenMPMapClause(
3116 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
3117 SourceLocation(), SourceLocation(), ImplicitMaps,
3118 SourceLocation(), SourceLocation(), SourceLocation())) {
3119 ClausesWithImplicit.emplace_back(Implicit);
3120 ErrorFound |=
3121 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003122 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003123 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003124 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003125 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003126 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003127
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003128 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003129 switch (Kind) {
3130 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003131 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3132 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003133 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003134 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003135 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003136 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3137 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003138 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003139 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003140 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3141 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003142 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003143 case OMPD_for_simd:
3144 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3145 EndLoc, VarsWithInheritedDSA);
3146 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003147 case OMPD_sections:
3148 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3149 EndLoc);
3150 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003151 case OMPD_section:
3152 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003153 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003154 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3155 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003156 case OMPD_single:
3157 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3158 EndLoc);
3159 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003160 case OMPD_master:
3161 assert(ClausesWithImplicit.empty() &&
3162 "No clauses are allowed for 'omp master' directive");
3163 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3164 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003165 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003166 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3167 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003168 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003169 case OMPD_parallel_for:
3170 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3171 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003172 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003173 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003174 case OMPD_parallel_for_simd:
3175 Res = ActOnOpenMPParallelForSimdDirective(
3176 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003177 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003178 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003179 case OMPD_parallel_sections:
3180 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3181 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003182 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003183 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003184 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003185 Res =
3186 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003187 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003188 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003189 case OMPD_taskyield:
3190 assert(ClausesWithImplicit.empty() &&
3191 "No clauses are allowed for 'omp taskyield' directive");
3192 assert(AStmt == nullptr &&
3193 "No associated statement allowed for 'omp taskyield' directive");
3194 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3195 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003196 case OMPD_barrier:
3197 assert(ClausesWithImplicit.empty() &&
3198 "No clauses are allowed for 'omp barrier' directive");
3199 assert(AStmt == nullptr &&
3200 "No associated statement allowed for 'omp barrier' directive");
3201 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3202 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003203 case OMPD_taskwait:
3204 assert(ClausesWithImplicit.empty() &&
3205 "No clauses are allowed for 'omp taskwait' directive");
3206 assert(AStmt == nullptr &&
3207 "No associated statement allowed for 'omp taskwait' directive");
3208 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3209 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003210 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003211 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3212 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003213 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003214 case OMPD_flush:
3215 assert(AStmt == nullptr &&
3216 "No associated statement allowed for 'omp flush' directive");
3217 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3218 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003219 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003220 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3221 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003222 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003223 case OMPD_atomic:
3224 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3225 EndLoc);
3226 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003227 case OMPD_teams:
3228 Res =
3229 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3230 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003231 case OMPD_target:
3232 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3233 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003234 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003235 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003236 case OMPD_target_parallel:
3237 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3238 StartLoc, EndLoc);
3239 AllowedNameModifiers.push_back(OMPD_target);
3240 AllowedNameModifiers.push_back(OMPD_parallel);
3241 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003242 case OMPD_target_parallel_for:
3243 Res = ActOnOpenMPTargetParallelForDirective(
3244 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3245 AllowedNameModifiers.push_back(OMPD_target);
3246 AllowedNameModifiers.push_back(OMPD_parallel);
3247 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003248 case OMPD_cancellation_point:
3249 assert(ClausesWithImplicit.empty() &&
3250 "No clauses are allowed for 'omp cancellation point' directive");
3251 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3252 "cancellation point' directive");
3253 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3254 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003255 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003256 assert(AStmt == nullptr &&
3257 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003258 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3259 CancelRegion);
3260 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003261 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003262 case OMPD_target_data:
3263 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3264 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003265 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003266 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003267 case OMPD_target_enter_data:
3268 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003269 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003270 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3271 break;
Samuel Antao72590762016-01-19 20:04:50 +00003272 case OMPD_target_exit_data:
3273 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003274 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003275 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3276 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003277 case OMPD_taskloop:
3278 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3279 EndLoc, VarsWithInheritedDSA);
3280 AllowedNameModifiers.push_back(OMPD_taskloop);
3281 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003282 case OMPD_taskloop_simd:
3283 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3284 EndLoc, VarsWithInheritedDSA);
3285 AllowedNameModifiers.push_back(OMPD_taskloop);
3286 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003287 case OMPD_distribute:
3288 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3289 EndLoc, VarsWithInheritedDSA);
3290 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003291 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003292 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3293 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003294 AllowedNameModifiers.push_back(OMPD_target_update);
3295 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003296 case OMPD_distribute_parallel_for:
3297 Res = ActOnOpenMPDistributeParallelForDirective(
3298 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3299 AllowedNameModifiers.push_back(OMPD_parallel);
3300 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003301 case OMPD_distribute_parallel_for_simd:
3302 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3303 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3304 AllowedNameModifiers.push_back(OMPD_parallel);
3305 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003306 case OMPD_distribute_simd:
3307 Res = ActOnOpenMPDistributeSimdDirective(
3308 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3309 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003310 case OMPD_target_parallel_for_simd:
3311 Res = ActOnOpenMPTargetParallelForSimdDirective(
3312 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3313 AllowedNameModifiers.push_back(OMPD_target);
3314 AllowedNameModifiers.push_back(OMPD_parallel);
3315 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003316 case OMPD_target_simd:
3317 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3318 EndLoc, VarsWithInheritedDSA);
3319 AllowedNameModifiers.push_back(OMPD_target);
3320 break;
Kelvin Li02532872016-08-05 14:37:37 +00003321 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003322 Res = ActOnOpenMPTeamsDistributeDirective(
3323 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003324 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003325 case OMPD_teams_distribute_simd:
3326 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3327 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3328 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003329 case OMPD_teams_distribute_parallel_for_simd:
3330 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3331 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3332 AllowedNameModifiers.push_back(OMPD_parallel);
3333 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003334 case OMPD_teams_distribute_parallel_for:
3335 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3336 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3337 AllowedNameModifiers.push_back(OMPD_parallel);
3338 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003339 case OMPD_target_teams:
3340 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3341 EndLoc);
3342 AllowedNameModifiers.push_back(OMPD_target);
3343 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003344 case OMPD_target_teams_distribute:
3345 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3346 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3347 AllowedNameModifiers.push_back(OMPD_target);
3348 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003349 case OMPD_target_teams_distribute_parallel_for:
3350 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3351 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3352 AllowedNameModifiers.push_back(OMPD_target);
3353 AllowedNameModifiers.push_back(OMPD_parallel);
3354 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003355 case OMPD_target_teams_distribute_parallel_for_simd:
3356 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3357 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3358 AllowedNameModifiers.push_back(OMPD_target);
3359 AllowedNameModifiers.push_back(OMPD_parallel);
3360 break;
Kelvin Lida681182017-01-10 18:08:18 +00003361 case OMPD_target_teams_distribute_simd:
3362 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3363 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3364 AllowedNameModifiers.push_back(OMPD_target);
3365 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003366 case OMPD_declare_target:
3367 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003368 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003369 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003370 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003371 llvm_unreachable("OpenMP Directive is not allowed");
3372 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003373 llvm_unreachable("Unknown OpenMP directive");
3374 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003375
Alexey Bataeve3727102018-04-18 15:57:46 +00003376 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003377 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3378 << P.first << P.second->getSourceRange();
3379 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003380 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3381
3382 if (!AllowedNameModifiers.empty())
3383 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3384 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003385
Alexey Bataeved09d242014-05-28 05:53:51 +00003386 if (ErrorFound)
3387 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003388 return Res;
3389}
3390
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003391Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3392 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003393 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003394 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3395 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003396 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003397 assert(Linears.size() == LinModifiers.size());
3398 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003399 if (!DG || DG.get().isNull())
3400 return DeclGroupPtrTy();
3401
3402 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003403 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003404 return DG;
3405 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003406 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003407 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3408 ADecl = FTD->getTemplatedDecl();
3409
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003410 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3411 if (!FD) {
3412 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003413 return DeclGroupPtrTy();
3414 }
3415
Alexey Bataev2af33e32016-04-07 12:45:37 +00003416 // OpenMP [2.8.2, declare simd construct, Description]
3417 // The parameter of the simdlen clause must be a constant positive integer
3418 // expression.
3419 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003420 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003421 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003422 // OpenMP [2.8.2, declare simd construct, Description]
3423 // The special this pointer can be used as if was one of the arguments to the
3424 // function in any of the linear, aligned, or uniform clauses.
3425 // The uniform clause declares one or more arguments to have an invariant
3426 // value for all concurrent invocations of the function in the execution of a
3427 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00003428 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3429 const Expr *UniformedLinearThis = nullptr;
3430 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003431 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003432 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3433 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003434 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3435 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003436 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00003437 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003438 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003439 }
3440 if (isa<CXXThisExpr>(E)) {
3441 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003442 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003443 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003444 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3445 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003446 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003447 // OpenMP [2.8.2, declare simd construct, Description]
3448 // The aligned clause declares that the object to which each list item points
3449 // is aligned to the number of bytes expressed in the optional parameter of
3450 // the aligned clause.
3451 // The special this pointer can be used as if was one of the arguments to the
3452 // function in any of the linear, aligned, or uniform clauses.
3453 // The type of list items appearing in the aligned clause must be array,
3454 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00003455 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3456 const Expr *AlignedThis = nullptr;
3457 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003458 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003459 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3460 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3461 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00003462 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3463 FD->getParamDecl(PVD->getFunctionScopeIndex())
3464 ->getCanonicalDecl() == CanonPVD) {
3465 // OpenMP [2.8.1, simd construct, Restrictions]
3466 // A list-item cannot appear in more than one aligned clause.
3467 if (AlignedArgs.count(CanonPVD) > 0) {
3468 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3469 << 1 << E->getSourceRange();
3470 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3471 diag::note_omp_explicit_dsa)
3472 << getOpenMPClauseName(OMPC_aligned);
3473 continue;
3474 }
3475 AlignedArgs[CanonPVD] = E;
3476 QualType QTy = PVD->getType()
3477 .getNonReferenceType()
3478 .getUnqualifiedType()
3479 .getCanonicalType();
3480 const Type *Ty = QTy.getTypePtrOrNull();
3481 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3482 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3483 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3484 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3485 }
3486 continue;
3487 }
3488 }
3489 if (isa<CXXThisExpr>(E)) {
3490 if (AlignedThis) {
3491 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3492 << 2 << E->getSourceRange();
3493 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3494 << getOpenMPClauseName(OMPC_aligned);
3495 }
3496 AlignedThis = E;
3497 continue;
3498 }
3499 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3500 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3501 }
3502 // The optional parameter of the aligned clause, alignment, must be a constant
3503 // positive integer expression. If no optional parameter is specified,
3504 // implementation-defined default alignments for SIMD instructions on the
3505 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00003506 SmallVector<const Expr *, 4> NewAligns;
3507 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003508 ExprResult Align;
3509 if (E)
3510 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3511 NewAligns.push_back(Align.get());
3512 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003513 // OpenMP [2.8.2, declare simd construct, Description]
3514 // The linear clause declares one or more list items to be private to a SIMD
3515 // lane and to have a linear relationship with respect to the iteration space
3516 // of a loop.
3517 // The special this pointer can be used as if was one of the arguments to the
3518 // function in any of the linear, aligned, or uniform clauses.
3519 // When a linear-step expression is specified in a linear clause it must be
3520 // either a constant integer expression or an integer-typed parameter that is
3521 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00003522 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003523 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3524 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00003525 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003526 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3527 ++MI;
3528 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003529 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3530 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3531 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003532 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3533 FD->getParamDecl(PVD->getFunctionScopeIndex())
3534 ->getCanonicalDecl() == CanonPVD) {
3535 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3536 // A list-item cannot appear in more than one linear clause.
3537 if (LinearArgs.count(CanonPVD) > 0) {
3538 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3539 << getOpenMPClauseName(OMPC_linear)
3540 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3541 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3542 diag::note_omp_explicit_dsa)
3543 << getOpenMPClauseName(OMPC_linear);
3544 continue;
3545 }
3546 // Each argument can appear in at most one uniform or linear clause.
3547 if (UniformedArgs.count(CanonPVD) > 0) {
3548 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3549 << getOpenMPClauseName(OMPC_linear)
3550 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3551 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3552 diag::note_omp_explicit_dsa)
3553 << getOpenMPClauseName(OMPC_uniform);
3554 continue;
3555 }
3556 LinearArgs[CanonPVD] = E;
3557 if (E->isValueDependent() || E->isTypeDependent() ||
3558 E->isInstantiationDependent() ||
3559 E->containsUnexpandedParameterPack())
3560 continue;
3561 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3562 PVD->getOriginalType());
3563 continue;
3564 }
3565 }
3566 if (isa<CXXThisExpr>(E)) {
3567 if (UniformedLinearThis) {
3568 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3569 << getOpenMPClauseName(OMPC_linear)
3570 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3571 << E->getSourceRange();
3572 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3573 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3574 : OMPC_linear);
3575 continue;
3576 }
3577 UniformedLinearThis = E;
3578 if (E->isValueDependent() || E->isTypeDependent() ||
3579 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3580 continue;
3581 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3582 E->getType());
3583 continue;
3584 }
3585 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3586 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3587 }
3588 Expr *Step = nullptr;
3589 Expr *NewStep = nullptr;
3590 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00003591 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003592 // Skip the same step expression, it was checked already.
3593 if (Step == E || !E) {
3594 NewSteps.push_back(E ? NewStep : nullptr);
3595 continue;
3596 }
3597 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00003598 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3599 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3600 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003601 if (UniformedArgs.count(CanonPVD) == 0) {
3602 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3603 << Step->getSourceRange();
3604 } else if (E->isValueDependent() || E->isTypeDependent() ||
3605 E->isInstantiationDependent() ||
3606 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00003607 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003608 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00003609 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003610 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3611 << Step->getSourceRange();
3612 }
3613 continue;
3614 }
3615 NewStep = Step;
3616 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3617 !Step->isInstantiationDependent() &&
3618 !Step->containsUnexpandedParameterPack()) {
3619 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3620 .get();
3621 if (NewStep)
3622 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3623 }
3624 NewSteps.push_back(NewStep);
3625 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003626 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3627 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003628 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003629 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3630 const_cast<Expr **>(Linears.data()), Linears.size(),
3631 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3632 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003633 ADecl->addAttr(NewAttr);
3634 return ConvertDeclToDeclGroup(ADecl);
3635}
3636
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003637StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3638 Stmt *AStmt,
3639 SourceLocation StartLoc,
3640 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003641 if (!AStmt)
3642 return StmtError();
3643
Alexey Bataeve3727102018-04-18 15:57:46 +00003644 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00003645 // 1.2.2 OpenMP Language Terminology
3646 // Structured block - An executable statement with a single entry at the
3647 // top and a single exit at the bottom.
3648 // The point of exit cannot be a branch out of the structured block.
3649 // longjmp() and throw() must not violate the entry/exit criteria.
3650 CS->getCapturedDecl()->setNothrow();
3651
Reid Kleckner87a31802018-03-12 21:43:02 +00003652 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003653
Alexey Bataev25e5b442015-09-15 12:52:43 +00003654 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3655 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003656}
3657
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003658namespace {
3659/// \brief Helper class for checking canonical form of the OpenMP loops and
3660/// extracting iteration space of each loop in the loop nest, that will be used
3661/// for IR generation.
3662class OpenMPIterationSpaceChecker {
3663 /// \brief Reference to Sema.
3664 Sema &SemaRef;
3665 /// \brief A location for diagnostics (when there is no some better location).
3666 SourceLocation DefaultLoc;
3667 /// \brief A location for diagnostics (when increment is not compatible).
3668 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003669 /// \brief A source location for referring to loop init later.
3670 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003671 /// \brief A source location for referring to condition later.
3672 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003673 /// \brief A source location for referring to increment later.
3674 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003675 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003676 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003677 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003678 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003679 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003680 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003681 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003682 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003683 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003684 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003685 /// \brief This flag is true when condition is one of:
3686 /// Var < UB
3687 /// Var <= UB
3688 /// UB > Var
3689 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003690 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003691 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003692 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003693 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003694 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003695
3696public:
3697 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003698 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003699 /// \brief Check init-expr for canonical loop form and save loop counter
3700 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00003701 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003702 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3703 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00003704 bool checkAndSetCond(Expr *S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003705 /// \brief Check incr-expr for canonical loop form and return true if it
3706 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00003707 bool checkAndSetInc(Expr *S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003708 /// \brief Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00003709 ValueDecl *getLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003710 /// \brief Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00003711 Expr *getLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003712 /// \brief Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00003713 SourceRange getInitSrcRange() const { return InitSrcRange; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003714 /// \brief Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00003715 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003716 /// \brief Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00003717 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003718 /// \brief True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00003719 bool shouldSubtractStep() const { return SubtractStep; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003720 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00003721 Expr *buildNumIterations(
3722 Scope *S, const bool LimitedType,
3723 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003724 /// \brief Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00003725 Expr *
3726 buildPreCond(Scope *S, Expr *Cond,
3727 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003728 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003729 DeclRefExpr *
3730 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
3731 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003732 /// \brief Build reference expression to the private counter be used for
3733 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003734 Expr *buildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003735 /// \brief Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003736 Expr *buildCounterInit() const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003737 /// \brief Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003738 Expr *buildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003739 /// \brief Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00003740 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003741
3742private:
3743 /// \brief Check the right-hand side of an assignment in the increment
3744 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00003745 bool checkAndSetIncRHS(Expr *RHS);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003746 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00003747 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003748 /// \brief Helper to set upper bound.
Alexey Bataeve3727102018-04-18 15:57:46 +00003749 bool setUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003750 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003751 /// \brief Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00003752 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003753};
3754
Alexey Bataeve3727102018-04-18 15:57:46 +00003755bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003756 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003757 assert(!LB && !UB && !Step);
3758 return false;
3759 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003760 return LCDecl->getType()->isDependentType() ||
3761 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3762 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003763}
3764
Alexey Bataeve3727102018-04-18 15:57:46 +00003765bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003766 Expr *NewLCRefExpr,
3767 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003768 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003769 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003770 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003771 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003772 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003773 LCDecl = getCanonicalDecl(NewLCDecl);
3774 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003775 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3776 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003777 if ((Ctor->isCopyOrMoveConstructor() ||
3778 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3779 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003780 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003781 LB = NewLB;
3782 return false;
3783}
3784
Alexey Bataeve3727102018-04-18 15:57:46 +00003785bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003786 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003787 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003788 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3789 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003790 if (!NewUB)
3791 return true;
3792 UB = NewUB;
3793 TestIsLessOp = LessOp;
3794 TestIsStrictOp = StrictOp;
3795 ConditionSrcRange = SR;
3796 ConditionLoc = SL;
3797 return false;
3798}
3799
Alexey Bataeve3727102018-04-18 15:57:46 +00003800bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003801 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003802 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003803 if (!NewStep)
3804 return true;
3805 if (!NewStep->isValueDependent()) {
3806 // Check that the step is integer expression.
3807 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003808 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3809 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003810 if (Val.isInvalid())
3811 return true;
3812 NewStep = Val.get();
3813
3814 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3815 // If test-expr is of form var relational-op b and relational-op is < or
3816 // <= then incr-expr must cause var to increase on each iteration of the
3817 // loop. If test-expr is of form var relational-op b and relational-op is
3818 // > or >= then incr-expr must cause var to decrease on each iteration of
3819 // the loop.
3820 // If test-expr is of form b relational-op var and relational-op is < or
3821 // <= then incr-expr must cause var to decrease on each iteration of the
3822 // loop. If test-expr is of form b relational-op var and relational-op is
3823 // > or >= then incr-expr must cause var to increase on each iteration of
3824 // the loop.
3825 llvm::APSInt Result;
3826 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3827 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3828 bool IsConstNeg =
3829 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003830 bool IsConstPos =
3831 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003832 bool IsConstZero = IsConstant && !Result.getBoolValue();
3833 if (UB && (IsConstZero ||
3834 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003835 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003836 SemaRef.Diag(NewStep->getExprLoc(),
3837 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003838 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003839 SemaRef.Diag(ConditionLoc,
3840 diag::note_omp_loop_cond_requres_compatible_incr)
3841 << TestIsLessOp << ConditionSrcRange;
3842 return true;
3843 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003844 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003845 NewStep =
3846 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3847 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003848 Subtract = !Subtract;
3849 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003850 }
3851
3852 Step = NewStep;
3853 SubtractStep = Subtract;
3854 return false;
3855}
3856
Alexey Bataeve3727102018-04-18 15:57:46 +00003857bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003858 // Check init-expr for canonical loop form and save loop counter
3859 // variable - #Var and its initialization value - #LB.
3860 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3861 // var = lb
3862 // integer-type var = lb
3863 // random-access-iterator-type var = lb
3864 // pointer-type var = lb
3865 //
3866 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003867 if (EmitDiags) {
3868 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3869 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003870 return true;
3871 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003872 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3873 if (!ExprTemp->cleanupsHaveSideEffects())
3874 S = ExprTemp->getSubExpr();
3875
Alexander Musmana5f070a2014-10-01 06:03:56 +00003876 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003877 if (Expr *E = dyn_cast<Expr>(S))
3878 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003879 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003880 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003881 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003882 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3883 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3884 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00003885 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3886 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003887 }
3888 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3889 if (ME->isArrow() &&
3890 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00003891 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003892 }
3893 }
David Majnemer9d168222016-08-05 17:44:54 +00003894 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003895 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003896 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003897 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003898 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003899 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003900 SemaRef.Diag(S->getLocStart(),
3901 diag::ext_omp_loop_not_canonical_init)
3902 << S->getSourceRange();
Alexey Bataeve3727102018-04-18 15:57:46 +00003903 return setLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003904 }
3905 }
3906 }
David Majnemer9d168222016-08-05 17:44:54 +00003907 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003908 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003909 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003910 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003911 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3912 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00003913 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3914 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003915 }
3916 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3917 if (ME->isArrow() &&
3918 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00003919 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003920 }
3921 }
3922 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003923
Alexey Bataeve3727102018-04-18 15:57:46 +00003924 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003925 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003926 if (EmitDiags) {
3927 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3928 << S->getSourceRange();
3929 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003930 return true;
3931}
3932
Alexey Bataev23b69422014-06-18 07:08:49 +00003933/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003934/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00003935static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003936 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003937 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003938 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00003939 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003940 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003941 if ((Ctor->isCopyOrMoveConstructor() ||
3942 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3943 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003944 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003945 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3946 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003947 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003948 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003949 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003950 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3951 return getCanonicalDecl(ME->getMemberDecl());
3952 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003953}
3954
Alexey Bataeve3727102018-04-18 15:57:46 +00003955bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003956 // Check test-expr for canonical form, save upper-bound UB, flags for
3957 // less/greater and for strict/non-strict comparison.
3958 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3959 // var relational-op b
3960 // b relational-op var
3961 //
3962 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003963 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003964 return true;
3965 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003966 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003967 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003968 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003969 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003970 if (getInitLCDecl(BO->getLHS()) == LCDecl)
3971 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003972 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3973 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3974 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00003975 if (getInitLCDecl(BO->getRHS()) == LCDecl)
3976 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003977 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3978 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3979 BO->getSourceRange(), BO->getOperatorLoc());
3980 }
David Majnemer9d168222016-08-05 17:44:54 +00003981 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003982 if (CE->getNumArgs() == 2) {
3983 auto Op = CE->getOperator();
3984 switch (Op) {
3985 case OO_Greater:
3986 case OO_GreaterEqual:
3987 case OO_Less:
3988 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00003989 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
3990 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003991 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3992 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00003993 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
3994 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003995 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3996 CE->getOperatorLoc());
3997 break;
3998 default:
3999 break;
4000 }
4001 }
4002 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004003 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004004 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004005 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004006 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004007 return true;
4008}
4009
Alexey Bataeve3727102018-04-18 15:57:46 +00004010bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004011 // RHS of canonical loop form increment can be:
4012 // var + incr
4013 // incr + var
4014 // var - incr
4015 //
4016 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004017 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004018 if (BO->isAdditiveOp()) {
4019 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004020 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4021 return setStep(BO->getRHS(), !IsAdd);
4022 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4023 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004024 }
David Majnemer9d168222016-08-05 17:44:54 +00004025 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004026 bool IsAdd = CE->getOperator() == OO_Plus;
4027 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004028 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4029 return setStep(CE->getArg(1), !IsAdd);
4030 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4031 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004032 }
4033 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004034 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004035 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004036 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004037 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004038 return true;
4039}
4040
Alexey Bataeve3727102018-04-18 15:57:46 +00004041bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004042 // Check incr-expr for canonical loop form and return true if it
4043 // does not conform.
4044 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4045 // ++var
4046 // var++
4047 // --var
4048 // var--
4049 // var += incr
4050 // var -= incr
4051 // var = var + incr
4052 // var = incr + var
4053 // var = var - incr
4054 //
4055 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004056 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004057 return true;
4058 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004059 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4060 if (!ExprTemp->cleanupsHaveSideEffects())
4061 S = ExprTemp->getSubExpr();
4062
Alexander Musmana5f070a2014-10-01 06:03:56 +00004063 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004064 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004065 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004066 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004067 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4068 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004069 .ActOnIntegerConstant(UO->getLocStart(),
4070 (UO->isDecrementOp() ? -1 : 1))
4071 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004072 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004073 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004074 switch (BO->getOpcode()) {
4075 case BO_AddAssign:
4076 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004077 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4078 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004079 break;
4080 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004081 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4082 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004083 break;
4084 default:
4085 break;
4086 }
David Majnemer9d168222016-08-05 17:44:54 +00004087 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004088 switch (CE->getOperator()) {
4089 case OO_PlusPlus:
4090 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004091 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4092 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004093 .ActOnIntegerConstant(
4094 CE->getLocStart(),
4095 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4096 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004097 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004098 break;
4099 case OO_PlusEqual:
4100 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004101 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4102 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004103 break;
4104 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004105 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4106 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004107 break;
4108 default:
4109 break;
4110 }
4111 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004112 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004113 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004114 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004115 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004116 return true;
4117}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004118
Alexey Bataev5a3af132016-03-29 08:58:54 +00004119static ExprResult
4120tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004121 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004122 if (SemaRef.CurContext->isDependentContext())
4123 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004124 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4125 return SemaRef.PerformImplicitConversion(
4126 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4127 /*AllowExplicit=*/true);
4128 auto I = Captures.find(Capture);
4129 if (I != Captures.end())
4130 return buildCapture(SemaRef, Capture, I->second);
4131 DeclRefExpr *Ref = nullptr;
4132 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4133 Captures[Capture] = Ref;
4134 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004135}
4136
Alexander Musmana5f070a2014-10-01 06:03:56 +00004137/// \brief Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004138Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004139 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004140 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004141 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004142 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004143 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004144 SemaRef.getLangOpts().CPlusPlus) {
4145 // Upper - Lower
Alexey Bataeve3727102018-04-18 15:57:46 +00004146 Expr *UBExpr = TestIsLessOp ? UB : LB;
4147 Expr *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004148 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4149 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004150 if (!Upper || !Lower)
4151 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004152
4153 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4154
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004155 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004156 // BuildBinOp already emitted error, this one is to point user to upper
4157 // and lower bound, and to tell what is passed to 'operator-'.
4158 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4159 << Upper->getSourceRange() << Lower->getSourceRange();
4160 return nullptr;
4161 }
4162 }
4163
4164 if (!Diff.isUsable())
4165 return nullptr;
4166
4167 // Upper - Lower [- 1]
4168 if (TestIsStrictOp)
4169 Diff = SemaRef.BuildBinOp(
4170 S, DefaultLoc, BO_Sub, Diff.get(),
4171 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4172 if (!Diff.isUsable())
4173 return nullptr;
4174
4175 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004176 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004177 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004178 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004179 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004180 if (!Diff.isUsable())
4181 return nullptr;
4182
4183 // Parentheses (for dumping/debugging purposes only).
4184 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4185 if (!Diff.isUsable())
4186 return nullptr;
4187
4188 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004189 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004190 if (!Diff.isUsable())
4191 return nullptr;
4192
Alexander Musman174b3ca2014-10-06 11:16:29 +00004193 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004194 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004195 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004196 bool UseVarType = VarType->hasIntegerRepresentation() &&
4197 C.getTypeSize(Type) > C.getTypeSize(VarType);
4198 if (!Type->isIntegerType() || UseVarType) {
4199 unsigned NewSize =
4200 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4201 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4202 : Type->hasSignedIntegerRepresentation();
4203 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004204 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4205 Diff = SemaRef.PerformImplicitConversion(
4206 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4207 if (!Diff.isUsable())
4208 return nullptr;
4209 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004210 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004211 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004212 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4213 if (NewSize != C.getTypeSize(Type)) {
4214 if (NewSize < C.getTypeSize(Type)) {
4215 assert(NewSize == 64 && "incorrect loop var size");
4216 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4217 << InitSrcRange << ConditionSrcRange;
4218 }
4219 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004220 NewSize, Type->hasSignedIntegerRepresentation() ||
4221 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004222 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4223 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4224 Sema::AA_Converting, true);
4225 if (!Diff.isUsable())
4226 return nullptr;
4227 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004228 }
4229 }
4230
Alexander Musmana5f070a2014-10-01 06:03:56 +00004231 return Diff.get();
4232}
4233
Alexey Bataeve3727102018-04-18 15:57:46 +00004234Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004235 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004236 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004237 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4238 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4239 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004240
Alexey Bataeve3727102018-04-18 15:57:46 +00004241 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4242 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004243 if (!NewLB.isUsable() || !NewUB.isUsable())
4244 return nullptr;
4245
Alexey Bataeve3727102018-04-18 15:57:46 +00004246 ExprResult CondExpr =
4247 SemaRef.BuildBinOp(S, DefaultLoc,
4248 TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4249 : (TestIsStrictOp ? BO_GT : BO_GE),
4250 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004251 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004252 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4253 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004254 CondExpr = SemaRef.PerformImplicitConversion(
4255 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4256 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004257 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004258 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4259 // Otherwise use original loop conditon and evaluate it in runtime.
4260 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4261}
4262
Alexander Musmana5f070a2014-10-01 06:03:56 +00004263/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004264DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
4265 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004266 auto *VD = dyn_cast<VarDecl>(LCDecl);
4267 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004268 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4269 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004270 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004271 const DSAStackTy::DSAVarData Data =
4272 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004273 // If the loop control decl is explicitly marked as private, do not mark it
4274 // as captured again.
4275 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4276 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004277 return Ref;
4278 }
4279 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004280 DefaultLoc);
4281}
4282
Alexey Bataeve3727102018-04-18 15:57:46 +00004283Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004284 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004285 QualType Type = LCDecl->getType().getNonReferenceType();
4286 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004287 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4288 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4289 isa<VarDecl>(LCDecl)
4290 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4291 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004292 if (PrivateVar->isInvalidDecl())
4293 return nullptr;
4294 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4295 }
4296 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004297}
4298
Samuel Antao4c8035b2016-12-12 18:00:20 +00004299/// \brief Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004300Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004301
4302/// \brief Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004303Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004304
4305/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004306struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004307 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004308 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004309 /// \brief This expression calculates the number of iterations in the loop.
4310 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004311 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004312 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004313 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004314 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004315 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004316 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004317 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004318 /// \brief This is step for the #CounterVar used to generate its update:
4319 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004320 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004321 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004322 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004323 /// \brief Source range of the loop init.
4324 SourceRange InitSrcRange;
4325 /// \brief Source range of the loop condition.
4326 SourceRange CondSrcRange;
4327 /// \brief Source range of the loop increment.
4328 SourceRange IncSrcRange;
4329};
4330
Alexey Bataev23b69422014-06-18 07:08:49 +00004331} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004332
Alexey Bataev9c821032015-04-30 04:23:23 +00004333void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4334 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4335 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004336 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4337 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004338 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4339 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004340 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4341 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004342 auto *VD = dyn_cast<VarDecl>(D);
4343 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004344 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004345 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00004346 } else {
4347 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4348 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004349 VD = cast<VarDecl>(Ref->getDecl());
4350 }
4351 }
4352 DSAStack->addLoopControlVariable(D, VD);
4353 }
4354 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004355 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004356 }
4357}
4358
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004359/// \brief Called on a for stmt to check and extract its iteration space
4360/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00004361static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00004362 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4363 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004364 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00004365 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004366 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00004367 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004368 // OpenMP [2.6, Canonical Loop Form]
4369 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004370 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004371 if (!For) {
4372 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004373 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4374 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4375 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4376 if (NestedLoopCount > 1) {
4377 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4378 SemaRef.Diag(DSA.getConstructLoc(),
4379 diag::note_omp_collapse_ordered_expr)
4380 << 2 << CollapseLoopCountExpr->getSourceRange()
4381 << OrderedLoopCountExpr->getSourceRange();
4382 else if (CollapseLoopCountExpr)
4383 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4384 diag::note_omp_collapse_ordered_expr)
4385 << 0 << CollapseLoopCountExpr->getSourceRange();
4386 else
4387 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4388 diag::note_omp_collapse_ordered_expr)
4389 << 1 << OrderedLoopCountExpr->getSourceRange();
4390 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004391 return true;
4392 }
4393 assert(For->getBody());
4394
4395 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4396
4397 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004398 Stmt *Init = For->getInit();
4399 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004400 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004401
4402 bool HasErrors = false;
4403
4404 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004405 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4406 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004407
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004408 // OpenMP [2.6, Canonical Loop Form]
4409 // Var is one of the following:
4410 // A variable of signed or unsigned integer type.
4411 // For C++, a variable of a random access iterator type.
4412 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004413 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004414 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4415 !VarType->isPointerType() &&
4416 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4417 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4418 << SemaRef.getLangOpts().CPlusPlus;
4419 HasErrors = true;
4420 }
4421
4422 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4423 // a Construct
4424 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4425 // parallel for construct is (are) private.
4426 // The loop iteration variable in the associated for-loop of a simd
4427 // construct with just one associated for-loop is linear with a
4428 // constant-linear-step that is the increment of the associated for-loop.
4429 // Exclude loop var from the list of variables with implicitly defined data
4430 // sharing attributes.
4431 VarsWithImplicitDSA.erase(LCDecl);
4432
4433 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4434 // in a Construct, C/C++].
4435 // The loop iteration variable in the associated for-loop of a simd
4436 // construct with just one associated for-loop may be listed in a linear
4437 // clause with a constant-linear-step that is the increment of the
4438 // associated for-loop.
4439 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4440 // parallel for construct may be listed in a private or lastprivate clause.
4441 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4442 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4443 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00004444 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004445 isOpenMPSimdDirective(DKind)
4446 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4447 : OMPC_private;
4448 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4449 DVar.CKind != PredeterminedCKind) ||
4450 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4451 isOpenMPDistributeDirective(DKind)) &&
4452 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4453 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4454 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4455 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4456 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4457 << getOpenMPClauseName(PredeterminedCKind);
4458 if (DVar.RefExpr == nullptr)
4459 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00004460 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004461 HasErrors = true;
4462 } else if (LoopDeclRefExpr != nullptr) {
4463 // Make the loop iteration variable private (for worksharing constructs),
4464 // linear (for simd directives with the only one associated loop) or
4465 // lastprivate (for simd directives with several collapsed or ordered
4466 // loops).
4467 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004468 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4469 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004470 /*FromParent=*/false);
4471 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4472 }
4473
4474 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4475
4476 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004477 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004478
4479 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004480 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004481 }
4482
Alexey Bataeve3727102018-04-18 15:57:46 +00004483 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004484 return HasErrors;
4485
Alexander Musmana5f070a2014-10-01 06:03:56 +00004486 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004487 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00004488 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4489 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004490 DSA.getCurScope(),
4491 (isOpenMPWorksharingDirective(DKind) ||
4492 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4493 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00004494 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4495 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4496 ResultIterSpace.CounterInit = ISC.buildCounterInit();
4497 ResultIterSpace.CounterStep = ISC.buildCounterStep();
4498 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4499 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4500 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4501 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004502
Alexey Bataev62dbb972015-04-22 11:59:37 +00004503 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4504 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004505 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004506 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004507 ResultIterSpace.CounterInit == nullptr ||
4508 ResultIterSpace.CounterStep == nullptr);
4509
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004510 return HasErrors;
4511}
4512
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004513/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004514static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00004515buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004516 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00004517 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004518 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00004519 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004520 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004521 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004522 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004523 VarRef.get()->getType())) {
4524 NewStart = SemaRef.PerformImplicitConversion(
4525 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4526 /*AllowExplicit=*/true);
4527 if (!NewStart.isUsable())
4528 return ExprError();
4529 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004530
Alexey Bataeve3727102018-04-18 15:57:46 +00004531 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004532 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4533 return Init;
4534}
4535
Alexander Musmana5f070a2014-10-01 06:03:56 +00004536/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00004537static ExprResult buildCounterUpdate(
4538 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4539 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
4540 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004541 // Add parentheses (for debugging purposes only).
4542 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4543 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4544 !Step.isUsable())
4545 return ExprError();
4546
Alexey Bataev5a3af132016-03-29 08:58:54 +00004547 ExprResult NewStep = Step;
4548 if (Captures)
4549 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004550 if (NewStep.isInvalid())
4551 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004552 ExprResult Update =
4553 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004554 if (!Update.isUsable())
4555 return ExprError();
4556
Alexey Bataevc0214e02016-02-16 12:13:49 +00004557 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4558 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004559 ExprResult NewStart = Start;
4560 if (Captures)
4561 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004562 if (NewStart.isInvalid())
4563 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004564
Alexey Bataevc0214e02016-02-16 12:13:49 +00004565 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4566 ExprResult SavedUpdate = Update;
4567 ExprResult UpdateVal;
4568 if (VarRef.get()->getType()->isOverloadableType() ||
4569 NewStart.get()->getType()->isOverloadableType() ||
4570 Update.get()->getType()->isOverloadableType()) {
4571 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4572 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4573 Update =
4574 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4575 if (Update.isUsable()) {
4576 UpdateVal =
4577 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4578 VarRef.get(), SavedUpdate.get());
4579 if (UpdateVal.isUsable()) {
4580 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4581 UpdateVal.get());
4582 }
4583 }
4584 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4585 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004586
Alexey Bataevc0214e02016-02-16 12:13:49 +00004587 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4588 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4589 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4590 NewStart.get(), SavedUpdate.get());
4591 if (!Update.isUsable())
4592 return ExprError();
4593
Alexey Bataev11481f52016-02-17 10:29:05 +00004594 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4595 VarRef.get()->getType())) {
4596 Update = SemaRef.PerformImplicitConversion(
4597 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4598 if (!Update.isUsable())
4599 return ExprError();
4600 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004601
4602 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4603 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004604 return Update;
4605}
4606
4607/// \brief Convert integer expression \a E to make it have at least \a Bits
4608/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00004609static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004610 if (E == nullptr)
4611 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00004612 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004613 QualType OldType = E->getType();
4614 unsigned HasBits = C.getTypeSize(OldType);
4615 if (HasBits >= Bits)
4616 return ExprResult(E);
4617 // OK to convert to signed, because new type has more bits than old.
4618 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4619 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4620 true);
4621}
4622
4623/// \brief Check if the given expression \a E is a constant integer that fits
4624/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00004625static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004626 if (E == nullptr)
4627 return false;
4628 llvm::APSInt Result;
4629 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4630 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4631 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004632}
4633
Alexey Bataev5a3af132016-03-29 08:58:54 +00004634/// Build preinits statement for the given declarations.
4635static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004636 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004637 if (!PreInits.empty()) {
4638 return new (Context) DeclStmt(
4639 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4640 SourceLocation(), SourceLocation());
4641 }
4642 return nullptr;
4643}
4644
4645/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004646static Stmt *
4647buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00004648 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004649 if (!Captures.empty()) {
4650 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00004651 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00004652 PreInits.push_back(Pair.second->getDecl());
4653 return buildPreInits(Context, PreInits);
4654 }
4655 return nullptr;
4656}
4657
4658/// Build postupdate expression for the given list of postupdates expressions.
4659static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4660 Expr *PostUpdate = nullptr;
4661 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004662 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004663 Expr *ConvE = S.BuildCStyleCastExpr(
4664 E->getExprLoc(),
4665 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4666 E->getExprLoc(), E)
4667 .get();
4668 PostUpdate = PostUpdate
4669 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4670 PostUpdate, ConvE)
4671 .get()
4672 : ConvE;
4673 }
4674 }
4675 return PostUpdate;
4676}
4677
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004678/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004679/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4680/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004681static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00004682checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004683 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4684 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00004685 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004686 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004687 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004688 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004689 // Found 'collapse' clause - calculate collapse number.
4690 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004691 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004692 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004693 }
4694 if (OrderedLoopCountExpr) {
4695 // Found 'ordered' clause - calculate collapse number.
4696 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004697 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4698 if (Result.getLimitedValue() < NestedLoopCount) {
4699 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4700 diag::err_omp_wrong_ordered_loop_count)
4701 << OrderedLoopCountExpr->getSourceRange();
4702 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4703 diag::note_collapse_loop_count)
4704 << CollapseLoopCountExpr->getSourceRange();
4705 }
4706 NestedLoopCount = Result.getLimitedValue();
4707 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004708 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004709 // This is helper routine for loop directives (e.g., 'for', 'simd',
4710 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00004711 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004712 SmallVector<LoopIterationSpace, 4> IterSpaces;
4713 IterSpaces.resize(NestedLoopCount);
4714 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004715 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004716 if (checkOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004717 NestedLoopCount, CollapseLoopCountExpr,
4718 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004719 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004720 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004721 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004722 // OpenMP [2.8.1, simd construct, Restrictions]
4723 // All loops associated with the construct must be perfectly nested; that
4724 // is, there must be no intervening code nor any OpenMP directive between
4725 // any two loops.
4726 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004727 }
4728
Alexander Musmana5f070a2014-10-01 06:03:56 +00004729 Built.clear(/* size */ NestedLoopCount);
4730
4731 if (SemaRef.CurContext->isDependentContext())
4732 return NestedLoopCount;
4733
4734 // An example of what is generated for the following code:
4735 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004736 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004737 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004738 // for (k = 0; k < NK; ++k)
4739 // for (j = J0; j < NJ; j+=2) {
4740 // <loop body>
4741 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004742 //
4743 // We generate the code below.
4744 // Note: the loop body may be outlined in CodeGen.
4745 // Note: some counters may be C++ classes, operator- is used to find number of
4746 // iterations and operator+= to calculate counter value.
4747 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4748 // or i64 is currently supported).
4749 //
4750 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4751 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4752 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4753 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4754 // // similar updates for vars in clauses (e.g. 'linear')
4755 // <loop body (using local i and j)>
4756 // }
4757 // i = NI; // assign final values of counters
4758 // j = NJ;
4759 //
4760
4761 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4762 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004763 // Precondition tests if there is at least one iteration (all conditions are
4764 // true).
4765 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00004766 Expr *N0 = IterSpaces[0].NumIterations;
4767 ExprResult LastIteration32 =
4768 widenIterationCount(/*Bits=*/32,
4769 SemaRef
4770 .PerformImplicitConversion(
4771 N0->IgnoreImpCasts(), N0->getType(),
4772 Sema::AA_Converting, /*AllowExplicit=*/true)
4773 .get(),
4774 SemaRef);
4775 ExprResult LastIteration64 = widenIterationCount(
4776 /*Bits=*/64,
4777 SemaRef
4778 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
4779 Sema::AA_Converting,
4780 /*AllowExplicit=*/true)
4781 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004782 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004783
4784 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4785 return NestedLoopCount;
4786
Alexey Bataeve3727102018-04-18 15:57:46 +00004787 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004788 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4789
4790 Scope *CurScope = DSA.getCurScope();
4791 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004792 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004793 PreCond =
4794 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4795 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004796 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004797 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004798 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004799 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4800 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004801 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004802 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004803 SemaRef
4804 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4805 Sema::AA_Converting,
4806 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004807 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004808 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004809 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004810 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004811 SemaRef
4812 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4813 Sema::AA_Converting,
4814 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004815 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004816 }
4817
4818 // Choose either the 32-bit or 64-bit version.
4819 ExprResult LastIteration = LastIteration64;
4820 if (LastIteration32.isUsable() &&
4821 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4822 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004823 fitsInto(
4824 /*Bits=*/32,
Alexander Musmana5f070a2014-10-01 06:03:56 +00004825 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4826 LastIteration64.get(), SemaRef)))
4827 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004828 QualType VType = LastIteration.get()->getType();
4829 QualType RealVType = VType;
4830 QualType StrideVType = VType;
4831 if (isOpenMPTaskLoopDirective(DKind)) {
4832 VType =
4833 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4834 StrideVType =
4835 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4836 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004837
4838 if (!LastIteration.isUsable())
4839 return 0;
4840
4841 // Save the number of iterations.
4842 ExprResult NumIterations = LastIteration;
4843 {
4844 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004845 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4846 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004847 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4848 if (!LastIteration.isUsable())
4849 return 0;
4850 }
4851
4852 // Calculate the last iteration number beforehand instead of doing this on
4853 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4854 llvm::APSInt Result;
4855 bool IsConstant =
4856 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4857 ExprResult CalcLastIteration;
4858 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004859 ExprResult SaveRef =
4860 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004861 LastIteration = SaveRef;
4862
4863 // Prepare SaveRef + 1.
4864 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004865 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004866 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4867 if (!NumIterations.isUsable())
4868 return 0;
4869 }
4870
4871 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4872
David Majnemer9d168222016-08-05 17:44:54 +00004873 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004874 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004875 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4876 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004877 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004878 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4879 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004880 SemaRef.AddInitializerToDecl(LBDecl,
4881 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4882 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004883
4884 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004885 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4886 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004887 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004888 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004889
4890 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4891 // This will be used to implement clause 'lastprivate'.
4892 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004893 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4894 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004895 SemaRef.AddInitializerToDecl(ILDecl,
4896 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4897 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004898
4899 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004900 VarDecl *STDecl =
4901 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4902 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004903 SemaRef.AddInitializerToDecl(STDecl,
4904 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4905 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004906
4907 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004908 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004909 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4910 UB.get(), LastIteration.get());
4911 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4912 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4913 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4914 CondOp.get());
4915 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004916
4917 // If we have a combined directive that combines 'distribute', 'for' or
4918 // 'simd' we need to be able to access the bounds of the schedule of the
4919 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4920 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4921 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00004922 // Lower bound variable, initialized with zero.
4923 VarDecl *CombLBDecl =
4924 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4925 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4926 SemaRef.AddInitializerToDecl(
4927 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4928 /*DirectInit*/ false);
4929
4930 // Upper bound variable, initialized with last iteration number.
4931 VarDecl *CombUBDecl =
4932 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4933 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4934 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4935 /*DirectInit*/ false);
4936
4937 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4938 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4939 ExprResult CombCondOp =
4940 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4941 LastIteration.get(), CombUB.get());
4942 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4943 CombCondOp.get());
4944 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4945
Alexey Bataeve3727102018-04-18 15:57:46 +00004946 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004947 // We expect to have at least 2 more parameters than the 'parallel'
4948 // directive does - the lower and upper bounds of the previous schedule.
4949 assert(CD->getNumParams() >= 4 &&
4950 "Unexpected number of parameters in loop combined directive");
4951
4952 // Set the proper type for the bounds given what we learned from the
4953 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004954 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4955 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00004956
4957 // Previous lower and upper bounds are obtained from the region
4958 // parameters.
4959 PrevLB =
4960 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4961 PrevUB =
4962 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4963 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004964 }
4965
4966 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004967 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004968 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004969 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004970 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4971 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004972 Expr *RHS =
4973 (isOpenMPWorksharingDirective(DKind) ||
4974 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4975 ? LB.get()
4976 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004977 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4978 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004979
4980 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4981 Expr *CombRHS =
4982 (isOpenMPWorksharingDirective(DKind) ||
4983 isOpenMPTaskLoopDirective(DKind) ||
4984 isOpenMPDistributeDirective(DKind))
4985 ? CombLB.get()
4986 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4987 CombInit =
4988 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4989 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4990 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004991 }
4992
Alexander Musmanc6388682014-12-15 07:07:06 +00004993 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004994 SourceLocation CondLoc = AStmt->getLocStart();
Alexander Musmanc6388682014-12-15 07:07:06 +00004995 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004996 (isOpenMPWorksharingDirective(DKind) ||
4997 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004998 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4999 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5000 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00005001 ExprResult CombCond;
5002 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5003 CombCond =
5004 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
5005 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005006 // Loop increment (IV = IV + 1)
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005007 SourceLocation IncLoc = AStmt->getLocStart();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005008 ExprResult Inc =
5009 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5010 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5011 if (!Inc.isUsable())
5012 return 0;
5013 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005014 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
5015 if (!Inc.isUsable())
5016 return 0;
5017
5018 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5019 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005020 // In combined construct, add combined version that use CombLB and CombUB
5021 // base variables for the update
5022 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005023 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5024 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005025 // LB + ST
5026 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5027 if (!NextLB.isUsable())
5028 return 0;
5029 // LB = LB + ST
5030 NextLB =
5031 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
5032 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
5033 if (!NextLB.isUsable())
5034 return 0;
5035 // UB + ST
5036 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5037 if (!NextUB.isUsable())
5038 return 0;
5039 // UB = UB + ST
5040 NextUB =
5041 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
5042 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
5043 if (!NextUB.isUsable())
5044 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005045 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5046 CombNextLB =
5047 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5048 if (!NextLB.isUsable())
5049 return 0;
5050 // LB = LB + ST
5051 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5052 CombNextLB.get());
5053 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
5054 if (!CombNextLB.isUsable())
5055 return 0;
5056 // UB + ST
5057 CombNextUB =
5058 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5059 if (!CombNextUB.isUsable())
5060 return 0;
5061 // UB = UB + ST
5062 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5063 CombNextUB.get());
5064 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
5065 if (!CombNextUB.isUsable())
5066 return 0;
5067 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005068 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005069
Carlo Bertolliffafe102017-04-20 00:39:39 +00005070 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005071 // directive with for as IV = IV + ST; ensure upper bound expression based
5072 // on PrevUB instead of NumIterations - used to implement 'for' when found
5073 // in combination with 'distribute', like in 'distribute parallel for'
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005074 SourceLocation DistIncLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005075 ExprResult DistCond, DistInc, PrevEUB;
5076 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5077 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
5078 assert(DistCond.isUsable() && "distribute cond expr was not built");
5079
5080 DistInc =
5081 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5082 assert(DistInc.isUsable() && "distribute inc expr was not built");
5083 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5084 DistInc.get());
5085 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
5086 assert(DistInc.isUsable() && "distribute inc expr was not built");
5087
5088 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5089 // construct
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005090 SourceLocation DistEUBLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005091 ExprResult IsUBGreater =
5092 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5093 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5094 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5095 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5096 CondOp.get());
5097 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
5098 }
5099
Alexander Musmana5f070a2014-10-01 06:03:56 +00005100 // Build updates and final values of the loop counters.
5101 bool HasErrors = false;
5102 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005103 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005104 Built.Updates.resize(NestedLoopCount);
5105 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00005106 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005107 {
5108 ExprResult Div;
5109 // Go from inner nested loop to outer.
5110 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5111 LoopIterationSpace &IS = IterSpaces[Cnt];
5112 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5113 // Build: Iter = (IV / Div) % IS.NumIters
5114 // where Div is product of previous iterations' IS.NumIters.
5115 ExprResult Iter;
5116 if (Div.isUsable()) {
5117 Iter =
5118 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5119 } else {
5120 Iter = IV;
5121 assert((Cnt == (int)NestedLoopCount - 1) &&
5122 "unusable div expected on first iteration only");
5123 }
5124
5125 if (Cnt != 0 && Iter.isUsable())
5126 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5127 IS.NumIterations);
5128 if (!Iter.isUsable()) {
5129 HasErrors = true;
5130 break;
5131 }
5132
Alexey Bataev39f915b82015-05-08 10:41:21 +00005133 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005134 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005135 DeclRefExpr *CounterVar = buildDeclRefExpr(
5136 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5137 /*RefersToCapture=*/true);
5138 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005139 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005140 if (!Init.isUsable()) {
5141 HasErrors = true;
5142 break;
5143 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005144 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005145 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5146 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005147 if (!Update.isUsable()) {
5148 HasErrors = true;
5149 break;
5150 }
5151
5152 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005153 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005154 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005155 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005156 if (!Final.isUsable()) {
5157 HasErrors = true;
5158 break;
5159 }
5160
5161 // Build Div for the next iteration: Div <- Div * IS.NumIters
5162 if (Cnt != 0) {
5163 if (Div.isUnset())
5164 Div = IS.NumIterations;
5165 else
5166 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5167 IS.NumIterations);
5168
5169 // Add parentheses (for debugging purposes only).
5170 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00005171 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005172 if (!Div.isUsable()) {
5173 HasErrors = true;
5174 break;
5175 }
Alexey Bataev8b427062016-05-25 12:36:08 +00005176 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005177 }
5178 if (!Update.isUsable() || !Final.isUsable()) {
5179 HasErrors = true;
5180 break;
5181 }
5182 // Save results
5183 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005184 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005185 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005186 Built.Updates[Cnt] = Update.get();
5187 Built.Finals[Cnt] = Final.get();
5188 }
5189 }
5190
5191 if (HasErrors)
5192 return 0;
5193
5194 // Save results
5195 Built.IterationVarRef = IV.get();
5196 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005197 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005198 Built.CalcLastIteration =
5199 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005200 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005201 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005202 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005203 Built.Init = Init.get();
5204 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005205 Built.LB = LB.get();
5206 Built.UB = UB.get();
5207 Built.IL = IL.get();
5208 Built.ST = ST.get();
5209 Built.EUB = EUB.get();
5210 Built.NLB = NextLB.get();
5211 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005212 Built.PrevLB = PrevLB.get();
5213 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005214 Built.DistInc = DistInc.get();
5215 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005216 Built.DistCombinedFields.LB = CombLB.get();
5217 Built.DistCombinedFields.UB = CombUB.get();
5218 Built.DistCombinedFields.EUB = CombEUB.get();
5219 Built.DistCombinedFields.Init = CombInit.get();
5220 Built.DistCombinedFields.Cond = CombCond.get();
5221 Built.DistCombinedFields.NLB = CombNextLB.get();
5222 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005223
Alexey Bataev8b427062016-05-25 12:36:08 +00005224 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5225 // Fill data for doacross depend clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +00005226 for (const auto &Pair : DSA.getDoacrossDependClauses()) {
5227 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00005228 Pair.first->setCounterValue(CounterVal);
Alexey Bataeve3727102018-04-18 15:57:46 +00005229 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00005230 if (NestedLoopCount != Pair.second.size() ||
5231 NestedLoopCount != LoopMultipliers.size() + 1) {
5232 // Erroneous case - clause has some problems.
5233 Pair.first->setCounterValue(CounterVal);
5234 continue;
5235 }
5236 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5237 auto I = Pair.second.rbegin();
5238 auto IS = IterSpaces.rbegin();
5239 auto ILM = LoopMultipliers.rbegin();
5240 Expr *UpCounterVal = CounterVal;
5241 Expr *Multiplier = nullptr;
5242 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5243 if (I->first) {
5244 assert(IS->CounterStep);
5245 Expr *NormalizedOffset =
5246 SemaRef
5247 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5248 I->first, IS->CounterStep)
5249 .get();
5250 if (Multiplier) {
5251 NormalizedOffset =
5252 SemaRef
5253 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5254 NormalizedOffset, Multiplier)
5255 .get();
5256 }
5257 assert(I->second == OO_Plus || I->second == OO_Minus);
5258 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005259 UpCounterVal = SemaRef
5260 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5261 UpCounterVal, NormalizedOffset)
5262 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005263 }
5264 Multiplier = *ILM;
5265 ++I;
5266 ++IS;
5267 ++ILM;
5268 }
5269 Pair.first->setCounterValue(UpCounterVal);
5270 }
5271 }
5272
Alexey Bataevabfc0692014-06-25 06:52:00 +00005273 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005274}
5275
Alexey Bataev10e775f2015-07-30 11:36:16 +00005276static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005277 auto CollapseClauses =
5278 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5279 if (CollapseClauses.begin() != CollapseClauses.end())
5280 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005281 return nullptr;
5282}
5283
Alexey Bataev10e775f2015-07-30 11:36:16 +00005284static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005285 auto OrderedClauses =
5286 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5287 if (OrderedClauses.begin() != OrderedClauses.end())
5288 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005289 return nullptr;
5290}
5291
Kelvin Lic5609492016-07-15 04:39:07 +00005292static bool checkSimdlenSafelenSpecified(Sema &S,
5293 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005294 const OMPSafelenClause *Safelen = nullptr;
5295 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00005296
Alexey Bataeve3727102018-04-18 15:57:46 +00005297 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00005298 if (Clause->getClauseKind() == OMPC_safelen)
5299 Safelen = cast<OMPSafelenClause>(Clause);
5300 else if (Clause->getClauseKind() == OMPC_simdlen)
5301 Simdlen = cast<OMPSimdlenClause>(Clause);
5302 if (Safelen && Simdlen)
5303 break;
5304 }
5305
5306 if (Simdlen && Safelen) {
5307 llvm::APSInt SimdlenRes, SafelenRes;
Alexey Bataeve3727102018-04-18 15:57:46 +00005308 const Expr *SimdlenLength = Simdlen->getSimdlen();
5309 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00005310 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5311 SimdlenLength->isInstantiationDependent() ||
5312 SimdlenLength->containsUnexpandedParameterPack())
5313 return false;
5314 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5315 SafelenLength->isInstantiationDependent() ||
5316 SafelenLength->containsUnexpandedParameterPack())
5317 return false;
5318 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5319 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5320 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5321 // If both simdlen and safelen clauses are specified, the value of the
5322 // simdlen parameter must be less than or equal to the value of the safelen
5323 // parameter.
5324 if (SimdlenRes > SafelenRes) {
5325 S.Diag(SimdlenLength->getExprLoc(),
5326 diag::err_omp_wrong_simdlen_safelen_values)
5327 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5328 return true;
5329 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005330 }
5331 return false;
5332}
5333
Alexey Bataeve3727102018-04-18 15:57:46 +00005334StmtResult
5335Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5336 SourceLocation StartLoc, SourceLocation EndLoc,
5337 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005338 if (!AStmt)
5339 return StmtError();
5340
5341 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005342 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005343 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5344 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005345 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005346 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5347 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005348 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005349 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005350
Alexander Musmana5f070a2014-10-01 06:03:56 +00005351 assert((CurContext->isDependentContext() || B.builtAll()) &&
5352 "omp simd loop exprs were not built");
5353
Alexander Musman3276a272015-03-21 10:12:56 +00005354 if (!CurContext->isDependentContext()) {
5355 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005356 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005357 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005358 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005359 B.NumIterations, *this, CurScope,
5360 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005361 return StmtError();
5362 }
5363 }
5364
Kelvin Lic5609492016-07-15 04:39:07 +00005365 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005366 return StmtError();
5367
Reid Kleckner87a31802018-03-12 21:43:02 +00005368 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005369 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5370 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005371}
5372
Alexey Bataeve3727102018-04-18 15:57:46 +00005373StmtResult
5374Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5375 SourceLocation StartLoc, SourceLocation EndLoc,
5376 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005377 if (!AStmt)
5378 return StmtError();
5379
5380 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005381 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005382 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5383 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005384 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005385 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5386 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005387 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005388 return StmtError();
5389
Alexander Musmana5f070a2014-10-01 06:03:56 +00005390 assert((CurContext->isDependentContext() || B.builtAll()) &&
5391 "omp for loop exprs were not built");
5392
Alexey Bataev54acd402015-08-04 11:18:19 +00005393 if (!CurContext->isDependentContext()) {
5394 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005395 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005396 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005397 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005398 B.NumIterations, *this, CurScope,
5399 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005400 return StmtError();
5401 }
5402 }
5403
Reid Kleckner87a31802018-03-12 21:43:02 +00005404 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005405 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005406 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005407}
5408
Alexander Musmanf82886e2014-09-18 05:12:34 +00005409StmtResult Sema::ActOnOpenMPForSimdDirective(
5410 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00005411 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005412 if (!AStmt)
5413 return StmtError();
5414
5415 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005416 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005417 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5418 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005419 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00005420 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00005421 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5422 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005423 if (NestedLoopCount == 0)
5424 return StmtError();
5425
Alexander Musmanc6388682014-12-15 07:07:06 +00005426 assert((CurContext->isDependentContext() || B.builtAll()) &&
5427 "omp for simd loop exprs were not built");
5428
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005429 if (!CurContext->isDependentContext()) {
5430 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005431 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005432 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005433 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005434 B.NumIterations, *this, CurScope,
5435 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005436 return StmtError();
5437 }
5438 }
5439
Kelvin Lic5609492016-07-15 04:39:07 +00005440 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005441 return StmtError();
5442
Reid Kleckner87a31802018-03-12 21:43:02 +00005443 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005444 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5445 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005446}
5447
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005448StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5449 Stmt *AStmt,
5450 SourceLocation StartLoc,
5451 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005452 if (!AStmt)
5453 return StmtError();
5454
5455 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005456 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005457 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005458 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005459 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005460 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005461 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005462 return StmtError();
5463 // All associated statements must be '#pragma omp section' except for
5464 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005465 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005466 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5467 if (SectionStmt)
5468 Diag(SectionStmt->getLocStart(),
5469 diag::err_omp_sections_substmt_not_section);
5470 return StmtError();
5471 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005472 cast<OMPSectionDirective>(SectionStmt)
5473 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005474 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005475 } else {
5476 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5477 return StmtError();
5478 }
5479
Reid Kleckner87a31802018-03-12 21:43:02 +00005480 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005481
Alexey Bataev25e5b442015-09-15 12:52:43 +00005482 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5483 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005484}
5485
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005486StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5487 SourceLocation StartLoc,
5488 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005489 if (!AStmt)
5490 return StmtError();
5491
5492 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005493
Reid Kleckner87a31802018-03-12 21:43:02 +00005494 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005495 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005496
Alexey Bataev25e5b442015-09-15 12:52:43 +00005497 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5498 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005499}
5500
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005501StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5502 Stmt *AStmt,
5503 SourceLocation StartLoc,
5504 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005505 if (!AStmt)
5506 return StmtError();
5507
5508 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005509
Reid Kleckner87a31802018-03-12 21:43:02 +00005510 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005511
Alexey Bataev3255bf32015-01-19 05:20:46 +00005512 // OpenMP [2.7.3, single Construct, Restrictions]
5513 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00005514 const OMPClause *Nowait = nullptr;
5515 const OMPClause *Copyprivate = nullptr;
5516 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00005517 if (Clause->getClauseKind() == OMPC_nowait)
5518 Nowait = Clause;
5519 else if (Clause->getClauseKind() == OMPC_copyprivate)
5520 Copyprivate = Clause;
5521 if (Copyprivate && Nowait) {
5522 Diag(Copyprivate->getLocStart(),
5523 diag::err_omp_single_copyprivate_with_nowait);
5524 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5525 return StmtError();
5526 }
5527 }
5528
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005529 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5530}
5531
Alexander Musman80c22892014-07-17 08:54:58 +00005532StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5533 SourceLocation StartLoc,
5534 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005535 if (!AStmt)
5536 return StmtError();
5537
5538 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005539
Reid Kleckner87a31802018-03-12 21:43:02 +00005540 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00005541
5542 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5543}
5544
Alexey Bataev28c75412015-12-15 08:19:24 +00005545StmtResult Sema::ActOnOpenMPCriticalDirective(
5546 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5547 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005548 if (!AStmt)
5549 return StmtError();
5550
5551 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005552
Alexey Bataev28c75412015-12-15 08:19:24 +00005553 bool ErrorFound = false;
5554 llvm::APSInt Hint;
5555 SourceLocation HintLoc;
5556 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00005557 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00005558 if (C->getClauseKind() == OMPC_hint) {
5559 if (!DirName.getName()) {
5560 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5561 ErrorFound = true;
5562 }
5563 Expr *E = cast<OMPHintClause>(C)->getHint();
5564 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005565 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00005566 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00005567 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00005568 Hint = E->EvaluateKnownConstInt(Context);
5569 HintLoc = C->getLocStart();
5570 }
5571 }
5572 }
5573 if (ErrorFound)
5574 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005575 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00005576 if (Pair.first && DirName.getName() && !DependentHint) {
5577 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5578 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00005579 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00005580 Diag(HintLoc, diag::note_omp_critical_hint_here)
5581 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00005582 else
Alexey Bataev28c75412015-12-15 08:19:24 +00005583 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00005584 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00005585 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5586 << 1
5587 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5588 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00005589 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00005590 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00005591 }
Alexey Bataev28c75412015-12-15 08:19:24 +00005592 }
5593 }
5594
Reid Kleckner87a31802018-03-12 21:43:02 +00005595 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005596
Alexey Bataev28c75412015-12-15 08:19:24 +00005597 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5598 Clauses, AStmt);
5599 if (!Pair.first && DirName.getName() && !DependentHint)
5600 DSAStack->addCriticalWithHint(Dir, Hint);
5601 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005602}
5603
Alexey Bataev4acb8592014-07-07 13:01:15 +00005604StmtResult Sema::ActOnOpenMPParallelForDirective(
5605 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00005606 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005607 if (!AStmt)
5608 return StmtError();
5609
Alexey Bataeve3727102018-04-18 15:57:46 +00005610 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005611 // 1.2.2 OpenMP Language Terminology
5612 // Structured block - An executable statement with a single entry at the
5613 // top and a single exit at the bottom.
5614 // The point of exit cannot be a branch out of the structured block.
5615 // longjmp() and throw() must not violate the entry/exit criteria.
5616 CS->getCapturedDecl()->setNothrow();
5617
Alexander Musmanc6388682014-12-15 07:07:06 +00005618 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005619 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5620 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005621 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00005622 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00005623 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5624 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005625 if (NestedLoopCount == 0)
5626 return StmtError();
5627
Alexander Musmana5f070a2014-10-01 06:03:56 +00005628 assert((CurContext->isDependentContext() || B.builtAll()) &&
5629 "omp parallel for loop exprs were not built");
5630
Alexey Bataev54acd402015-08-04 11:18:19 +00005631 if (!CurContext->isDependentContext()) {
5632 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005633 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005634 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005635 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005636 B.NumIterations, *this, CurScope,
5637 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005638 return StmtError();
5639 }
5640 }
5641
Reid Kleckner87a31802018-03-12 21:43:02 +00005642 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005643 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005644 NestedLoopCount, Clauses, AStmt, B,
5645 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005646}
5647
Alexander Musmane4e893b2014-09-23 09:33:00 +00005648StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5649 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00005650 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005651 if (!AStmt)
5652 return StmtError();
5653
Alexey Bataeve3727102018-04-18 15:57:46 +00005654 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005655 // 1.2.2 OpenMP Language Terminology
5656 // Structured block - An executable statement with a single entry at the
5657 // top and a single exit at the bottom.
5658 // The point of exit cannot be a branch out of the structured block.
5659 // longjmp() and throw() must not violate the entry/exit criteria.
5660 CS->getCapturedDecl()->setNothrow();
5661
Alexander Musmanc6388682014-12-15 07:07:06 +00005662 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005663 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5664 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005665 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00005666 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00005667 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5668 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005669 if (NestedLoopCount == 0)
5670 return StmtError();
5671
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005672 if (!CurContext->isDependentContext()) {
5673 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005674 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005675 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005676 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005677 B.NumIterations, *this, CurScope,
5678 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005679 return StmtError();
5680 }
5681 }
5682
Kelvin Lic5609492016-07-15 04:39:07 +00005683 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005684 return StmtError();
5685
Reid Kleckner87a31802018-03-12 21:43:02 +00005686 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005687 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005688 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005689}
5690
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005691StmtResult
5692Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5693 Stmt *AStmt, SourceLocation StartLoc,
5694 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005695 if (!AStmt)
5696 return StmtError();
5697
5698 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005699 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005700 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005701 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005702 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005703 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005704 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005705 return StmtError();
5706 // All associated statements must be '#pragma omp section' except for
5707 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005708 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005709 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5710 if (SectionStmt)
5711 Diag(SectionStmt->getLocStart(),
5712 diag::err_omp_parallel_sections_substmt_not_section);
5713 return StmtError();
5714 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005715 cast<OMPSectionDirective>(SectionStmt)
5716 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005717 }
5718 } else {
5719 Diag(AStmt->getLocStart(),
5720 diag::err_omp_parallel_sections_not_compound_stmt);
5721 return StmtError();
5722 }
5723
Reid Kleckner87a31802018-03-12 21:43:02 +00005724 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005725
Alexey Bataev25e5b442015-09-15 12:52:43 +00005726 return OMPParallelSectionsDirective::Create(
5727 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005728}
5729
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005730StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5731 Stmt *AStmt, SourceLocation StartLoc,
5732 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005733 if (!AStmt)
5734 return StmtError();
5735
David Majnemer9d168222016-08-05 17:44:54 +00005736 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005737 // 1.2.2 OpenMP Language Terminology
5738 // Structured block - An executable statement with a single entry at the
5739 // top and a single exit at the bottom.
5740 // The point of exit cannot be a branch out of the structured block.
5741 // longjmp() and throw() must not violate the entry/exit criteria.
5742 CS->getCapturedDecl()->setNothrow();
5743
Reid Kleckner87a31802018-03-12 21:43:02 +00005744 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005745
Alexey Bataev25e5b442015-09-15 12:52:43 +00005746 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5747 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005748}
5749
Alexey Bataev68446b72014-07-18 07:47:19 +00005750StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5751 SourceLocation EndLoc) {
5752 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5753}
5754
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005755StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5756 SourceLocation EndLoc) {
5757 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5758}
5759
Alexey Bataev2df347a2014-07-18 10:17:07 +00005760StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5761 SourceLocation EndLoc) {
5762 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5763}
5764
Alexey Bataev169d96a2017-07-18 20:17:46 +00005765StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5766 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005767 SourceLocation StartLoc,
5768 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005769 if (!AStmt)
5770 return StmtError();
5771
5772 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005773
Reid Kleckner87a31802018-03-12 21:43:02 +00005774 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005775
Alexey Bataev169d96a2017-07-18 20:17:46 +00005776 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005777 AStmt,
5778 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005779}
5780
Alexey Bataev6125da92014-07-21 11:26:11 +00005781StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5782 SourceLocation StartLoc,
5783 SourceLocation EndLoc) {
5784 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5785 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5786}
5787
Alexey Bataev346265e2015-09-25 10:37:12 +00005788StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5789 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005790 SourceLocation StartLoc,
5791 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005792 const OMPClause *DependFound = nullptr;
5793 const OMPClause *DependSourceClause = nullptr;
5794 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005795 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00005796 const OMPThreadsClause *TC = nullptr;
5797 const OMPSIMDClause *SC = nullptr;
5798 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005799 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5800 DependFound = C;
5801 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5802 if (DependSourceClause) {
5803 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5804 << getOpenMPDirectiveName(OMPD_ordered)
5805 << getOpenMPClauseName(OMPC_depend) << 2;
5806 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00005807 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00005808 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00005809 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005810 if (DependSinkClause) {
5811 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5812 << 0;
5813 ErrorFound = true;
5814 }
5815 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5816 if (DependSourceClause) {
5817 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5818 << 1;
5819 ErrorFound = true;
5820 }
5821 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005822 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005823 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00005824 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00005825 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005826 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00005827 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005828 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005829 if (!ErrorFound && !SC &&
5830 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005831 // OpenMP [2.8.1,simd Construct, Restrictions]
5832 // An ordered construct with the simd clause is the only OpenMP construct
5833 // that can appear in the simd region.
5834 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005835 ErrorFound = true;
5836 } else if (DependFound && (TC || SC)) {
5837 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5838 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5839 ErrorFound = true;
5840 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5841 Diag(DependFound->getLocStart(),
5842 diag::err_omp_ordered_directive_without_param);
5843 ErrorFound = true;
5844 } else if (TC || Clauses.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005845 if (const Expr *Param = DSAStack->getParentOrderedRegionParam()) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005846 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5847 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5848 << (TC != nullptr);
5849 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5850 ErrorFound = true;
5851 }
5852 }
5853 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005854 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005855
5856 if (AStmt) {
5857 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5858
Reid Kleckner87a31802018-03-12 21:43:02 +00005859 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005860 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005861
5862 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005863}
5864
Alexey Bataev1d160b12015-03-13 12:27:31 +00005865namespace {
5866/// \brief Helper class for checking expression in 'omp atomic [update]'
5867/// construct.
5868class OpenMPAtomicUpdateChecker {
5869 /// \brief Error results for atomic update expressions.
5870 enum ExprAnalysisErrorCode {
5871 /// \brief A statement is not an expression statement.
5872 NotAnExpression,
5873 /// \brief Expression is not builtin binary or unary operation.
5874 NotABinaryOrUnaryExpression,
5875 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5876 NotAnUnaryIncDecExpression,
5877 /// \brief An expression is not of scalar type.
5878 NotAScalarType,
5879 /// \brief A binary operation is not an assignment operation.
5880 NotAnAssignmentOp,
5881 /// \brief RHS part of the binary operation is not a binary expression.
5882 NotABinaryExpression,
5883 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5884 /// expression.
5885 NotABinaryOperator,
5886 /// \brief RHS binary operation does not have reference to the updated LHS
5887 /// part.
5888 NotAnUpdateExpression,
5889 /// \brief No errors is found.
5890 NoError
5891 };
5892 /// \brief Reference to Sema.
5893 Sema &SemaRef;
5894 /// \brief A location for note diagnostics (when error is found).
5895 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005896 /// \brief 'x' lvalue part of the source atomic expression.
5897 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005898 /// \brief 'expr' rvalue part of the source atomic expression.
5899 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005900 /// \brief Helper expression of the form
5901 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5902 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5903 Expr *UpdateExpr;
5904 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5905 /// important for non-associative operations.
5906 bool IsXLHSInRHSPart;
5907 BinaryOperatorKind Op;
5908 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005909 /// \brief true if the source expression is a postfix unary operation, false
5910 /// if it is a prefix unary operation.
5911 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005912
5913public:
5914 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005915 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005916 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005917 /// \brief Check specified statement that it is suitable for 'atomic update'
5918 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005919 /// expression. If DiagId and NoteId == 0, then only check is performed
5920 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005921 /// \param DiagId Diagnostic which should be emitted if error is found.
5922 /// \param NoteId Diagnostic note for the main error message.
5923 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005924 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005925 /// \brief Return the 'x' lvalue part of the source atomic expression.
5926 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005927 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5928 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005929 /// \brief Return the update expression used in calculation of the updated
5930 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5931 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5932 Expr *getUpdateExpr() const { return UpdateExpr; }
5933 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5934 /// false otherwise.
5935 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5936
Alexey Bataevb78ca832015-04-01 03:33:17 +00005937 /// \brief true if the source expression is a postfix unary operation, false
5938 /// if it is a prefix unary operation.
5939 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5940
Alexey Bataev1d160b12015-03-13 12:27:31 +00005941private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005942 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5943 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005944};
5945} // namespace
5946
5947bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5948 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5949 ExprAnalysisErrorCode ErrorFound = NoError;
5950 SourceLocation ErrorLoc, NoteLoc;
5951 SourceRange ErrorRange, NoteRange;
5952 // Allowed constructs are:
5953 // x = x binop expr;
5954 // x = expr binop x;
5955 if (AtomicBinOp->getOpcode() == BO_Assign) {
5956 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00005957 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005958 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5959 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5960 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5961 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005962 Op = AtomicInnerBinOp->getOpcode();
5963 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00005964 Expr *LHS = AtomicInnerBinOp->getLHS();
5965 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005966 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5967 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5968 /*Canonical=*/true);
5969 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5970 /*Canonical=*/true);
5971 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5972 /*Canonical=*/true);
5973 if (XId == LHSId) {
5974 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005975 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005976 } else if (XId == RHSId) {
5977 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005978 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005979 } else {
5980 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5981 ErrorRange = AtomicInnerBinOp->getSourceRange();
5982 NoteLoc = X->getExprLoc();
5983 NoteRange = X->getSourceRange();
5984 ErrorFound = NotAnUpdateExpression;
5985 }
5986 } else {
5987 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5988 ErrorRange = AtomicInnerBinOp->getSourceRange();
5989 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5990 NoteRange = SourceRange(NoteLoc, NoteLoc);
5991 ErrorFound = NotABinaryOperator;
5992 }
5993 } else {
5994 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5995 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5996 ErrorFound = NotABinaryExpression;
5997 }
5998 } else {
5999 ErrorLoc = AtomicBinOp->getExprLoc();
6000 ErrorRange = AtomicBinOp->getSourceRange();
6001 NoteLoc = AtomicBinOp->getOperatorLoc();
6002 NoteRange = SourceRange(NoteLoc, NoteLoc);
6003 ErrorFound = NotAnAssignmentOp;
6004 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006005 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006006 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6007 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6008 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006009 }
6010 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006011 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006012 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006013}
6014
6015bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6016 unsigned NoteId) {
6017 ExprAnalysisErrorCode ErrorFound = NoError;
6018 SourceLocation ErrorLoc, NoteLoc;
6019 SourceRange ErrorRange, NoteRange;
6020 // Allowed constructs are:
6021 // x++;
6022 // x--;
6023 // ++x;
6024 // --x;
6025 // x binop= expr;
6026 // x = x binop expr;
6027 // x = expr binop x;
6028 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6029 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6030 if (AtomicBody->getType()->isScalarType() ||
6031 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006032 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006033 AtomicBody->IgnoreParenImpCasts())) {
6034 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006035 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006036 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006037 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006038 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006039 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006040 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006041 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6042 AtomicBody->IgnoreParenImpCasts())) {
6043 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006044 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006045 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006046 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006047 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006048 // Check for Unary Operation
6049 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006050 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006051 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6052 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006053 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006054 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6055 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006056 } else {
6057 ErrorFound = NotAnUnaryIncDecExpression;
6058 ErrorLoc = AtomicUnaryOp->getExprLoc();
6059 ErrorRange = AtomicUnaryOp->getSourceRange();
6060 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6061 NoteRange = SourceRange(NoteLoc, NoteLoc);
6062 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006063 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006064 ErrorFound = NotABinaryOrUnaryExpression;
6065 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6066 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6067 }
6068 } else {
6069 ErrorFound = NotAScalarType;
6070 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
6071 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6072 }
6073 } else {
6074 ErrorFound = NotAnExpression;
6075 NoteLoc = ErrorLoc = S->getLocStart();
6076 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6077 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006078 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006079 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6080 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6081 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006082 }
6083 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006084 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006085 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006086 // Build an update expression of form 'OpaqueValueExpr(x) binop
6087 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6088 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6089 auto *OVEX = new (SemaRef.getASTContext())
6090 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6091 auto *OVEExpr = new (SemaRef.getASTContext())
6092 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006093 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006094 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6095 IsXLHSInRHSPart ? OVEExpr : OVEX);
6096 if (Update.isInvalid())
6097 return true;
6098 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6099 Sema::AA_Casting);
6100 if (Update.isInvalid())
6101 return true;
6102 UpdateExpr = Update.get();
6103 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006104 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006105}
6106
Alexey Bataev0162e452014-07-22 10:10:35 +00006107StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6108 Stmt *AStmt,
6109 SourceLocation StartLoc,
6110 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006111 if (!AStmt)
6112 return StmtError();
6113
David Majnemer9d168222016-08-05 17:44:54 +00006114 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006115 // 1.2.2 OpenMP Language Terminology
6116 // Structured block - An executable statement with a single entry at the
6117 // top and a single exit at the bottom.
6118 // The point of exit cannot be a branch out of the structured block.
6119 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006120 OpenMPClauseKind AtomicKind = OMPC_unknown;
6121 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006122 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006123 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006124 C->getClauseKind() == OMPC_update ||
6125 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006126 if (AtomicKind != OMPC_unknown) {
6127 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
6128 << SourceRange(C->getLocStart(), C->getLocEnd());
6129 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6130 << getOpenMPClauseName(AtomicKind);
6131 } else {
6132 AtomicKind = C->getClauseKind();
6133 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006134 }
6135 }
6136 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006137
Alexey Bataeve3727102018-04-18 15:57:46 +00006138 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006139 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6140 Body = EWC->getSubExpr();
6141
Alexey Bataev62cec442014-11-18 10:14:22 +00006142 Expr *X = nullptr;
6143 Expr *V = nullptr;
6144 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006145 Expr *UE = nullptr;
6146 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006147 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006148 // OpenMP [2.12.6, atomic Construct]
6149 // In the next expressions:
6150 // * x and v (as applicable) are both l-value expressions with scalar type.
6151 // * During the execution of an atomic region, multiple syntactic
6152 // occurrences of x must designate the same storage location.
6153 // * Neither of v and expr (as applicable) may access the storage location
6154 // designated by x.
6155 // * Neither of x and expr (as applicable) may access the storage location
6156 // designated by v.
6157 // * expr is an expression with scalar type.
6158 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6159 // * binop, binop=, ++, and -- are not overloaded operators.
6160 // * The expression x binop expr must be numerically equivalent to x binop
6161 // (expr). This requirement is satisfied if the operators in expr have
6162 // precedence greater than binop, or by using parentheses around expr or
6163 // subexpressions of expr.
6164 // * The expression expr binop x must be numerically equivalent to (expr)
6165 // binop x. This requirement is satisfied if the operators in expr have
6166 // precedence equal to or greater than binop, or by using parentheses around
6167 // expr or subexpressions of expr.
6168 // * For forms that allow multiple occurrences of x, the number of times
6169 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006170 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006171 enum {
6172 NotAnExpression,
6173 NotAnAssignmentOp,
6174 NotAScalarType,
6175 NotAnLValue,
6176 NoError
6177 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006178 SourceLocation ErrorLoc, NoteLoc;
6179 SourceRange ErrorRange, NoteRange;
6180 // If clause is read:
6181 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006182 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6183 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006184 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6185 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6186 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6187 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6188 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6189 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6190 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006191 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006192 ErrorFound = NotAnLValue;
6193 ErrorLoc = AtomicBinOp->getExprLoc();
6194 ErrorRange = AtomicBinOp->getSourceRange();
6195 NoteLoc = NotLValueExpr->getExprLoc();
6196 NoteRange = NotLValueExpr->getSourceRange();
6197 }
6198 } else if (!X->isInstantiationDependent() ||
6199 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006200 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006201 (X->isInstantiationDependent() || X->getType()->isScalarType())
6202 ? V
6203 : X;
6204 ErrorFound = NotAScalarType;
6205 ErrorLoc = AtomicBinOp->getExprLoc();
6206 ErrorRange = AtomicBinOp->getSourceRange();
6207 NoteLoc = NotScalarExpr->getExprLoc();
6208 NoteRange = NotScalarExpr->getSourceRange();
6209 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006210 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006211 ErrorFound = NotAnAssignmentOp;
6212 ErrorLoc = AtomicBody->getExprLoc();
6213 ErrorRange = AtomicBody->getSourceRange();
6214 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6215 : AtomicBody->getExprLoc();
6216 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6217 : AtomicBody->getSourceRange();
6218 }
6219 } else {
6220 ErrorFound = NotAnExpression;
6221 NoteLoc = ErrorLoc = Body->getLocStart();
6222 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006223 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006224 if (ErrorFound != NoError) {
6225 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6226 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006227 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6228 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006229 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006230 }
6231 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00006232 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006233 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006234 enum {
6235 NotAnExpression,
6236 NotAnAssignmentOp,
6237 NotAScalarType,
6238 NotAnLValue,
6239 NoError
6240 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006241 SourceLocation ErrorLoc, NoteLoc;
6242 SourceRange ErrorRange, NoteRange;
6243 // If clause is write:
6244 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00006245 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6246 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006247 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6248 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006249 X = AtomicBinOp->getLHS();
6250 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006251 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6252 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6253 if (!X->isLValue()) {
6254 ErrorFound = NotAnLValue;
6255 ErrorLoc = AtomicBinOp->getExprLoc();
6256 ErrorRange = AtomicBinOp->getSourceRange();
6257 NoteLoc = X->getExprLoc();
6258 NoteRange = X->getSourceRange();
6259 }
6260 } else if (!X->isInstantiationDependent() ||
6261 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006262 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006263 (X->isInstantiationDependent() || X->getType()->isScalarType())
6264 ? E
6265 : X;
6266 ErrorFound = NotAScalarType;
6267 ErrorLoc = AtomicBinOp->getExprLoc();
6268 ErrorRange = AtomicBinOp->getSourceRange();
6269 NoteLoc = NotScalarExpr->getExprLoc();
6270 NoteRange = NotScalarExpr->getSourceRange();
6271 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006272 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006273 ErrorFound = NotAnAssignmentOp;
6274 ErrorLoc = AtomicBody->getExprLoc();
6275 ErrorRange = AtomicBody->getSourceRange();
6276 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6277 : AtomicBody->getExprLoc();
6278 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6279 : AtomicBody->getSourceRange();
6280 }
6281 } else {
6282 ErrorFound = NotAnExpression;
6283 NoteLoc = ErrorLoc = Body->getLocStart();
6284 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006285 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006286 if (ErrorFound != NoError) {
6287 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6288 << ErrorRange;
6289 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6290 << NoteRange;
6291 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006292 }
6293 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00006294 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006295 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006296 // If clause is update:
6297 // x++;
6298 // x--;
6299 // ++x;
6300 // --x;
6301 // x binop= expr;
6302 // x = x binop expr;
6303 // x = expr binop x;
6304 OpenMPAtomicUpdateChecker Checker(*this);
6305 if (Checker.checkStatement(
6306 Body, (AtomicKind == OMPC_update)
6307 ? diag::err_omp_atomic_update_not_expression_statement
6308 : diag::err_omp_atomic_not_expression_statement,
6309 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006310 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006311 if (!CurContext->isDependentContext()) {
6312 E = Checker.getExpr();
6313 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006314 UE = Checker.getUpdateExpr();
6315 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006316 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006317 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006318 enum {
6319 NotAnAssignmentOp,
6320 NotACompoundStatement,
6321 NotTwoSubstatements,
6322 NotASpecificExpression,
6323 NoError
6324 } ErrorFound = NoError;
6325 SourceLocation ErrorLoc, NoteLoc;
6326 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00006327 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006328 // If clause is a capture:
6329 // v = x++;
6330 // v = x--;
6331 // v = ++x;
6332 // v = --x;
6333 // v = x binop= expr;
6334 // v = x = x binop expr;
6335 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006336 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00006337 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6338 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6339 V = AtomicBinOp->getLHS();
6340 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6341 OpenMPAtomicUpdateChecker Checker(*this);
6342 if (Checker.checkStatement(
6343 Body, diag::err_omp_atomic_capture_not_expression_statement,
6344 diag::note_omp_atomic_update))
6345 return StmtError();
6346 E = Checker.getExpr();
6347 X = Checker.getX();
6348 UE = Checker.getUpdateExpr();
6349 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6350 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006351 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006352 ErrorLoc = AtomicBody->getExprLoc();
6353 ErrorRange = AtomicBody->getSourceRange();
6354 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6355 : AtomicBody->getExprLoc();
6356 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6357 : AtomicBody->getSourceRange();
6358 ErrorFound = NotAnAssignmentOp;
6359 }
6360 if (ErrorFound != NoError) {
6361 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6362 << ErrorRange;
6363 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6364 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006365 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006366 if (CurContext->isDependentContext())
6367 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006368 } else {
6369 // If clause is a capture:
6370 // { v = x; x = expr; }
6371 // { v = x; x++; }
6372 // { v = x; x--; }
6373 // { v = x; ++x; }
6374 // { v = x; --x; }
6375 // { v = x; x binop= expr; }
6376 // { v = x; x = x binop expr; }
6377 // { v = x; x = expr binop x; }
6378 // { x++; v = x; }
6379 // { x--; v = x; }
6380 // { ++x; v = x; }
6381 // { --x; v = x; }
6382 // { x binop= expr; v = x; }
6383 // { x = x binop expr; v = x; }
6384 // { x = expr binop x; v = x; }
6385 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6386 // Check that this is { expr1; expr2; }
6387 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006388 Stmt *First = CS->body_front();
6389 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006390 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6391 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6392 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6393 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6394 // Need to find what subexpression is 'v' and what is 'x'.
6395 OpenMPAtomicUpdateChecker Checker(*this);
6396 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6397 BinaryOperator *BinOp = nullptr;
6398 if (IsUpdateExprFound) {
6399 BinOp = dyn_cast<BinaryOperator>(First);
6400 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6401 }
6402 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6403 // { v = x; x++; }
6404 // { v = x; x--; }
6405 // { v = x; ++x; }
6406 // { v = x; --x; }
6407 // { v = x; x binop= expr; }
6408 // { v = x; x = x binop expr; }
6409 // { v = x; x = expr binop x; }
6410 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006411 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006412 llvm::FoldingSetNodeID XId, PossibleXId;
6413 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6414 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6415 IsUpdateExprFound = XId == PossibleXId;
6416 if (IsUpdateExprFound) {
6417 V = BinOp->getLHS();
6418 X = Checker.getX();
6419 E = Checker.getExpr();
6420 UE = Checker.getUpdateExpr();
6421 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006422 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006423 }
6424 }
6425 if (!IsUpdateExprFound) {
6426 IsUpdateExprFound = !Checker.checkStatement(First);
6427 BinOp = nullptr;
6428 if (IsUpdateExprFound) {
6429 BinOp = dyn_cast<BinaryOperator>(Second);
6430 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6431 }
6432 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6433 // { x++; v = x; }
6434 // { x--; v = x; }
6435 // { ++x; v = x; }
6436 // { --x; v = x; }
6437 // { x binop= expr; v = x; }
6438 // { x = x binop expr; v = x; }
6439 // { x = expr binop x; v = x; }
6440 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006441 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006442 llvm::FoldingSetNodeID XId, PossibleXId;
6443 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6444 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6445 IsUpdateExprFound = XId == PossibleXId;
6446 if (IsUpdateExprFound) {
6447 V = BinOp->getLHS();
6448 X = Checker.getX();
6449 E = Checker.getExpr();
6450 UE = Checker.getUpdateExpr();
6451 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006452 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006453 }
6454 }
6455 }
6456 if (!IsUpdateExprFound) {
6457 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006458 auto *FirstExpr = dyn_cast<Expr>(First);
6459 auto *SecondExpr = dyn_cast<Expr>(Second);
6460 if (!FirstExpr || !SecondExpr ||
6461 !(FirstExpr->isInstantiationDependent() ||
6462 SecondExpr->isInstantiationDependent())) {
6463 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6464 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006465 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006466 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6467 : First->getLocStart();
6468 NoteRange = ErrorRange = FirstBinOp
6469 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006470 : SourceRange(ErrorLoc, ErrorLoc);
6471 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006472 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6473 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6474 ErrorFound = NotAnAssignmentOp;
6475 NoteLoc = ErrorLoc = SecondBinOp
6476 ? SecondBinOp->getOperatorLoc()
6477 : Second->getLocStart();
6478 NoteRange = ErrorRange =
6479 SecondBinOp ? SecondBinOp->getSourceRange()
6480 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006481 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00006482 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00006483 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00006484 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00006485 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6486 llvm::FoldingSetNodeID X1Id, X2Id;
6487 PossibleXRHSInFirst->Profile(X1Id, Context,
6488 /*Canonical=*/true);
6489 PossibleXLHSInSecond->Profile(X2Id, Context,
6490 /*Canonical=*/true);
6491 IsUpdateExprFound = X1Id == X2Id;
6492 if (IsUpdateExprFound) {
6493 V = FirstBinOp->getLHS();
6494 X = SecondBinOp->getLHS();
6495 E = SecondBinOp->getRHS();
6496 UE = nullptr;
6497 IsXLHSInRHSPart = false;
6498 IsPostfixUpdate = true;
6499 } else {
6500 ErrorFound = NotASpecificExpression;
6501 ErrorLoc = FirstBinOp->getExprLoc();
6502 ErrorRange = FirstBinOp->getSourceRange();
6503 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6504 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6505 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006506 }
6507 }
6508 }
6509 }
6510 } else {
6511 NoteLoc = ErrorLoc = Body->getLocStart();
6512 NoteRange = ErrorRange =
6513 SourceRange(Body->getLocStart(), Body->getLocStart());
6514 ErrorFound = NotTwoSubstatements;
6515 }
6516 } else {
6517 NoteLoc = ErrorLoc = Body->getLocStart();
6518 NoteRange = ErrorRange =
6519 SourceRange(Body->getLocStart(), Body->getLocStart());
6520 ErrorFound = NotACompoundStatement;
6521 }
6522 if (ErrorFound != NoError) {
6523 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6524 << ErrorRange;
6525 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6526 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006527 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006528 if (CurContext->isDependentContext())
6529 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00006530 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006531 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006532
Reid Kleckner87a31802018-03-12 21:43:02 +00006533 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00006534
Alexey Bataev62cec442014-11-18 10:14:22 +00006535 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006536 X, V, E, UE, IsXLHSInRHSPart,
6537 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006538}
6539
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006540StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6541 Stmt *AStmt,
6542 SourceLocation StartLoc,
6543 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006544 if (!AStmt)
6545 return StmtError();
6546
Alexey Bataeve3727102018-04-18 15:57:46 +00006547 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006548 // 1.2.2 OpenMP Language Terminology
6549 // Structured block - An executable statement with a single entry at the
6550 // top and a single exit at the bottom.
6551 // The point of exit cannot be a branch out of the structured block.
6552 // longjmp() and throw() must not violate the entry/exit criteria.
6553 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006554 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6555 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6556 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6557 // 1.2.2 OpenMP Language Terminology
6558 // Structured block - An executable statement with a single entry at the
6559 // top and a single exit at the bottom.
6560 // The point of exit cannot be a branch out of the structured block.
6561 // longjmp() and throw() must not violate the entry/exit criteria.
6562 CS->getCapturedDecl()->setNothrow();
6563 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006564
Alexey Bataev13314bf2014-10-09 04:18:56 +00006565 // OpenMP [2.16, Nesting of Regions]
6566 // If specified, a teams construct must be contained within a target
6567 // construct. That target construct must contain no statements or directives
6568 // outside of the teams construct.
6569 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006570 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006571 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006572 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00006573 auto I = CS->body_begin();
6574 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006575 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006576 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6577 OMPTeamsFound = false;
6578 break;
6579 }
6580 ++I;
6581 }
6582 assert(I != CS->body_end() && "Not found statement");
6583 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006584 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00006585 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00006586 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006587 }
6588 if (!OMPTeamsFound) {
6589 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6590 Diag(DSAStack->getInnerTeamsRegionLoc(),
6591 diag::note_omp_nested_teams_construct_here);
6592 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6593 << isa<OMPExecutableDirective>(S);
6594 return StmtError();
6595 }
6596 }
6597
Reid Kleckner87a31802018-03-12 21:43:02 +00006598 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006599
6600 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6601}
6602
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006603StmtResult
6604Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6605 Stmt *AStmt, SourceLocation StartLoc,
6606 SourceLocation EndLoc) {
6607 if (!AStmt)
6608 return StmtError();
6609
Alexey Bataeve3727102018-04-18 15:57:46 +00006610 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006611 // 1.2.2 OpenMP Language Terminology
6612 // Structured block - An executable statement with a single entry at the
6613 // top and a single exit at the bottom.
6614 // The point of exit cannot be a branch out of the structured block.
6615 // longjmp() and throw() must not violate the entry/exit criteria.
6616 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006617 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6618 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6619 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6620 // 1.2.2 OpenMP Language Terminology
6621 // Structured block - An executable statement with a single entry at the
6622 // top and a single exit at the bottom.
6623 // The point of exit cannot be a branch out of the structured block.
6624 // longjmp() and throw() must not violate the entry/exit criteria.
6625 CS->getCapturedDecl()->setNothrow();
6626 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006627
Reid Kleckner87a31802018-03-12 21:43:02 +00006628 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006629
6630 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6631 AStmt);
6632}
6633
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006634StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6635 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006636 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006637 if (!AStmt)
6638 return StmtError();
6639
Alexey Bataeve3727102018-04-18 15:57:46 +00006640 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006641 // 1.2.2 OpenMP Language Terminology
6642 // Structured block - An executable statement with a single entry at the
6643 // top and a single exit at the bottom.
6644 // The point of exit cannot be a branch out of the structured block.
6645 // longjmp() and throw() must not violate the entry/exit criteria.
6646 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006647 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6648 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6649 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6650 // 1.2.2 OpenMP Language Terminology
6651 // Structured block - An executable statement with a single entry at the
6652 // top and a single exit at the bottom.
6653 // The point of exit cannot be a branch out of the structured block.
6654 // longjmp() and throw() must not violate the entry/exit criteria.
6655 CS->getCapturedDecl()->setNothrow();
6656 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006657
6658 OMPLoopDirective::HelperExprs B;
6659 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6660 // define the nested loops number.
6661 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006662 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006663 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006664 VarsWithImplicitDSA, B);
6665 if (NestedLoopCount == 0)
6666 return StmtError();
6667
6668 assert((CurContext->isDependentContext() || B.builtAll()) &&
6669 "omp target parallel for loop exprs were not built");
6670
6671 if (!CurContext->isDependentContext()) {
6672 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006673 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006674 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006675 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006676 B.NumIterations, *this, CurScope,
6677 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006678 return StmtError();
6679 }
6680 }
6681
Reid Kleckner87a31802018-03-12 21:43:02 +00006682 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006683 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6684 NestedLoopCount, Clauses, AStmt,
6685 B, DSAStack->isCancelRegion());
6686}
6687
Alexey Bataev95b64a92017-05-30 16:00:04 +00006688/// Check for existence of a map clause in the list of clauses.
6689static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6690 const OpenMPClauseKind K) {
6691 return llvm::any_of(
6692 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6693}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006694
Alexey Bataev95b64a92017-05-30 16:00:04 +00006695template <typename... Params>
6696static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6697 const Params... ClauseTypes) {
6698 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006699}
6700
Michael Wong65f367f2015-07-21 13:44:28 +00006701StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6702 Stmt *AStmt,
6703 SourceLocation StartLoc,
6704 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006705 if (!AStmt)
6706 return StmtError();
6707
6708 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6709
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006710 // OpenMP [2.10.1, Restrictions, p. 97]
6711 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006712 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6713 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6714 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006715 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006716 return StmtError();
6717 }
6718
Reid Kleckner87a31802018-03-12 21:43:02 +00006719 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00006720
6721 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6722 AStmt);
6723}
6724
Samuel Antaodf67fc42016-01-19 19:15:56 +00006725StmtResult
6726Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6727 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006728 SourceLocation EndLoc, Stmt *AStmt) {
6729 if (!AStmt)
6730 return StmtError();
6731
Alexey Bataeve3727102018-04-18 15:57:46 +00006732 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00006733 // 1.2.2 OpenMP Language Terminology
6734 // Structured block - An executable statement with a single entry at the
6735 // top and a single exit at the bottom.
6736 // The point of exit cannot be a branch out of the structured block.
6737 // longjmp() and throw() must not violate the entry/exit criteria.
6738 CS->getCapturedDecl()->setNothrow();
6739 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6740 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6741 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6742 // 1.2.2 OpenMP Language Terminology
6743 // Structured block - An executable statement with a single entry at the
6744 // top and a single exit at the bottom.
6745 // The point of exit cannot be a branch out of the structured block.
6746 // longjmp() and throw() must not violate the entry/exit criteria.
6747 CS->getCapturedDecl()->setNothrow();
6748 }
6749
Samuel Antaodf67fc42016-01-19 19:15:56 +00006750 // OpenMP [2.10.2, Restrictions, p. 99]
6751 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006752 if (!hasClauses(Clauses, OMPC_map)) {
6753 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6754 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006755 return StmtError();
6756 }
6757
Alexey Bataev7828b252017-11-21 17:08:48 +00006758 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6759 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006760}
6761
Samuel Antao72590762016-01-19 20:04:50 +00006762StmtResult
6763Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6764 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006765 SourceLocation EndLoc, Stmt *AStmt) {
6766 if (!AStmt)
6767 return StmtError();
6768
Alexey Bataeve3727102018-04-18 15:57:46 +00006769 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00006770 // 1.2.2 OpenMP Language Terminology
6771 // Structured block - An executable statement with a single entry at the
6772 // top and a single exit at the bottom.
6773 // The point of exit cannot be a branch out of the structured block.
6774 // longjmp() and throw() must not violate the entry/exit criteria.
6775 CS->getCapturedDecl()->setNothrow();
6776 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6777 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6778 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6779 // 1.2.2 OpenMP Language Terminology
6780 // Structured block - An executable statement with a single entry at the
6781 // top and a single exit at the bottom.
6782 // The point of exit cannot be a branch out of the structured block.
6783 // longjmp() and throw() must not violate the entry/exit criteria.
6784 CS->getCapturedDecl()->setNothrow();
6785 }
6786
Samuel Antao72590762016-01-19 20:04:50 +00006787 // OpenMP [2.10.3, Restrictions, p. 102]
6788 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006789 if (!hasClauses(Clauses, OMPC_map)) {
6790 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6791 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006792 return StmtError();
6793 }
6794
Alexey Bataev7828b252017-11-21 17:08:48 +00006795 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6796 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006797}
6798
Samuel Antao686c70c2016-05-26 17:30:50 +00006799StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6800 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006801 SourceLocation EndLoc,
6802 Stmt *AStmt) {
6803 if (!AStmt)
6804 return StmtError();
6805
Alexey Bataeve3727102018-04-18 15:57:46 +00006806 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00006807 // 1.2.2 OpenMP Language Terminology
6808 // Structured block - An executable statement with a single entry at the
6809 // top and a single exit at the bottom.
6810 // The point of exit cannot be a branch out of the structured block.
6811 // longjmp() and throw() must not violate the entry/exit criteria.
6812 CS->getCapturedDecl()->setNothrow();
6813 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6814 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6815 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6816 // 1.2.2 OpenMP Language Terminology
6817 // Structured block - An executable statement with a single entry at the
6818 // top and a single exit at the bottom.
6819 // The point of exit cannot be a branch out of the structured block.
6820 // longjmp() and throw() must not violate the entry/exit criteria.
6821 CS->getCapturedDecl()->setNothrow();
6822 }
6823
Alexey Bataev95b64a92017-05-30 16:00:04 +00006824 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006825 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6826 return StmtError();
6827 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006828 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6829 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006830}
6831
Alexey Bataev13314bf2014-10-09 04:18:56 +00006832StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6833 Stmt *AStmt, SourceLocation StartLoc,
6834 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006835 if (!AStmt)
6836 return StmtError();
6837
Alexey Bataeve3727102018-04-18 15:57:46 +00006838 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006839 // 1.2.2 OpenMP Language Terminology
6840 // Structured block - An executable statement with a single entry at the
6841 // top and a single exit at the bottom.
6842 // The point of exit cannot be a branch out of the structured block.
6843 // longjmp() and throw() must not violate the entry/exit criteria.
6844 CS->getCapturedDecl()->setNothrow();
6845
Reid Kleckner87a31802018-03-12 21:43:02 +00006846 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00006847
Alexey Bataevceabd412017-11-30 18:01:54 +00006848 DSAStack->setParentTeamsRegionLoc(StartLoc);
6849
Alexey Bataev13314bf2014-10-09 04:18:56 +00006850 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6851}
6852
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006853StmtResult
6854Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6855 SourceLocation EndLoc,
6856 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006857 if (DSAStack->isParentNowaitRegion()) {
6858 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6859 return StmtError();
6860 }
6861 if (DSAStack->isParentOrderedRegion()) {
6862 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6863 return StmtError();
6864 }
6865 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6866 CancelRegion);
6867}
6868
Alexey Bataev87933c72015-09-18 08:07:34 +00006869StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6870 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006871 SourceLocation EndLoc,
6872 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006873 if (DSAStack->isParentNowaitRegion()) {
6874 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6875 return StmtError();
6876 }
6877 if (DSAStack->isParentOrderedRegion()) {
6878 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6879 return StmtError();
6880 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006881 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006882 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6883 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006884}
6885
Alexey Bataev382967a2015-12-08 12:06:20 +00006886static bool checkGrainsizeNumTasksClauses(Sema &S,
6887 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006888 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00006889 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006890 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00006891 if (C->getClauseKind() == OMPC_grainsize ||
6892 C->getClauseKind() == OMPC_num_tasks) {
6893 if (!PrevClause)
6894 PrevClause = C;
6895 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6896 S.Diag(C->getLocStart(),
6897 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6898 << getOpenMPClauseName(C->getClauseKind())
6899 << getOpenMPClauseName(PrevClause->getClauseKind());
6900 S.Diag(PrevClause->getLocStart(),
6901 diag::note_omp_previous_grainsize_num_tasks)
6902 << getOpenMPClauseName(PrevClause->getClauseKind());
6903 ErrorFound = true;
6904 }
6905 }
6906 }
6907 return ErrorFound;
6908}
6909
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006910static bool checkReductionClauseWithNogroup(Sema &S,
6911 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006912 const OMPClause *ReductionClause = nullptr;
6913 const OMPClause *NogroupClause = nullptr;
6914 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006915 if (C->getClauseKind() == OMPC_reduction) {
6916 ReductionClause = C;
6917 if (NogroupClause)
6918 break;
6919 continue;
6920 }
6921 if (C->getClauseKind() == OMPC_nogroup) {
6922 NogroupClause = C;
6923 if (ReductionClause)
6924 break;
6925 continue;
6926 }
6927 }
6928 if (ReductionClause && NogroupClause) {
6929 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6930 << SourceRange(NogroupClause->getLocStart(),
6931 NogroupClause->getLocEnd());
6932 return true;
6933 }
6934 return false;
6935}
6936
Alexey Bataev49f6e782015-12-01 04:18:41 +00006937StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6938 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006939 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006940 if (!AStmt)
6941 return StmtError();
6942
6943 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6944 OMPLoopDirective::HelperExprs B;
6945 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6946 // define the nested loops number.
6947 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006948 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006949 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006950 VarsWithImplicitDSA, B);
6951 if (NestedLoopCount == 0)
6952 return StmtError();
6953
6954 assert((CurContext->isDependentContext() || B.builtAll()) &&
6955 "omp for loop exprs were not built");
6956
Alexey Bataev382967a2015-12-08 12:06:20 +00006957 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6958 // The grainsize clause and num_tasks clause are mutually exclusive and may
6959 // not appear on the same taskloop directive.
6960 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6961 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006962 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6963 // If a reduction clause is present on the taskloop directive, the nogroup
6964 // clause must not be specified.
6965 if (checkReductionClauseWithNogroup(*this, Clauses))
6966 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006967
Reid Kleckner87a31802018-03-12 21:43:02 +00006968 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00006969 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6970 NestedLoopCount, Clauses, AStmt, B);
6971}
6972
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006973StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6974 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006975 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006976 if (!AStmt)
6977 return StmtError();
6978
6979 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6980 OMPLoopDirective::HelperExprs B;
6981 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6982 // define the nested loops number.
6983 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006984 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006985 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6986 VarsWithImplicitDSA, B);
6987 if (NestedLoopCount == 0)
6988 return StmtError();
6989
6990 assert((CurContext->isDependentContext() || B.builtAll()) &&
6991 "omp for loop exprs were not built");
6992
Alexey Bataev5a3af132016-03-29 08:58:54 +00006993 if (!CurContext->isDependentContext()) {
6994 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006995 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006996 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006997 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006998 B.NumIterations, *this, CurScope,
6999 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007000 return StmtError();
7001 }
7002 }
7003
Alexey Bataev382967a2015-12-08 12:06:20 +00007004 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7005 // The grainsize clause and num_tasks clause are mutually exclusive and may
7006 // not appear on the same taskloop directive.
7007 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7008 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007009 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7010 // If a reduction clause is present on the taskloop directive, the nogroup
7011 // clause must not be specified.
7012 if (checkReductionClauseWithNogroup(*this, Clauses))
7013 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007014 if (checkSimdlenSafelenSpecified(*this, Clauses))
7015 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007016
Reid Kleckner87a31802018-03-12 21:43:02 +00007017 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007018 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7019 NestedLoopCount, Clauses, AStmt, B);
7020}
7021
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007022StmtResult Sema::ActOnOpenMPDistributeDirective(
7023 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007024 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007025 if (!AStmt)
7026 return StmtError();
7027
7028 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7029 OMPLoopDirective::HelperExprs B;
7030 // In presence of clause 'collapse' with number of loops, it will
7031 // define the nested loops number.
7032 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007033 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007034 nullptr /*ordered not a clause on distribute*/, AStmt,
7035 *this, *DSAStack, VarsWithImplicitDSA, B);
7036 if (NestedLoopCount == 0)
7037 return StmtError();
7038
7039 assert((CurContext->isDependentContext() || B.builtAll()) &&
7040 "omp for loop exprs were not built");
7041
Reid Kleckner87a31802018-03-12 21:43:02 +00007042 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007043 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7044 NestedLoopCount, Clauses, AStmt, B);
7045}
7046
Carlo Bertolli9925f152016-06-27 14:55:37 +00007047StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7048 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007049 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007050 if (!AStmt)
7051 return StmtError();
7052
Alexey Bataeve3727102018-04-18 15:57:46 +00007053 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007054 // 1.2.2 OpenMP Language Terminology
7055 // Structured block - An executable statement with a single entry at the
7056 // top and a single exit at the bottom.
7057 // The point of exit cannot be a branch out of the structured block.
7058 // longjmp() and throw() must not violate the entry/exit criteria.
7059 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007060 for (int ThisCaptureLevel =
7061 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7062 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7063 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7064 // 1.2.2 OpenMP Language Terminology
7065 // Structured block - An executable statement with a single entry at the
7066 // top and a single exit at the bottom.
7067 // The point of exit cannot be a branch out of the structured block.
7068 // longjmp() and throw() must not violate the entry/exit criteria.
7069 CS->getCapturedDecl()->setNothrow();
7070 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007071
7072 OMPLoopDirective::HelperExprs B;
7073 // In presence of clause 'collapse' with number of loops, it will
7074 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007075 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007076 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007077 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007078 VarsWithImplicitDSA, B);
7079 if (NestedLoopCount == 0)
7080 return StmtError();
7081
7082 assert((CurContext->isDependentContext() || B.builtAll()) &&
7083 "omp for loop exprs were not built");
7084
Reid Kleckner87a31802018-03-12 21:43:02 +00007085 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007086 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007087 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7088 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007089}
7090
Kelvin Li4a39add2016-07-05 05:00:15 +00007091StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7092 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007093 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007094 if (!AStmt)
7095 return StmtError();
7096
Alexey Bataeve3727102018-04-18 15:57:46 +00007097 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007098 // 1.2.2 OpenMP Language Terminology
7099 // Structured block - An executable statement with a single entry at the
7100 // top and a single exit at the bottom.
7101 // The point of exit cannot be a branch out of the structured block.
7102 // longjmp() and throw() must not violate the entry/exit criteria.
7103 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007104 for (int ThisCaptureLevel =
7105 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7106 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7107 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7108 // 1.2.2 OpenMP Language Terminology
7109 // Structured block - An executable statement with a single entry at the
7110 // top and a single exit at the bottom.
7111 // The point of exit cannot be a branch out of the structured block.
7112 // longjmp() and throw() must not violate the entry/exit criteria.
7113 CS->getCapturedDecl()->setNothrow();
7114 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007115
7116 OMPLoopDirective::HelperExprs B;
7117 // In presence of clause 'collapse' with number of loops, it will
7118 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007119 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007120 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007121 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007122 VarsWithImplicitDSA, B);
7123 if (NestedLoopCount == 0)
7124 return StmtError();
7125
7126 assert((CurContext->isDependentContext() || B.builtAll()) &&
7127 "omp for loop exprs were not built");
7128
Alexey Bataev438388c2017-11-22 18:34:02 +00007129 if (!CurContext->isDependentContext()) {
7130 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007131 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007132 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7133 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7134 B.NumIterations, *this, CurScope,
7135 DSAStack))
7136 return StmtError();
7137 }
7138 }
7139
Kelvin Lic5609492016-07-15 04:39:07 +00007140 if (checkSimdlenSafelenSpecified(*this, Clauses))
7141 return StmtError();
7142
Reid Kleckner87a31802018-03-12 21:43:02 +00007143 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007144 return OMPDistributeParallelForSimdDirective::Create(
7145 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7146}
7147
Kelvin Li787f3fc2016-07-06 04:45:38 +00007148StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7149 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007150 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007151 if (!AStmt)
7152 return StmtError();
7153
Alexey Bataeve3727102018-04-18 15:57:46 +00007154 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007155 // 1.2.2 OpenMP Language Terminology
7156 // Structured block - An executable statement with a single entry at the
7157 // top and a single exit at the bottom.
7158 // The point of exit cannot be a branch out of the structured block.
7159 // longjmp() and throw() must not violate the entry/exit criteria.
7160 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007161 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7162 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7163 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7164 // 1.2.2 OpenMP Language Terminology
7165 // Structured block - An executable statement with a single entry at the
7166 // top and a single exit at the bottom.
7167 // The point of exit cannot be a branch out of the structured block.
7168 // longjmp() and throw() must not violate the entry/exit criteria.
7169 CS->getCapturedDecl()->setNothrow();
7170 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007171
7172 OMPLoopDirective::HelperExprs B;
7173 // In presence of clause 'collapse' with number of loops, it will
7174 // define the nested loops number.
7175 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007176 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007177 nullptr /*ordered not a clause on distribute*/, CS, *this,
7178 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007179 if (NestedLoopCount == 0)
7180 return StmtError();
7181
7182 assert((CurContext->isDependentContext() || B.builtAll()) &&
7183 "omp for loop exprs were not built");
7184
Alexey Bataev438388c2017-11-22 18:34:02 +00007185 if (!CurContext->isDependentContext()) {
7186 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007187 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007188 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7189 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7190 B.NumIterations, *this, CurScope,
7191 DSAStack))
7192 return StmtError();
7193 }
7194 }
7195
Kelvin Lic5609492016-07-15 04:39:07 +00007196 if (checkSimdlenSafelenSpecified(*this, Clauses))
7197 return StmtError();
7198
Reid Kleckner87a31802018-03-12 21:43:02 +00007199 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007200 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7201 NestedLoopCount, Clauses, AStmt, B);
7202}
7203
Kelvin Lia579b912016-07-14 02:54:56 +00007204StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7205 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007206 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007207 if (!AStmt)
7208 return StmtError();
7209
Alexey Bataeve3727102018-04-18 15:57:46 +00007210 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00007211 // 1.2.2 OpenMP Language Terminology
7212 // Structured block - An executable statement with a single entry at the
7213 // top and a single exit at the bottom.
7214 // The point of exit cannot be a branch out of the structured block.
7215 // longjmp() and throw() must not violate the entry/exit criteria.
7216 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007217 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7218 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7219 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7220 // 1.2.2 OpenMP Language Terminology
7221 // Structured block - An executable statement with a single entry at the
7222 // top and a single exit at the bottom.
7223 // The point of exit cannot be a branch out of the structured block.
7224 // longjmp() and throw() must not violate the entry/exit criteria.
7225 CS->getCapturedDecl()->setNothrow();
7226 }
Kelvin Lia579b912016-07-14 02:54:56 +00007227
7228 OMPLoopDirective::HelperExprs B;
7229 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7230 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007231 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00007232 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007233 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007234 VarsWithImplicitDSA, B);
7235 if (NestedLoopCount == 0)
7236 return StmtError();
7237
7238 assert((CurContext->isDependentContext() || B.builtAll()) &&
7239 "omp target parallel for simd loop exprs were not built");
7240
7241 if (!CurContext->isDependentContext()) {
7242 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007243 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007244 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007245 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7246 B.NumIterations, *this, CurScope,
7247 DSAStack))
7248 return StmtError();
7249 }
7250 }
Kelvin Lic5609492016-07-15 04:39:07 +00007251 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007252 return StmtError();
7253
Reid Kleckner87a31802018-03-12 21:43:02 +00007254 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007255 return OMPTargetParallelForSimdDirective::Create(
7256 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7257}
7258
Kelvin Li986330c2016-07-20 22:57:10 +00007259StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7260 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007261 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00007262 if (!AStmt)
7263 return StmtError();
7264
Alexey Bataeve3727102018-04-18 15:57:46 +00007265 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00007266 // 1.2.2 OpenMP Language Terminology
7267 // Structured block - An executable statement with a single entry at the
7268 // top and a single exit at the bottom.
7269 // The point of exit cannot be a branch out of the structured block.
7270 // longjmp() and throw() must not violate the entry/exit criteria.
7271 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007272 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7273 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7274 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7275 // 1.2.2 OpenMP Language Terminology
7276 // Structured block - An executable statement with a single entry at the
7277 // top and a single exit at the bottom.
7278 // The point of exit cannot be a branch out of the structured block.
7279 // longjmp() and throw() must not violate the entry/exit criteria.
7280 CS->getCapturedDecl()->setNothrow();
7281 }
7282
Kelvin Li986330c2016-07-20 22:57:10 +00007283 OMPLoopDirective::HelperExprs B;
7284 // In presence of clause 'collapse' with number of loops, it will define the
7285 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007286 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007287 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007288 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007289 VarsWithImplicitDSA, B);
7290 if (NestedLoopCount == 0)
7291 return StmtError();
7292
7293 assert((CurContext->isDependentContext() || B.builtAll()) &&
7294 "omp target simd loop exprs were not built");
7295
7296 if (!CurContext->isDependentContext()) {
7297 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007298 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007299 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007300 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7301 B.NumIterations, *this, CurScope,
7302 DSAStack))
7303 return StmtError();
7304 }
7305 }
7306
7307 if (checkSimdlenSafelenSpecified(*this, Clauses))
7308 return StmtError();
7309
Reid Kleckner87a31802018-03-12 21:43:02 +00007310 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007311 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7312 NestedLoopCount, Clauses, AStmt, B);
7313}
7314
Kelvin Li02532872016-08-05 14:37:37 +00007315StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7316 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007317 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00007318 if (!AStmt)
7319 return StmtError();
7320
Alexey Bataeve3727102018-04-18 15:57:46 +00007321 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00007322 // 1.2.2 OpenMP Language Terminology
7323 // Structured block - An executable statement with a single entry at the
7324 // top and a single exit at the bottom.
7325 // The point of exit cannot be a branch out of the structured block.
7326 // longjmp() and throw() must not violate the entry/exit criteria.
7327 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007328 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7329 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7330 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7331 // 1.2.2 OpenMP Language Terminology
7332 // Structured block - An executable statement with a single entry at the
7333 // top and a single exit at the bottom.
7334 // The point of exit cannot be a branch out of the structured block.
7335 // longjmp() and throw() must not violate the entry/exit criteria.
7336 CS->getCapturedDecl()->setNothrow();
7337 }
Kelvin Li02532872016-08-05 14:37:37 +00007338
7339 OMPLoopDirective::HelperExprs B;
7340 // In presence of clause 'collapse' with number of loops, it will
7341 // define the nested loops number.
7342 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007343 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007344 nullptr /*ordered not a clause on distribute*/, CS, *this,
7345 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007346 if (NestedLoopCount == 0)
7347 return StmtError();
7348
7349 assert((CurContext->isDependentContext() || B.builtAll()) &&
7350 "omp teams distribute loop exprs were not built");
7351
Reid Kleckner87a31802018-03-12 21:43:02 +00007352 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007353
7354 DSAStack->setParentTeamsRegionLoc(StartLoc);
7355
David Majnemer9d168222016-08-05 17:44:54 +00007356 return OMPTeamsDistributeDirective::Create(
7357 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007358}
7359
Kelvin Li4e325f72016-10-25 12:50:55 +00007360StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7361 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007362 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007363 if (!AStmt)
7364 return StmtError();
7365
Alexey Bataeve3727102018-04-18 15:57:46 +00007366 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00007367 // 1.2.2 OpenMP Language Terminology
7368 // Structured block - An executable statement with a single entry at the
7369 // top and a single exit at the bottom.
7370 // The point of exit cannot be a branch out of the structured block.
7371 // longjmp() and throw() must not violate the entry/exit criteria.
7372 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007373 for (int ThisCaptureLevel =
7374 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7375 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7376 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7377 // 1.2.2 OpenMP Language Terminology
7378 // Structured block - An executable statement with a single entry at the
7379 // top and a single exit at the bottom.
7380 // The point of exit cannot be a branch out of the structured block.
7381 // longjmp() and throw() must not violate the entry/exit criteria.
7382 CS->getCapturedDecl()->setNothrow();
7383 }
7384
Kelvin Li4e325f72016-10-25 12:50:55 +00007385
7386 OMPLoopDirective::HelperExprs B;
7387 // In presence of clause 'collapse' with number of loops, it will
7388 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007389 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00007390 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007391 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007392 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007393
7394 if (NestedLoopCount == 0)
7395 return StmtError();
7396
7397 assert((CurContext->isDependentContext() || B.builtAll()) &&
7398 "omp teams distribute simd loop exprs were not built");
7399
7400 if (!CurContext->isDependentContext()) {
7401 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007402 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007403 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7404 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7405 B.NumIterations, *this, CurScope,
7406 DSAStack))
7407 return StmtError();
7408 }
7409 }
7410
7411 if (checkSimdlenSafelenSpecified(*this, Clauses))
7412 return StmtError();
7413
Reid Kleckner87a31802018-03-12 21:43:02 +00007414 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007415
7416 DSAStack->setParentTeamsRegionLoc(StartLoc);
7417
Kelvin Li4e325f72016-10-25 12:50:55 +00007418 return OMPTeamsDistributeSimdDirective::Create(
7419 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7420}
7421
Kelvin Li579e41c2016-11-30 23:51:03 +00007422StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7423 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007424 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00007425 if (!AStmt)
7426 return StmtError();
7427
Alexey Bataeve3727102018-04-18 15:57:46 +00007428 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00007429 // 1.2.2 OpenMP Language Terminology
7430 // Structured block - An executable statement with a single entry at the
7431 // top and a single exit at the bottom.
7432 // The point of exit cannot be a branch out of the structured block.
7433 // longjmp() and throw() must not violate the entry/exit criteria.
7434 CS->getCapturedDecl()->setNothrow();
7435
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007436 for (int ThisCaptureLevel =
7437 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7438 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7439 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7440 // 1.2.2 OpenMP Language Terminology
7441 // Structured block - An executable statement with a single entry at the
7442 // top and a single exit at the bottom.
7443 // The point of exit cannot be a branch out of the structured block.
7444 // longjmp() and throw() must not violate the entry/exit criteria.
7445 CS->getCapturedDecl()->setNothrow();
7446 }
7447
Kelvin Li579e41c2016-11-30 23:51:03 +00007448 OMPLoopDirective::HelperExprs B;
7449 // In presence of clause 'collapse' with number of loops, it will
7450 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007451 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00007452 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007453 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00007454 VarsWithImplicitDSA, B);
7455
7456 if (NestedLoopCount == 0)
7457 return StmtError();
7458
7459 assert((CurContext->isDependentContext() || B.builtAll()) &&
7460 "omp for loop exprs were not built");
7461
7462 if (!CurContext->isDependentContext()) {
7463 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007464 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00007465 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7466 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7467 B.NumIterations, *this, CurScope,
7468 DSAStack))
7469 return StmtError();
7470 }
7471 }
7472
7473 if (checkSimdlenSafelenSpecified(*this, Clauses))
7474 return StmtError();
7475
Reid Kleckner87a31802018-03-12 21:43:02 +00007476 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007477
7478 DSAStack->setParentTeamsRegionLoc(StartLoc);
7479
Kelvin Li579e41c2016-11-30 23:51:03 +00007480 return OMPTeamsDistributeParallelForSimdDirective::Create(
7481 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7482}
7483
Kelvin Li7ade93f2016-12-09 03:24:30 +00007484StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007486 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00007487 if (!AStmt)
7488 return StmtError();
7489
Alexey Bataeve3727102018-04-18 15:57:46 +00007490 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00007491 // 1.2.2 OpenMP Language Terminology
7492 // Structured block - An executable statement with a single entry at the
7493 // top and a single exit at the bottom.
7494 // The point of exit cannot be a branch out of the structured block.
7495 // longjmp() and throw() must not violate the entry/exit criteria.
7496 CS->getCapturedDecl()->setNothrow();
7497
Carlo Bertolli62fae152017-11-20 20:46:39 +00007498 for (int ThisCaptureLevel =
7499 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7500 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7501 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7502 // 1.2.2 OpenMP Language Terminology
7503 // Structured block - An executable statement with a single entry at the
7504 // top and a single exit at the bottom.
7505 // The point of exit cannot be a branch out of the structured block.
7506 // longjmp() and throw() must not violate the entry/exit criteria.
7507 CS->getCapturedDecl()->setNothrow();
7508 }
7509
Kelvin Li7ade93f2016-12-09 03:24:30 +00007510 OMPLoopDirective::HelperExprs B;
7511 // In presence of clause 'collapse' with number of loops, it will
7512 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007513 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00007514 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007515 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007516 VarsWithImplicitDSA, B);
7517
7518 if (NestedLoopCount == 0)
7519 return StmtError();
7520
7521 assert((CurContext->isDependentContext() || B.builtAll()) &&
7522 "omp for loop exprs were not built");
7523
Reid Kleckner87a31802018-03-12 21:43:02 +00007524 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007525
7526 DSAStack->setParentTeamsRegionLoc(StartLoc);
7527
Kelvin Li7ade93f2016-12-09 03:24:30 +00007528 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007529 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7530 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007531}
7532
Kelvin Libf594a52016-12-17 05:48:59 +00007533StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7534 Stmt *AStmt,
7535 SourceLocation StartLoc,
7536 SourceLocation EndLoc) {
7537 if (!AStmt)
7538 return StmtError();
7539
Alexey Bataeve3727102018-04-18 15:57:46 +00007540 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00007541 // 1.2.2 OpenMP Language Terminology
7542 // Structured block - An executable statement with a single entry at the
7543 // top and a single exit at the bottom.
7544 // The point of exit cannot be a branch out of the structured block.
7545 // longjmp() and throw() must not violate the entry/exit criteria.
7546 CS->getCapturedDecl()->setNothrow();
7547
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007548 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7549 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7550 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7551 // 1.2.2 OpenMP Language Terminology
7552 // Structured block - An executable statement with a single entry at the
7553 // top and a single exit at the bottom.
7554 // The point of exit cannot be a branch out of the structured block.
7555 // longjmp() and throw() must not violate the entry/exit criteria.
7556 CS->getCapturedDecl()->setNothrow();
7557 }
Reid Kleckner87a31802018-03-12 21:43:02 +00007558 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00007559
7560 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7561 AStmt);
7562}
7563
Kelvin Li83c451e2016-12-25 04:52:54 +00007564StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7565 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007566 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00007567 if (!AStmt)
7568 return StmtError();
7569
Alexey Bataeve3727102018-04-18 15:57:46 +00007570 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00007571 // 1.2.2 OpenMP Language Terminology
7572 // Structured block - An executable statement with a single entry at the
7573 // top and a single exit at the bottom.
7574 // The point of exit cannot be a branch out of the structured block.
7575 // longjmp() and throw() must not violate the entry/exit criteria.
7576 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007577 for (int ThisCaptureLevel =
7578 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7579 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7580 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7581 // 1.2.2 OpenMP Language Terminology
7582 // Structured block - An executable statement with a single entry at the
7583 // top and a single exit at the bottom.
7584 // The point of exit cannot be a branch out of the structured block.
7585 // longjmp() and throw() must not violate the entry/exit criteria.
7586 CS->getCapturedDecl()->setNothrow();
7587 }
Kelvin Li83c451e2016-12-25 04:52:54 +00007588
7589 OMPLoopDirective::HelperExprs B;
7590 // In presence of clause 'collapse' with number of loops, it will
7591 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007592 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007593 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7594 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00007595 VarsWithImplicitDSA, B);
7596 if (NestedLoopCount == 0)
7597 return StmtError();
7598
7599 assert((CurContext->isDependentContext() || B.builtAll()) &&
7600 "omp target teams distribute loop exprs were not built");
7601
Reid Kleckner87a31802018-03-12 21:43:02 +00007602 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00007603 return OMPTargetTeamsDistributeDirective::Create(
7604 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7605}
7606
Kelvin Li80e8f562016-12-29 22:16:30 +00007607StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7608 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007609 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00007610 if (!AStmt)
7611 return StmtError();
7612
Alexey Bataeve3727102018-04-18 15:57:46 +00007613 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00007614 // 1.2.2 OpenMP Language Terminology
7615 // Structured block - An executable statement with a single entry at the
7616 // top and a single exit at the bottom.
7617 // The point of exit cannot be a branch out of the structured block.
7618 // longjmp() and throw() must not violate the entry/exit criteria.
7619 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00007620 for (int ThisCaptureLevel =
7621 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7622 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7623 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7624 // 1.2.2 OpenMP Language Terminology
7625 // Structured block - An executable statement with a single entry at the
7626 // top and a single exit at the bottom.
7627 // The point of exit cannot be a branch out of the structured block.
7628 // longjmp() and throw() must not violate the entry/exit criteria.
7629 CS->getCapturedDecl()->setNothrow();
7630 }
7631
Kelvin Li80e8f562016-12-29 22:16:30 +00007632 OMPLoopDirective::HelperExprs B;
7633 // In presence of clause 'collapse' with number of loops, it will
7634 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007635 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00007636 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7637 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00007638 VarsWithImplicitDSA, B);
7639 if (NestedLoopCount == 0)
7640 return StmtError();
7641
7642 assert((CurContext->isDependentContext() || B.builtAll()) &&
7643 "omp target teams distribute parallel for loop exprs were not built");
7644
Alexey Bataev647dd842018-01-15 20:59:40 +00007645 if (!CurContext->isDependentContext()) {
7646 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007647 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00007648 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7649 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7650 B.NumIterations, *this, CurScope,
7651 DSAStack))
7652 return StmtError();
7653 }
7654 }
7655
Reid Kleckner87a31802018-03-12 21:43:02 +00007656 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00007657 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007658 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7659 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007660}
7661
Kelvin Li1851df52017-01-03 05:23:48 +00007662StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7663 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007664 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00007665 if (!AStmt)
7666 return StmtError();
7667
Alexey Bataeve3727102018-04-18 15:57:46 +00007668 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00007669 // 1.2.2 OpenMP Language Terminology
7670 // Structured block - An executable statement with a single entry at the
7671 // top and a single exit at the bottom.
7672 // The point of exit cannot be a branch out of the structured block.
7673 // longjmp() and throw() must not violate the entry/exit criteria.
7674 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00007675 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7676 OMPD_target_teams_distribute_parallel_for_simd);
7677 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7678 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7679 // 1.2.2 OpenMP Language Terminology
7680 // Structured block - An executable statement with a single entry at the
7681 // top and a single exit at the bottom.
7682 // The point of exit cannot be a branch out of the structured block.
7683 // longjmp() and throw() must not violate the entry/exit criteria.
7684 CS->getCapturedDecl()->setNothrow();
7685 }
Kelvin Li1851df52017-01-03 05:23:48 +00007686
7687 OMPLoopDirective::HelperExprs B;
7688 // In presence of clause 'collapse' with number of loops, it will
7689 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007690 unsigned NestedLoopCount =
7691 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00007692 getCollapseNumberExpr(Clauses),
7693 nullptr /*ordered not a clause on distribute*/, CS, *this,
7694 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00007695 if (NestedLoopCount == 0)
7696 return StmtError();
7697
7698 assert((CurContext->isDependentContext() || B.builtAll()) &&
7699 "omp target teams distribute parallel for simd loop exprs were not "
7700 "built");
7701
7702 if (!CurContext->isDependentContext()) {
7703 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007704 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00007705 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7706 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7707 B.NumIterations, *this, CurScope,
7708 DSAStack))
7709 return StmtError();
7710 }
7711 }
7712
Alexey Bataev438388c2017-11-22 18:34:02 +00007713 if (checkSimdlenSafelenSpecified(*this, Clauses))
7714 return StmtError();
7715
Reid Kleckner87a31802018-03-12 21:43:02 +00007716 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00007717 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7718 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7719}
7720
Kelvin Lida681182017-01-10 18:08:18 +00007721StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7722 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007723 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00007724 if (!AStmt)
7725 return StmtError();
7726
7727 auto *CS = cast<CapturedStmt>(AStmt);
7728 // 1.2.2 OpenMP Language Terminology
7729 // Structured block - An executable statement with a single entry at the
7730 // top and a single exit at the bottom.
7731 // The point of exit cannot be a branch out of the structured block.
7732 // longjmp() and throw() must not violate the entry/exit criteria.
7733 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007734 for (int ThisCaptureLevel =
7735 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7736 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7737 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7738 // 1.2.2 OpenMP Language Terminology
7739 // Structured block - An executable statement with a single entry at the
7740 // top and a single exit at the bottom.
7741 // The point of exit cannot be a branch out of the structured block.
7742 // longjmp() and throw() must not violate the entry/exit criteria.
7743 CS->getCapturedDecl()->setNothrow();
7744 }
Kelvin Lida681182017-01-10 18:08:18 +00007745
7746 OMPLoopDirective::HelperExprs B;
7747 // In presence of clause 'collapse' with number of loops, it will
7748 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007749 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00007750 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007751 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00007752 VarsWithImplicitDSA, B);
7753 if (NestedLoopCount == 0)
7754 return StmtError();
7755
7756 assert((CurContext->isDependentContext() || B.builtAll()) &&
7757 "omp target teams distribute simd loop exprs were not built");
7758
Alexey Bataev438388c2017-11-22 18:34:02 +00007759 if (!CurContext->isDependentContext()) {
7760 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007761 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007762 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7763 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7764 B.NumIterations, *this, CurScope,
7765 DSAStack))
7766 return StmtError();
7767 }
7768 }
7769
7770 if (checkSimdlenSafelenSpecified(*this, Clauses))
7771 return StmtError();
7772
Reid Kleckner87a31802018-03-12 21:43:02 +00007773 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00007774 return OMPTargetTeamsDistributeSimdDirective::Create(
7775 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7776}
7777
Alexey Bataeved09d242014-05-28 05:53:51 +00007778OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007779 SourceLocation StartLoc,
7780 SourceLocation LParenLoc,
7781 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007782 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007783 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007784 case OMPC_final:
7785 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7786 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007787 case OMPC_num_threads:
7788 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7789 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007790 case OMPC_safelen:
7791 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7792 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007793 case OMPC_simdlen:
7794 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7795 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007796 case OMPC_collapse:
7797 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7798 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007799 case OMPC_ordered:
7800 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7801 break;
Michael Wonge710d542015-08-07 16:16:36 +00007802 case OMPC_device:
7803 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7804 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007805 case OMPC_num_teams:
7806 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7807 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007808 case OMPC_thread_limit:
7809 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7810 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007811 case OMPC_priority:
7812 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7813 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007814 case OMPC_grainsize:
7815 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7816 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007817 case OMPC_num_tasks:
7818 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7819 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007820 case OMPC_hint:
7821 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7822 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007823 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007824 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007825 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007826 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007827 case OMPC_private:
7828 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007829 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007830 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007831 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007832 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007833 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007834 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007835 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007836 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007837 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007838 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007839 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007840 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007841 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007842 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007843 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007844 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007845 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007846 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007847 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007848 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007849 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007850 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007851 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007852 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007853 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007854 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007855 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007856 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007857 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007858 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007859 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007860 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007861 llvm_unreachable("Clause is not allowed.");
7862 }
7863 return Res;
7864}
7865
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007866// An OpenMP directive such as 'target parallel' has two captured regions:
7867// for the 'target' and 'parallel' respectively. This function returns
7868// the region in which to capture expressions associated with a clause.
7869// A return value of OMPD_unknown signifies that the expression should not
7870// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007871static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7872 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7873 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007874 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007875 switch (CKind) {
7876 case OMPC_if:
7877 switch (DKind) {
7878 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007879 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007880 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007881 // If this clause applies to the nested 'parallel' region, capture within
7882 // the 'target' region, otherwise do not capture.
7883 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7884 CaptureRegion = OMPD_target;
7885 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007886 case OMPD_target_teams_distribute_parallel_for:
7887 case OMPD_target_teams_distribute_parallel_for_simd:
7888 // If this clause applies to the nested 'parallel' region, capture within
7889 // the 'teams' region, otherwise do not capture.
7890 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7891 CaptureRegion = OMPD_teams;
7892 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007893 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007894 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007895 CaptureRegion = OMPD_teams;
7896 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007897 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00007898 case OMPD_target_enter_data:
7899 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007900 CaptureRegion = OMPD_task;
7901 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007902 case OMPD_cancel:
7903 case OMPD_parallel:
7904 case OMPD_parallel_sections:
7905 case OMPD_parallel_for:
7906 case OMPD_parallel_for_simd:
7907 case OMPD_target:
7908 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007909 case OMPD_target_teams:
7910 case OMPD_target_teams_distribute:
7911 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007912 case OMPD_distribute_parallel_for:
7913 case OMPD_distribute_parallel_for_simd:
7914 case OMPD_task:
7915 case OMPD_taskloop:
7916 case OMPD_taskloop_simd:
7917 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007918 // Do not capture if-clause expressions.
7919 break;
7920 case OMPD_threadprivate:
7921 case OMPD_taskyield:
7922 case OMPD_barrier:
7923 case OMPD_taskwait:
7924 case OMPD_cancellation_point:
7925 case OMPD_flush:
7926 case OMPD_declare_reduction:
7927 case OMPD_declare_simd:
7928 case OMPD_declare_target:
7929 case OMPD_end_declare_target:
7930 case OMPD_teams:
7931 case OMPD_simd:
7932 case OMPD_for:
7933 case OMPD_for_simd:
7934 case OMPD_sections:
7935 case OMPD_section:
7936 case OMPD_single:
7937 case OMPD_master:
7938 case OMPD_critical:
7939 case OMPD_taskgroup:
7940 case OMPD_distribute:
7941 case OMPD_ordered:
7942 case OMPD_atomic:
7943 case OMPD_distribute_simd:
7944 case OMPD_teams_distribute:
7945 case OMPD_teams_distribute_simd:
7946 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7947 case OMPD_unknown:
7948 llvm_unreachable("Unknown OpenMP directive");
7949 }
7950 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007951 case OMPC_num_threads:
7952 switch (DKind) {
7953 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007954 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007955 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007956 CaptureRegion = OMPD_target;
7957 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007958 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007959 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00007960 case OMPD_target_teams_distribute_parallel_for:
7961 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007962 CaptureRegion = OMPD_teams;
7963 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007964 case OMPD_parallel:
7965 case OMPD_parallel_sections:
7966 case OMPD_parallel_for:
7967 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007968 case OMPD_distribute_parallel_for:
7969 case OMPD_distribute_parallel_for_simd:
7970 // Do not capture num_threads-clause expressions.
7971 break;
7972 case OMPD_target_data:
7973 case OMPD_target_enter_data:
7974 case OMPD_target_exit_data:
7975 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007976 case OMPD_target:
7977 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007978 case OMPD_target_teams:
7979 case OMPD_target_teams_distribute:
7980 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007981 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007982 case OMPD_task:
7983 case OMPD_taskloop:
7984 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007985 case OMPD_threadprivate:
7986 case OMPD_taskyield:
7987 case OMPD_barrier:
7988 case OMPD_taskwait:
7989 case OMPD_cancellation_point:
7990 case OMPD_flush:
7991 case OMPD_declare_reduction:
7992 case OMPD_declare_simd:
7993 case OMPD_declare_target:
7994 case OMPD_end_declare_target:
7995 case OMPD_teams:
7996 case OMPD_simd:
7997 case OMPD_for:
7998 case OMPD_for_simd:
7999 case OMPD_sections:
8000 case OMPD_section:
8001 case OMPD_single:
8002 case OMPD_master:
8003 case OMPD_critical:
8004 case OMPD_taskgroup:
8005 case OMPD_distribute:
8006 case OMPD_ordered:
8007 case OMPD_atomic:
8008 case OMPD_distribute_simd:
8009 case OMPD_teams_distribute:
8010 case OMPD_teams_distribute_simd:
8011 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8012 case OMPD_unknown:
8013 llvm_unreachable("Unknown OpenMP directive");
8014 }
8015 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008016 case OMPC_num_teams:
8017 switch (DKind) {
8018 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008019 case OMPD_target_teams_distribute:
8020 case OMPD_target_teams_distribute_simd:
8021 case OMPD_target_teams_distribute_parallel_for:
8022 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008023 CaptureRegion = OMPD_target;
8024 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008025 case OMPD_teams_distribute_parallel_for:
8026 case OMPD_teams_distribute_parallel_for_simd:
8027 case OMPD_teams:
8028 case OMPD_teams_distribute:
8029 case OMPD_teams_distribute_simd:
8030 // Do not capture num_teams-clause expressions.
8031 break;
8032 case OMPD_distribute_parallel_for:
8033 case OMPD_distribute_parallel_for_simd:
8034 case OMPD_task:
8035 case OMPD_taskloop:
8036 case OMPD_taskloop_simd:
8037 case OMPD_target_data:
8038 case OMPD_target_enter_data:
8039 case OMPD_target_exit_data:
8040 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008041 case OMPD_cancel:
8042 case OMPD_parallel:
8043 case OMPD_parallel_sections:
8044 case OMPD_parallel_for:
8045 case OMPD_parallel_for_simd:
8046 case OMPD_target:
8047 case OMPD_target_simd:
8048 case OMPD_target_parallel:
8049 case OMPD_target_parallel_for:
8050 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008051 case OMPD_threadprivate:
8052 case OMPD_taskyield:
8053 case OMPD_barrier:
8054 case OMPD_taskwait:
8055 case OMPD_cancellation_point:
8056 case OMPD_flush:
8057 case OMPD_declare_reduction:
8058 case OMPD_declare_simd:
8059 case OMPD_declare_target:
8060 case OMPD_end_declare_target:
8061 case OMPD_simd:
8062 case OMPD_for:
8063 case OMPD_for_simd:
8064 case OMPD_sections:
8065 case OMPD_section:
8066 case OMPD_single:
8067 case OMPD_master:
8068 case OMPD_critical:
8069 case OMPD_taskgroup:
8070 case OMPD_distribute:
8071 case OMPD_ordered:
8072 case OMPD_atomic:
8073 case OMPD_distribute_simd:
8074 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8075 case OMPD_unknown:
8076 llvm_unreachable("Unknown OpenMP directive");
8077 }
8078 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008079 case OMPC_thread_limit:
8080 switch (DKind) {
8081 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008082 case OMPD_target_teams_distribute:
8083 case OMPD_target_teams_distribute_simd:
8084 case OMPD_target_teams_distribute_parallel_for:
8085 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008086 CaptureRegion = OMPD_target;
8087 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008088 case OMPD_teams_distribute_parallel_for:
8089 case OMPD_teams_distribute_parallel_for_simd:
8090 case OMPD_teams:
8091 case OMPD_teams_distribute:
8092 case OMPD_teams_distribute_simd:
8093 // Do not capture thread_limit-clause expressions.
8094 break;
8095 case OMPD_distribute_parallel_for:
8096 case OMPD_distribute_parallel_for_simd:
8097 case OMPD_task:
8098 case OMPD_taskloop:
8099 case OMPD_taskloop_simd:
8100 case OMPD_target_data:
8101 case OMPD_target_enter_data:
8102 case OMPD_target_exit_data:
8103 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008104 case OMPD_cancel:
8105 case OMPD_parallel:
8106 case OMPD_parallel_sections:
8107 case OMPD_parallel_for:
8108 case OMPD_parallel_for_simd:
8109 case OMPD_target:
8110 case OMPD_target_simd:
8111 case OMPD_target_parallel:
8112 case OMPD_target_parallel_for:
8113 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008114 case OMPD_threadprivate:
8115 case OMPD_taskyield:
8116 case OMPD_barrier:
8117 case OMPD_taskwait:
8118 case OMPD_cancellation_point:
8119 case OMPD_flush:
8120 case OMPD_declare_reduction:
8121 case OMPD_declare_simd:
8122 case OMPD_declare_target:
8123 case OMPD_end_declare_target:
8124 case OMPD_simd:
8125 case OMPD_for:
8126 case OMPD_for_simd:
8127 case OMPD_sections:
8128 case OMPD_section:
8129 case OMPD_single:
8130 case OMPD_master:
8131 case OMPD_critical:
8132 case OMPD_taskgroup:
8133 case OMPD_distribute:
8134 case OMPD_ordered:
8135 case OMPD_atomic:
8136 case OMPD_distribute_simd:
8137 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8138 case OMPD_unknown:
8139 llvm_unreachable("Unknown OpenMP directive");
8140 }
8141 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008142 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008143 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008144 case OMPD_parallel_for:
8145 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008146 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008147 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008148 case OMPD_teams_distribute_parallel_for:
8149 case OMPD_teams_distribute_parallel_for_simd:
8150 case OMPD_target_parallel_for:
8151 case OMPD_target_parallel_for_simd:
8152 case OMPD_target_teams_distribute_parallel_for:
8153 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008154 CaptureRegion = OMPD_parallel;
8155 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008156 case OMPD_for:
8157 case OMPD_for_simd:
8158 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008159 break;
8160 case OMPD_task:
8161 case OMPD_taskloop:
8162 case OMPD_taskloop_simd:
8163 case OMPD_target_data:
8164 case OMPD_target_enter_data:
8165 case OMPD_target_exit_data:
8166 case OMPD_target_update:
8167 case OMPD_teams:
8168 case OMPD_teams_distribute:
8169 case OMPD_teams_distribute_simd:
8170 case OMPD_target_teams_distribute:
8171 case OMPD_target_teams_distribute_simd:
8172 case OMPD_target:
8173 case OMPD_target_simd:
8174 case OMPD_target_parallel:
8175 case OMPD_cancel:
8176 case OMPD_parallel:
8177 case OMPD_parallel_sections:
8178 case OMPD_threadprivate:
8179 case OMPD_taskyield:
8180 case OMPD_barrier:
8181 case OMPD_taskwait:
8182 case OMPD_cancellation_point:
8183 case OMPD_flush:
8184 case OMPD_declare_reduction:
8185 case OMPD_declare_simd:
8186 case OMPD_declare_target:
8187 case OMPD_end_declare_target:
8188 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008189 case OMPD_sections:
8190 case OMPD_section:
8191 case OMPD_single:
8192 case OMPD_master:
8193 case OMPD_critical:
8194 case OMPD_taskgroup:
8195 case OMPD_distribute:
8196 case OMPD_ordered:
8197 case OMPD_atomic:
8198 case OMPD_distribute_simd:
8199 case OMPD_target_teams:
8200 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8201 case OMPD_unknown:
8202 llvm_unreachable("Unknown OpenMP directive");
8203 }
8204 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008205 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008206 switch (DKind) {
8207 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008208 case OMPD_teams_distribute_parallel_for_simd:
8209 case OMPD_teams_distribute:
8210 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008211 case OMPD_target_teams_distribute_parallel_for:
8212 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008213 case OMPD_target_teams_distribute:
8214 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008215 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008216 break;
8217 case OMPD_distribute_parallel_for:
8218 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008219 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008220 case OMPD_distribute_simd:
8221 // Do not capture thread_limit-clause expressions.
8222 break;
8223 case OMPD_parallel_for:
8224 case OMPD_parallel_for_simd:
8225 case OMPD_target_parallel_for_simd:
8226 case OMPD_target_parallel_for:
8227 case OMPD_task:
8228 case OMPD_taskloop:
8229 case OMPD_taskloop_simd:
8230 case OMPD_target_data:
8231 case OMPD_target_enter_data:
8232 case OMPD_target_exit_data:
8233 case OMPD_target_update:
8234 case OMPD_teams:
8235 case OMPD_target:
8236 case OMPD_target_simd:
8237 case OMPD_target_parallel:
8238 case OMPD_cancel:
8239 case OMPD_parallel:
8240 case OMPD_parallel_sections:
8241 case OMPD_threadprivate:
8242 case OMPD_taskyield:
8243 case OMPD_barrier:
8244 case OMPD_taskwait:
8245 case OMPD_cancellation_point:
8246 case OMPD_flush:
8247 case OMPD_declare_reduction:
8248 case OMPD_declare_simd:
8249 case OMPD_declare_target:
8250 case OMPD_end_declare_target:
8251 case OMPD_simd:
8252 case OMPD_for:
8253 case OMPD_for_simd:
8254 case OMPD_sections:
8255 case OMPD_section:
8256 case OMPD_single:
8257 case OMPD_master:
8258 case OMPD_critical:
8259 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008260 case OMPD_ordered:
8261 case OMPD_atomic:
8262 case OMPD_target_teams:
8263 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8264 case OMPD_unknown:
8265 llvm_unreachable("Unknown OpenMP directive");
8266 }
8267 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008268 case OMPC_device:
8269 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008270 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008271 case OMPD_target_enter_data:
8272 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008273 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008274 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008275 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008276 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008277 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008278 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008279 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008280 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008281 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008282 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008283 CaptureRegion = OMPD_task;
8284 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008285 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008286 // Do not capture device-clause expressions.
8287 break;
8288 case OMPD_teams_distribute_parallel_for:
8289 case OMPD_teams_distribute_parallel_for_simd:
8290 case OMPD_teams:
8291 case OMPD_teams_distribute:
8292 case OMPD_teams_distribute_simd:
8293 case OMPD_distribute_parallel_for:
8294 case OMPD_distribute_parallel_for_simd:
8295 case OMPD_task:
8296 case OMPD_taskloop:
8297 case OMPD_taskloop_simd:
8298 case OMPD_cancel:
8299 case OMPD_parallel:
8300 case OMPD_parallel_sections:
8301 case OMPD_parallel_for:
8302 case OMPD_parallel_for_simd:
8303 case OMPD_threadprivate:
8304 case OMPD_taskyield:
8305 case OMPD_barrier:
8306 case OMPD_taskwait:
8307 case OMPD_cancellation_point:
8308 case OMPD_flush:
8309 case OMPD_declare_reduction:
8310 case OMPD_declare_simd:
8311 case OMPD_declare_target:
8312 case OMPD_end_declare_target:
8313 case OMPD_simd:
8314 case OMPD_for:
8315 case OMPD_for_simd:
8316 case OMPD_sections:
8317 case OMPD_section:
8318 case OMPD_single:
8319 case OMPD_master:
8320 case OMPD_critical:
8321 case OMPD_taskgroup:
8322 case OMPD_distribute:
8323 case OMPD_ordered:
8324 case OMPD_atomic:
8325 case OMPD_distribute_simd:
8326 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8327 case OMPD_unknown:
8328 llvm_unreachable("Unknown OpenMP directive");
8329 }
8330 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008331 case OMPC_firstprivate:
8332 case OMPC_lastprivate:
8333 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008334 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008335 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008336 case OMPC_linear:
8337 case OMPC_default:
8338 case OMPC_proc_bind:
8339 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008340 case OMPC_safelen:
8341 case OMPC_simdlen:
8342 case OMPC_collapse:
8343 case OMPC_private:
8344 case OMPC_shared:
8345 case OMPC_aligned:
8346 case OMPC_copyin:
8347 case OMPC_copyprivate:
8348 case OMPC_ordered:
8349 case OMPC_nowait:
8350 case OMPC_untied:
8351 case OMPC_mergeable:
8352 case OMPC_threadprivate:
8353 case OMPC_flush:
8354 case OMPC_read:
8355 case OMPC_write:
8356 case OMPC_update:
8357 case OMPC_capture:
8358 case OMPC_seq_cst:
8359 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008360 case OMPC_threads:
8361 case OMPC_simd:
8362 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008363 case OMPC_priority:
8364 case OMPC_grainsize:
8365 case OMPC_nogroup:
8366 case OMPC_num_tasks:
8367 case OMPC_hint:
8368 case OMPC_defaultmap:
8369 case OMPC_unknown:
8370 case OMPC_uniform:
8371 case OMPC_to:
8372 case OMPC_from:
8373 case OMPC_use_device_ptr:
8374 case OMPC_is_device_ptr:
8375 llvm_unreachable("Unexpected OpenMP clause.");
8376 }
8377 return CaptureRegion;
8378}
8379
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008380OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8381 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008382 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008383 SourceLocation NameModifierLoc,
8384 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008385 SourceLocation EndLoc) {
8386 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008387 Stmt *HelperValStmt = nullptr;
8388 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008389 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8390 !Condition->isInstantiationDependent() &&
8391 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008392 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008393 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008394 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008395
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008396 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008397
8398 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8399 CaptureRegion =
8400 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008401 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008402 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00008403 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008404 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8405 HelperValStmt = buildPreInits(Context, Captures);
8406 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008407 }
8408
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008409 return new (Context)
8410 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8411 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008412}
8413
Alexey Bataev3778b602014-07-17 07:32:53 +00008414OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8415 SourceLocation StartLoc,
8416 SourceLocation LParenLoc,
8417 SourceLocation EndLoc) {
8418 Expr *ValExpr = Condition;
8419 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8420 !Condition->isInstantiationDependent() &&
8421 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008422 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008423 if (Val.isInvalid())
8424 return nullptr;
8425
Richard Smith03a4aa32016-06-23 19:02:52 +00008426 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008427 }
8428
8429 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8430}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008431ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8432 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008433 if (!Op)
8434 return ExprError();
8435
8436 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8437 public:
8438 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008439 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008440 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8441 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008442 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8443 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008444 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8445 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008446 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8447 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008448 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8449 QualType T,
8450 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008451 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8452 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008453 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8454 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008455 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008456 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008457 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008458 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8459 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008460 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8461 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008462 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8463 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008464 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008465 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008466 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008467 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8468 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008469 llvm_unreachable("conversion functions are permitted");
8470 }
8471 } ConvertDiagnoser;
8472 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8473}
8474
Alexey Bataeve3727102018-04-18 15:57:46 +00008475static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008476 OpenMPClauseKind CKind,
8477 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008478 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8479 !ValExpr->isInstantiationDependent()) {
8480 SourceLocation Loc = ValExpr->getExprLoc();
8481 ExprResult Value =
8482 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8483 if (Value.isInvalid())
8484 return false;
8485
8486 ValExpr = Value.get();
8487 // The expression must evaluate to a non-negative integer value.
8488 llvm::APSInt Result;
8489 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008490 Result.isSigned() &&
8491 !((!StrictlyPositive && Result.isNonNegative()) ||
8492 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008493 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008494 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8495 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008496 return false;
8497 }
8498 }
8499 return true;
8500}
8501
Alexey Bataev568a8332014-03-06 06:15:19 +00008502OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8503 SourceLocation StartLoc,
8504 SourceLocation LParenLoc,
8505 SourceLocation EndLoc) {
8506 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008507 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008508
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008509 // OpenMP [2.5, Restrictions]
8510 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00008511 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00008512 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008513 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008514
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008515 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008516 OpenMPDirectiveKind CaptureRegion =
8517 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8518 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008519 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00008520 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008521 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8522 HelperValStmt = buildPreInits(Context, Captures);
8523 }
8524
8525 return new (Context) OMPNumThreadsClause(
8526 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008527}
8528
Alexey Bataev62c87d22014-03-21 04:51:18 +00008529ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008530 OpenMPClauseKind CKind,
8531 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008532 if (!E)
8533 return ExprError();
8534 if (E->isValueDependent() || E->isTypeDependent() ||
8535 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008536 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008537 llvm::APSInt Result;
8538 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8539 if (ICE.isInvalid())
8540 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008541 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8542 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008543 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008544 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8545 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008546 return ExprError();
8547 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008548 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8549 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8550 << E->getSourceRange();
8551 return ExprError();
8552 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008553 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8554 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008555 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008556 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008557 return ICE;
8558}
8559
8560OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8561 SourceLocation LParenLoc,
8562 SourceLocation EndLoc) {
8563 // OpenMP [2.8.1, simd construct, Description]
8564 // The parameter of the safelen clause must be a constant
8565 // positive integer expression.
8566 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8567 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008568 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008569 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008570 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008571}
8572
Alexey Bataev66b15b52015-08-21 11:14:16 +00008573OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8574 SourceLocation LParenLoc,
8575 SourceLocation EndLoc) {
8576 // OpenMP [2.8.1, simd construct, Description]
8577 // The parameter of the simdlen clause must be a constant
8578 // positive integer expression.
8579 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8580 if (Simdlen.isInvalid())
8581 return nullptr;
8582 return new (Context)
8583 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8584}
8585
Alexander Musman64d33f12014-06-04 07:53:32 +00008586OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8587 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008588 SourceLocation LParenLoc,
8589 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008590 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008591 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008592 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008593 // The parameter of the collapse clause must be a constant
8594 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008595 ExprResult NumForLoopsResult =
8596 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8597 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008598 return nullptr;
8599 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008600 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008601}
8602
Alexey Bataev10e775f2015-07-30 11:36:16 +00008603OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8604 SourceLocation EndLoc,
8605 SourceLocation LParenLoc,
8606 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008607 // OpenMP [2.7.1, loop construct, Description]
8608 // OpenMP [2.8.1, simd construct, Description]
8609 // OpenMP [2.9.6, distribute construct, Description]
8610 // The parameter of the ordered clause must be a constant
8611 // positive integer expression if any.
8612 if (NumForLoops && LParenLoc.isValid()) {
8613 ExprResult NumForLoopsResult =
8614 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8615 if (NumForLoopsResult.isInvalid())
8616 return nullptr;
8617 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00008618 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00008619 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008620 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008621 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008622 return new (Context)
8623 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8624}
8625
Alexey Bataeved09d242014-05-28 05:53:51 +00008626OMPClause *Sema::ActOnOpenMPSimpleClause(
8627 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8628 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008629 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008630 switch (Kind) {
8631 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008632 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008633 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8634 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008635 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008636 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008637 Res = ActOnOpenMPProcBindClause(
8638 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8639 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008640 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008641 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008642 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008643 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008644 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008645 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008646 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008647 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008648 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008649 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008650 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008651 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008652 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008653 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008654 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008655 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008656 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008657 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008658 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008659 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008660 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008661 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008662 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008663 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008664 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008665 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008666 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008667 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008668 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008669 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008670 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008671 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008672 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008673 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008674 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008675 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008676 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008677 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008678 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008679 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008680 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008681 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008682 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008683 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008684 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008685 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008686 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008687 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008688 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008689 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008690 llvm_unreachable("Clause is not allowed.");
8691 }
8692 return Res;
8693}
8694
Alexey Bataev6402bca2015-12-28 07:25:51 +00008695static std::string
8696getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8697 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008698 SmallString<256> Buffer;
8699 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00008700 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8701 unsigned Skipped = Exclude.size();
8702 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00008703 for (unsigned I = First; I < Last; ++I) {
8704 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00008705 --Skipped;
8706 continue;
8707 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008708 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
8709 if (I == Bound - Skipped)
8710 Out << " or ";
8711 else if (I != Bound + 1 - Skipped)
8712 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00008713 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008714 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00008715}
8716
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008717OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8718 SourceLocation KindKwLoc,
8719 SourceLocation StartLoc,
8720 SourceLocation LParenLoc,
8721 SourceLocation EndLoc) {
8722 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008723 static_assert(OMPC_DEFAULT_unknown > 0,
8724 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008725 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008726 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8727 /*Last=*/OMPC_DEFAULT_unknown)
8728 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008729 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008730 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008731 switch (Kind) {
8732 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008733 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008734 break;
8735 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008736 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008737 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008738 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008739 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008740 break;
8741 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008742 return new (Context)
8743 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008744}
8745
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008746OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8747 SourceLocation KindKwLoc,
8748 SourceLocation StartLoc,
8749 SourceLocation LParenLoc,
8750 SourceLocation EndLoc) {
8751 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008752 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008753 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8754 /*Last=*/OMPC_PROC_BIND_unknown)
8755 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008756 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008757 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008758 return new (Context)
8759 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008760}
8761
Alexey Bataev56dafe82014-06-20 07:16:17 +00008762OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008763 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008764 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008765 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008766 SourceLocation EndLoc) {
8767 OMPClause *Res = nullptr;
8768 switch (Kind) {
8769 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008770 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8771 assert(Argument.size() == NumberOfElements &&
8772 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008773 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008774 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8775 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8776 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8777 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8778 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008779 break;
8780 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008781 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8782 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8783 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8784 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008785 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008786 case OMPC_dist_schedule:
8787 Res = ActOnOpenMPDistScheduleClause(
8788 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8789 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8790 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008791 case OMPC_defaultmap:
8792 enum { Modifier, DefaultmapKind };
8793 Res = ActOnOpenMPDefaultmapClause(
8794 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8795 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008796 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8797 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008798 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008799 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008800 case OMPC_num_threads:
8801 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008802 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008803 case OMPC_collapse:
8804 case OMPC_default:
8805 case OMPC_proc_bind:
8806 case OMPC_private:
8807 case OMPC_firstprivate:
8808 case OMPC_lastprivate:
8809 case OMPC_shared:
8810 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008811 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008812 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008813 case OMPC_linear:
8814 case OMPC_aligned:
8815 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008816 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008817 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008818 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008819 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008820 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008821 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008822 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008823 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008824 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008825 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008826 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008827 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008828 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008829 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008830 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008831 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008832 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008833 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008834 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008835 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008836 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008837 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008838 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008839 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008840 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008841 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008842 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008843 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008844 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008845 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008846 llvm_unreachable("Clause is not allowed.");
8847 }
8848 return Res;
8849}
8850
Alexey Bataev6402bca2015-12-28 07:25:51 +00008851static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8852 OpenMPScheduleClauseModifier M2,
8853 SourceLocation M1Loc, SourceLocation M2Loc) {
8854 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8855 SmallVector<unsigned, 2> Excluded;
8856 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8857 Excluded.push_back(M2);
8858 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8859 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8860 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8861 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8862 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8863 << getListOfPossibleValues(OMPC_schedule,
8864 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8865 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8866 Excluded)
8867 << getOpenMPClauseName(OMPC_schedule);
8868 return true;
8869 }
8870 return false;
8871}
8872
Alexey Bataev56dafe82014-06-20 07:16:17 +00008873OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008874 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008875 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008876 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8877 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8878 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8879 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8880 return nullptr;
8881 // OpenMP, 2.7.1, Loop Construct, Restrictions
8882 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8883 // but not both.
8884 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8885 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8886 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8887 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8888 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8889 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8890 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8891 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8892 return nullptr;
8893 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008894 if (Kind == OMPC_SCHEDULE_unknown) {
8895 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008896 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8897 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8898 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8899 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8900 Exclude);
8901 } else {
8902 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8903 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008904 }
8905 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8906 << Values << getOpenMPClauseName(OMPC_schedule);
8907 return nullptr;
8908 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008909 // OpenMP, 2.7.1, Loop Construct, Restrictions
8910 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8911 // schedule(guided).
8912 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8913 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8914 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8915 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8916 diag::err_omp_schedule_nonmonotonic_static);
8917 return nullptr;
8918 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008919 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008920 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008921 if (ChunkSize) {
8922 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8923 !ChunkSize->isInstantiationDependent() &&
8924 !ChunkSize->containsUnexpandedParameterPack()) {
8925 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8926 ExprResult Val =
8927 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8928 if (Val.isInvalid())
8929 return nullptr;
8930
8931 ValExpr = Val.get();
8932
8933 // OpenMP [2.7.1, Restrictions]
8934 // chunk_size must be a loop invariant integer expression with a positive
8935 // value.
8936 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008937 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8938 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8939 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008940 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008941 return nullptr;
8942 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008943 } else if (getOpenMPCaptureRegionForClause(
8944 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8945 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008946 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008947 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00008948 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00008949 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8950 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008951 }
8952 }
8953 }
8954
Alexey Bataev6402bca2015-12-28 07:25:51 +00008955 return new (Context)
8956 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008957 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008958}
8959
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008960OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8961 SourceLocation StartLoc,
8962 SourceLocation EndLoc) {
8963 OMPClause *Res = nullptr;
8964 switch (Kind) {
8965 case OMPC_ordered:
8966 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8967 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008968 case OMPC_nowait:
8969 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8970 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008971 case OMPC_untied:
8972 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8973 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008974 case OMPC_mergeable:
8975 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8976 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008977 case OMPC_read:
8978 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8979 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008980 case OMPC_write:
8981 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8982 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008983 case OMPC_update:
8984 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8985 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008986 case OMPC_capture:
8987 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8988 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008989 case OMPC_seq_cst:
8990 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8991 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008992 case OMPC_threads:
8993 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8994 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008995 case OMPC_simd:
8996 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8997 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008998 case OMPC_nogroup:
8999 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9000 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009001 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009002 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009003 case OMPC_num_threads:
9004 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009005 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009006 case OMPC_collapse:
9007 case OMPC_schedule:
9008 case OMPC_private:
9009 case OMPC_firstprivate:
9010 case OMPC_lastprivate:
9011 case OMPC_shared:
9012 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009013 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009014 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009015 case OMPC_linear:
9016 case OMPC_aligned:
9017 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009018 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009019 case OMPC_default:
9020 case OMPC_proc_bind:
9021 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009022 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009023 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009024 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009025 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009026 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009027 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009028 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009029 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009030 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009031 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009032 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009033 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009034 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009035 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009036 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009037 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009038 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009039 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009040 llvm_unreachable("Clause is not allowed.");
9041 }
9042 return Res;
9043}
9044
Alexey Bataev236070f2014-06-20 11:19:47 +00009045OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9046 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009047 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009048 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9049}
9050
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009051OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9052 SourceLocation EndLoc) {
9053 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9054}
9055
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009056OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9057 SourceLocation EndLoc) {
9058 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9059}
9060
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009061OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9062 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009063 return new (Context) OMPReadClause(StartLoc, EndLoc);
9064}
9065
Alexey Bataevdea47612014-07-23 07:46:59 +00009066OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9067 SourceLocation EndLoc) {
9068 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9069}
9070
Alexey Bataev67a4f222014-07-23 10:25:33 +00009071OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9072 SourceLocation EndLoc) {
9073 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9074}
9075
Alexey Bataev459dec02014-07-24 06:46:57 +00009076OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9077 SourceLocation EndLoc) {
9078 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9079}
9080
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009081OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9082 SourceLocation EndLoc) {
9083 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9084}
9085
Alexey Bataev346265e2015-09-25 10:37:12 +00009086OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9087 SourceLocation EndLoc) {
9088 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9089}
9090
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009091OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9092 SourceLocation EndLoc) {
9093 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9094}
9095
Alexey Bataevb825de12015-12-07 10:51:44 +00009096OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9097 SourceLocation EndLoc) {
9098 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9099}
9100
Alexey Bataevc5e02582014-06-16 07:08:35 +00009101OMPClause *Sema::ActOnOpenMPVarListClause(
9102 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9103 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9104 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009105 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00009106 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9107 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9108 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009109 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009110 switch (Kind) {
9111 case OMPC_private:
9112 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9113 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009114 case OMPC_firstprivate:
9115 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9116 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009117 case OMPC_lastprivate:
9118 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9119 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009120 case OMPC_shared:
9121 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9122 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009123 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009124 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9125 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009126 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009127 case OMPC_task_reduction:
9128 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9129 EndLoc, ReductionIdScopeSpec,
9130 ReductionId);
9131 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009132 case OMPC_in_reduction:
9133 Res =
9134 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9135 EndLoc, ReductionIdScopeSpec, ReductionId);
9136 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009137 case OMPC_linear:
9138 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009139 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009140 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009141 case OMPC_aligned:
9142 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9143 ColonLoc, EndLoc);
9144 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009145 case OMPC_copyin:
9146 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9147 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009148 case OMPC_copyprivate:
9149 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9150 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009151 case OMPC_flush:
9152 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9153 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009154 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009155 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009156 StartLoc, LParenLoc, EndLoc);
9157 break;
9158 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00009159 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9160 DepLinMapLoc, ColonLoc, VarList, StartLoc,
9161 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009162 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009163 case OMPC_to:
9164 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9165 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009166 case OMPC_from:
9167 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9168 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009169 case OMPC_use_device_ptr:
9170 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9171 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009172 case OMPC_is_device_ptr:
9173 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9174 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009175 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009176 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009177 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009178 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009179 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009180 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009181 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009182 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009183 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009184 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009185 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009186 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009187 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009188 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009189 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009190 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009191 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009192 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009193 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009194 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009195 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009196 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009197 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009198 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009199 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009200 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009201 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009202 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009203 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009204 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009205 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009206 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009207 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009208 llvm_unreachable("Clause is not allowed.");
9209 }
9210 return Res;
9211}
9212
Alexey Bataev90c228f2016-02-08 09:29:13 +00009213ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009214 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009215 ExprResult Res = BuildDeclRefExpr(
9216 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9217 if (!Res.isUsable())
9218 return ExprError();
9219 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9220 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9221 if (!Res.isUsable())
9222 return ExprError();
9223 }
9224 if (VK != VK_LValue && Res.get()->isGLValue()) {
9225 Res = DefaultLvalueConversion(Res.get());
9226 if (!Res.isUsable())
9227 return ExprError();
9228 }
9229 return Res;
9230}
9231
Alexey Bataev60da77e2016-02-29 05:54:20 +00009232static std::pair<ValueDecl *, bool>
9233getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9234 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009235 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9236 RefExpr->containsUnexpandedParameterPack())
9237 return std::make_pair(nullptr, true);
9238
Alexey Bataevd985eda2016-02-10 11:29:16 +00009239 // OpenMP [3.1, C/C++]
9240 // A list item is a variable name.
9241 // OpenMP [2.9.3.3, Restrictions, p.1]
9242 // A variable that is part of another variable (as an array or
9243 // structure element) cannot appear in a private clause.
9244 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009245 enum {
9246 NoArrayExpr = -1,
9247 ArraySubscript = 0,
9248 OMPArraySection = 1
9249 } IsArrayExpr = NoArrayExpr;
9250 if (AllowArraySection) {
9251 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009252 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009253 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9254 Base = TempASE->getBase()->IgnoreParenImpCasts();
9255 RefExpr = Base;
9256 IsArrayExpr = ArraySubscript;
9257 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009258 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009259 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9260 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9261 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9262 Base = TempASE->getBase()->IgnoreParenImpCasts();
9263 RefExpr = Base;
9264 IsArrayExpr = OMPArraySection;
9265 }
9266 }
9267 ELoc = RefExpr->getExprLoc();
9268 ERange = RefExpr->getSourceRange();
9269 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009270 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9271 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9272 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9273 (S.getCurrentThisType().isNull() || !ME ||
9274 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9275 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009276 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009277 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9278 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009279 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009280 S.Diag(ELoc,
9281 AllowArraySection
9282 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9283 : diag::err_omp_expected_var_name_member_expr)
9284 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9285 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009286 return std::make_pair(nullptr, false);
9287 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009288 return std::make_pair(
9289 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009290}
9291
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009292OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9293 SourceLocation StartLoc,
9294 SourceLocation LParenLoc,
9295 SourceLocation EndLoc) {
9296 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009297 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00009298 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009299 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009300 SourceLocation ELoc;
9301 SourceRange ERange;
9302 Expr *SimpleRefExpr = RefExpr;
9303 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009304 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009305 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009306 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009307 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009308 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009309 ValueDecl *D = Res.first;
9310 if (!D)
9311 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009312
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009313 QualType Type = D->getType();
9314 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009315
9316 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9317 // A variable that appears in a private clause must not have an incomplete
9318 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009319 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009320 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009321 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009322
Alexey Bataev758e55e2013-09-06 18:03:48 +00009323 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9324 // in a Construct]
9325 // Variables with the predetermined data-sharing attributes may not be
9326 // listed in data-sharing attributes clauses, except for the cases
9327 // listed below. For these exceptions only, listing a predetermined
9328 // variable in a data-sharing attribute clause is allowed and overrides
9329 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00009330 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009331 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009332 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9333 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +00009334 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009335 continue;
9336 }
9337
Alexey Bataeve3727102018-04-18 15:57:46 +00009338 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009339 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009340 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009341 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009342 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9343 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009344 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009345 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009346 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009347 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009348 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009349 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009350 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009351 continue;
9352 }
9353
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009354 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9355 // A list item cannot appear in both a map clause and a data-sharing
9356 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +00009357 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009358 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009359 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009360 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009361 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9362 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9363 ConflictKind = WhereFoundClauseKind;
9364 return true;
9365 })) {
9366 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009367 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009368 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009369 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +00009370 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009371 continue;
9372 }
9373 }
9374
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009375 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9376 // A variable of class type (or array thereof) that appears in a private
9377 // clause requires an accessible, unambiguous default constructor for the
9378 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009379 // Generate helper private variable and initialize it with the default
9380 // value. The address of the original variable is replaced by the address of
9381 // the new private variable in CodeGen. This new variable is not added to
9382 // IdResolver, so the code in the OpenMP region uses original variable for
9383 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009384 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +00009385 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +00009386 buildVarDecl(*this, ELoc, Type, D->getName(),
9387 D->hasAttrs() ? &D->getAttrs() : nullptr,
9388 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009389 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009390 if (VDPrivate->isInvalidDecl())
9391 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00009392 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009393 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009394
Alexey Bataev90c228f2016-02-08 09:29:13 +00009395 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009396 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009397 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009398 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009399 Vars.push_back((VD || CurContext->isDependentContext())
9400 ? RefExpr->IgnoreParens()
9401 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009402 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009403 }
9404
Alexey Bataeved09d242014-05-28 05:53:51 +00009405 if (Vars.empty())
9406 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009407
Alexey Bataev03b340a2014-10-21 03:16:40 +00009408 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9409 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009410}
9411
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009412namespace {
9413class DiagsUninitializedSeveretyRAII {
9414private:
9415 DiagnosticsEngine &Diags;
9416 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00009417 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009418
9419public:
9420 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9421 bool IsIgnored)
9422 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9423 if (!IsIgnored) {
9424 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9425 /*Map*/ diag::Severity::Ignored, Loc);
9426 }
9427 }
9428 ~DiagsUninitializedSeveretyRAII() {
9429 if (!IsIgnored)
9430 Diags.popMappings(SavedLoc);
9431 }
9432};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009433}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009434
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009435OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9436 SourceLocation StartLoc,
9437 SourceLocation LParenLoc,
9438 SourceLocation EndLoc) {
9439 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009440 SmallVector<Expr *, 8> PrivateCopies;
9441 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009442 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009443 bool IsImplicitClause =
9444 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +00009445 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009446
Alexey Bataeve3727102018-04-18 15:57:46 +00009447 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009448 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009449 SourceLocation ELoc;
9450 SourceRange ERange;
9451 Expr *SimpleRefExpr = RefExpr;
9452 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009453 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009454 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009455 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009456 PrivateCopies.push_back(nullptr);
9457 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009458 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009459 ValueDecl *D = Res.first;
9460 if (!D)
9461 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009462
Alexey Bataev60da77e2016-02-29 05:54:20 +00009463 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009464 QualType Type = D->getType();
9465 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009466
9467 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9468 // A variable that appears in a private clause must not have an incomplete
9469 // type or a reference type.
9470 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009471 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009472 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009473 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009474
9475 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9476 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009477 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009478 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +00009479 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009480
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009481 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009482 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009483 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009484 DSAStackTy::DSAVarData DVar =
9485 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009486 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009487 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009488 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009489 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9490 // A list item that specifies a given variable may not appear in more
9491 // than one clause on the same directive, except that a variable may be
9492 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009493 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9494 // A list item may appear in a firstprivate or lastprivate clause but not
9495 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009496 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009497 (isOpenMPDistributeDirective(CurrDir) ||
9498 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009499 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009500 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009501 << getOpenMPClauseName(DVar.CKind)
9502 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +00009503 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009504 continue;
9505 }
9506
9507 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9508 // in a Construct]
9509 // Variables with the predetermined data-sharing attributes may not be
9510 // listed in data-sharing attributes clauses, except for the cases
9511 // listed below. For these exceptions only, listing a predetermined
9512 // variable in a data-sharing attribute clause is allowed and overrides
9513 // the variable's predetermined data-sharing attributes.
9514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9515 // in a Construct, C/C++, p.2]
9516 // Variables with const-qualified type having no mutable member may be
9517 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009518 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009519 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9520 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009521 << getOpenMPClauseName(DVar.CKind)
9522 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +00009523 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009524 continue;
9525 }
9526
9527 // OpenMP [2.9.3.4, Restrictions, p.2]
9528 // A list item that is private within a parallel region must not appear
9529 // in a firstprivate clause on a worksharing construct if any of the
9530 // worksharing regions arising from the worksharing construct ever bind
9531 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009532 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9533 // A list item that is private within a teams region must not appear in a
9534 // firstprivate clause on a distribute construct if any of the distribute
9535 // regions arising from the distribute construct ever bind to any of the
9536 // teams regions arising from the teams construct.
9537 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9538 // A list item that appears in a reduction clause of a teams construct
9539 // must not appear in a firstprivate clause on a distribute construct if
9540 // any of the distribute regions arising from the distribute construct
9541 // ever bind to any of the teams regions arising from the teams construct.
9542 if ((isOpenMPWorksharingDirective(CurrDir) ||
9543 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009544 !isOpenMPParallelDirective(CurrDir) &&
9545 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009546 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009547 if (DVar.CKind != OMPC_shared &&
9548 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009549 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009550 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009551 Diag(ELoc, diag::err_omp_required_access)
9552 << getOpenMPClauseName(OMPC_firstprivate)
9553 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +00009554 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009555 continue;
9556 }
9557 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009558 // OpenMP [2.9.3.4, Restrictions, p.3]
9559 // A list item that appears in a reduction clause of a parallel construct
9560 // must not appear in a firstprivate clause on a worksharing or task
9561 // construct if any of the worksharing or task regions arising from the
9562 // worksharing or task construct ever bind to any of the parallel regions
9563 // arising from the parallel construct.
9564 // OpenMP [2.9.3.4, Restrictions, p.4]
9565 // A list item that appears in a reduction clause in worksharing
9566 // construct must not appear in a firstprivate clause in a task construct
9567 // encountered during execution of any of the worksharing regions arising
9568 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009569 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009570 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00009571 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
9572 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009573 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009574 isOpenMPWorksharingDirective(K) ||
9575 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009576 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009577 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009578 if (DVar.CKind == OMPC_reduction &&
9579 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009580 isOpenMPWorksharingDirective(DVar.DKind) ||
9581 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009582 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9583 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +00009584 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009585 continue;
9586 }
9587 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009588
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009589 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9590 // A list item cannot appear in both a map clause and a data-sharing
9591 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +00009592 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009593 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009594 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009595 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +00009596 [&ConflictKind](
9597 OMPClauseMappableExprCommon::MappableExprComponentListRef,
9598 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +00009599 ConflictKind = WhereFoundClauseKind;
9600 return true;
9601 })) {
9602 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009603 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009604 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009605 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +00009606 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009607 continue;
9608 }
9609 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009610 }
9611
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009612 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009613 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009614 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009615 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9616 << getOpenMPClauseName(OMPC_firstprivate) << Type
9617 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9618 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009619 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009620 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009621 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009622 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009623 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009624 continue;
9625 }
9626
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009627 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +00009628 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +00009629 buildVarDecl(*this, ELoc, Type, D->getName(),
9630 D->hasAttrs() ? &D->getAttrs() : nullptr,
9631 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009632 // Generate helper private variable and initialize it with the value of the
9633 // original variable. The address of the original variable is replaced by
9634 // the address of the new private variable in the CodeGen. This new variable
9635 // is not added to IdResolver, so the code in the OpenMP region uses
9636 // original variable for proper diagnostics and variable capturing.
9637 Expr *VDInitRefExpr = nullptr;
9638 // For arrays generate initializer for single element and replace it by the
9639 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009640 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009641 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009642 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009643 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00009644 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009645 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +00009646 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
9647 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009648 InitializedEntity Entity =
9649 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009650 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9651
9652 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9653 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9654 if (Result.isInvalid())
9655 VDPrivate->setInvalidDecl();
9656 else
9657 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009658 // Remove temp variable declaration.
9659 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009660 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009661 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9662 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +00009663 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9664 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009665 AddInitializerToDecl(VDPrivate,
9666 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009667 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009668 }
9669 if (VDPrivate->isInvalidDecl()) {
9670 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009671 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009672 diag::note_omp_task_predetermined_firstprivate_here);
9673 }
9674 continue;
9675 }
9676 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +00009677 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009678 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9679 RefExpr->getExprLoc());
9680 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009681 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009682 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009683 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +00009684 } else {
Alexey Bataev61205072016-03-02 04:57:40 +00009685 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +00009686 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +00009687 ExprCaptures.push_back(Ref->getDecl());
9688 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009689 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009690 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009691 Vars.push_back((VD || CurContext->isDependentContext())
9692 ? RefExpr->IgnoreParens()
9693 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009694 PrivateCopies.push_back(VDPrivateRefExpr);
9695 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009696 }
9697
Alexey Bataeved09d242014-05-28 05:53:51 +00009698 if (Vars.empty())
9699 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009700
9701 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009702 Vars, PrivateCopies, Inits,
9703 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009704}
9705
Alexander Musman1bb328c2014-06-04 13:06:39 +00009706OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9707 SourceLocation StartLoc,
9708 SourceLocation LParenLoc,
9709 SourceLocation EndLoc) {
9710 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009711 SmallVector<Expr *, 8> SrcExprs;
9712 SmallVector<Expr *, 8> DstExprs;
9713 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009714 SmallVector<Decl *, 4> ExprCaptures;
9715 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +00009716 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009717 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009718 SourceLocation ELoc;
9719 SourceRange ERange;
9720 Expr *SimpleRefExpr = RefExpr;
9721 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009722 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009723 // It will be analyzed later.
9724 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009725 SrcExprs.push_back(nullptr);
9726 DstExprs.push_back(nullptr);
9727 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009728 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009729 ValueDecl *D = Res.first;
9730 if (!D)
9731 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009732
Alexey Bataev74caaf22016-02-20 04:09:36 +00009733 QualType Type = D->getType();
9734 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009735
9736 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9737 // A variable that appears in a lastprivate clause must not have an
9738 // incomplete type or a reference type.
9739 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009740 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009741 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009742 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009743
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009744 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009745 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9746 // in a Construct]
9747 // Variables with the predetermined data-sharing attributes may not be
9748 // listed in data-sharing attributes clauses, except for the cases
9749 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009750 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9751 // A list item may appear in a firstprivate or lastprivate clause but not
9752 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +00009753 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009754 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009755 (isOpenMPDistributeDirective(CurrDir) ||
9756 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009757 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9758 Diag(ELoc, diag::err_omp_wrong_dsa)
9759 << getOpenMPClauseName(DVar.CKind)
9760 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +00009761 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009762 continue;
9763 }
9764
Alexey Bataevf29276e2014-06-18 04:14:57 +00009765 // OpenMP [2.14.3.5, Restrictions, p.2]
9766 // A list item that is private within a parallel region, or that appears in
9767 // the reduction clause of a parallel construct, must not appear in a
9768 // lastprivate clause on a worksharing construct if any of the corresponding
9769 // worksharing regions ever binds to any of the corresponding parallel
9770 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009771 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009772 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009773 !isOpenMPParallelDirective(CurrDir) &&
9774 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009775 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009776 if (DVar.CKind != OMPC_shared) {
9777 Diag(ELoc, diag::err_omp_required_access)
9778 << getOpenMPClauseName(OMPC_lastprivate)
9779 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +00009780 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009781 continue;
9782 }
9783 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009784
Alexander Musman1bb328c2014-06-04 13:06:39 +00009785 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009786 // A variable of class type (or array thereof) that appears in a
9787 // lastprivate clause requires an accessible, unambiguous default
9788 // constructor for the class type, unless the list item is also specified
9789 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009790 // A variable of class type (or array thereof) that appears in a
9791 // lastprivate clause requires an accessible, unambiguous copy assignment
9792 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009793 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00009794 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
9795 Type.getUnqualifiedType(), ".lastprivate.src",
9796 D->hasAttrs() ? &D->getAttrs() : nullptr);
9797 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +00009798 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00009799 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009800 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009801 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +00009802 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009803 // For arrays generate assignment operation for single element and replace
9804 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009805 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
9806 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009807 if (AssignmentOp.isInvalid())
9808 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009809 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009810 /*DiscardedValue=*/true);
9811 if (AssignmentOp.isInvalid())
9812 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009813
Alexey Bataev74caaf22016-02-20 04:09:36 +00009814 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009815 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009816 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009817 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +00009818 } else {
Alexey Bataev61205072016-03-02 04:57:40 +00009819 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00009820 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +00009821 ExprCaptures.push_back(Ref->getDecl());
9822 }
9823 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +00009824 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009825 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009826 ExprResult RefRes = DefaultLvalueConversion(Ref);
9827 if (!RefRes.isUsable())
9828 continue;
9829 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009830 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9831 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009832 if (!PostUpdateRes.isUsable())
9833 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009834 ExprPostUpdates.push_back(
9835 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009836 }
9837 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009838 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009839 Vars.push_back((VD || CurContext->isDependentContext())
9840 ? RefExpr->IgnoreParens()
9841 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009842 SrcExprs.push_back(PseudoSrcExpr);
9843 DstExprs.push_back(PseudoDstExpr);
9844 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009845 }
9846
9847 if (Vars.empty())
9848 return nullptr;
9849
9850 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009851 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009852 buildPreInits(Context, ExprCaptures),
9853 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009854}
9855
Alexey Bataev758e55e2013-09-06 18:03:48 +00009856OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9857 SourceLocation StartLoc,
9858 SourceLocation LParenLoc,
9859 SourceLocation EndLoc) {
9860 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00009861 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009862 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009863 SourceLocation ELoc;
9864 SourceRange ERange;
9865 Expr *SimpleRefExpr = RefExpr;
9866 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009867 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009868 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009869 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009870 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009871 ValueDecl *D = Res.first;
9872 if (!D)
9873 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009874
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009875 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009876 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9877 // in a Construct]
9878 // Variables with the predetermined data-sharing attributes may not be
9879 // listed in data-sharing attributes clauses, except for the cases
9880 // listed below. For these exceptions only, listing a predetermined
9881 // variable in a data-sharing attribute clause is allowed and overrides
9882 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00009883 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009884 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9885 DVar.RefExpr) {
9886 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9887 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +00009888 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009889 continue;
9890 }
9891
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009892 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009893 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009894 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009895 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009896 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9897 ? RefExpr->IgnoreParens()
9898 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009899 }
9900
Alexey Bataeved09d242014-05-28 05:53:51 +00009901 if (Vars.empty())
9902 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009903
9904 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9905}
9906
Alexey Bataevc5e02582014-06-16 07:08:35 +00009907namespace {
9908class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9909 DSAStackTy *Stack;
9910
9911public:
9912 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009913 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
9914 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009915 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9916 return false;
9917 if (DVar.CKind != OMPC_unknown)
9918 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009919 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00009920 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009921 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +00009922 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009923 }
9924 return false;
9925 }
9926 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009927 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009928 if (Child && Visit(Child))
9929 return true;
9930 }
9931 return false;
9932 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009933 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009934};
Alexey Bataev23b69422014-06-18 07:08:49 +00009935} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009936
Alexey Bataev60da77e2016-02-29 05:54:20 +00009937namespace {
9938// Transform MemberExpression for specified FieldDecl of current class to
9939// DeclRefExpr to specified OMPCapturedExprDecl.
9940class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9941 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +00009942 ValueDecl *Field = nullptr;
9943 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009944
9945public:
9946 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9947 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9948
9949 ExprResult TransformMemberExpr(MemberExpr *E) {
9950 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9951 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009952 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009953 return CapturedExpr;
9954 }
9955 return BaseTransform::TransformMemberExpr(E);
9956 }
9957 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9958};
9959} // namespace
9960
Alexey Bataev97d18bf2018-04-11 19:21:00 +00009961template <typename T, typename U>
9962static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
9963 const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009964 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009965 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009966 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009967 return Res;
9968 }
9969 }
9970 return T();
9971}
9972
9973static ExprResult
9974buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9975 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9976 const DeclarationNameInfo &ReductionId, QualType Ty,
9977 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9978 if (ReductionIdScopeSpec.isInvalid())
9979 return ExprError();
9980 SmallVector<UnresolvedSet<8>, 4> Lookups;
9981 if (S) {
9982 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9983 Lookup.suppressDiagnostics();
9984 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009985 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009986 do {
9987 S = S->getParent();
9988 } while (S && !S->isDeclScope(D));
9989 if (S)
9990 S = S->getParent();
9991 Lookups.push_back(UnresolvedSet<8>());
9992 Lookups.back().append(Lookup.begin(), Lookup.end());
9993 Lookup.clear();
9994 }
9995 } else if (auto *ULE =
9996 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9997 Lookups.push_back(UnresolvedSet<8>());
9998 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009999 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010000 if (D == PrevD)
10001 Lookups.push_back(UnresolvedSet<8>());
10002 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10003 Lookups.back().addDecl(DRD);
10004 PrevD = D;
10005 }
10006 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000010007 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10008 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010009 Ty->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010010 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010011 return !D->isInvalidDecl() &&
10012 (D->getType()->isDependentType() ||
10013 D->getType()->isInstantiationDependentType() ||
10014 D->getType()->containsUnexpandedParameterPack());
10015 })) {
10016 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000010017 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010018 ResSet.append(Set.begin(), Set.end());
10019 // The last item marks the end of all declarations at the specified scope.
10020 ResSet.addDecl(Set[Set.size() - 1]);
10021 }
10022 return UnresolvedLookupExpr::Create(
10023 SemaRef.Context, /*NamingClass=*/nullptr,
10024 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10025 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10026 }
10027 if (auto *VD = filterLookupForUDR<ValueDecl *>(
10028 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10029 if (!D->isInvalidDecl() &&
10030 SemaRef.Context.hasSameType(D->getType(), Ty))
10031 return D;
10032 return nullptr;
10033 }))
10034 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10035 if (auto *VD = filterLookupForUDR<ValueDecl *>(
10036 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10037 if (!D->isInvalidDecl() &&
10038 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10039 !Ty.isMoreQualifiedThan(D->getType()))
10040 return D;
10041 return nullptr;
10042 })) {
10043 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10044 /*DetectVirtual=*/false);
10045 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10046 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10047 VD->getType().getUnqualifiedType()))) {
10048 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10049 /*DiagID=*/0) !=
10050 Sema::AR_inaccessible) {
10051 SemaRef.BuildBasePathArray(Paths, BasePath);
10052 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10053 }
10054 }
10055 }
10056 }
10057 if (ReductionIdScopeSpec.isSet()) {
10058 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10059 return ExprError();
10060 }
10061 return ExprEmpty();
10062}
10063
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010064namespace {
10065/// Data for the reduction-based clauses.
10066struct ReductionData {
10067 /// List of original reduction items.
10068 SmallVector<Expr *, 8> Vars;
10069 /// List of private copies of the reduction items.
10070 SmallVector<Expr *, 8> Privates;
10071 /// LHS expressions for the reduction_op expressions.
10072 SmallVector<Expr *, 8> LHSs;
10073 /// RHS expressions for the reduction_op expressions.
10074 SmallVector<Expr *, 8> RHSs;
10075 /// Reduction operation expression.
10076 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010077 /// Taskgroup descriptors for the corresponding reduction items in
10078 /// in_reduction clauses.
10079 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010080 /// List of captures for clause.
10081 SmallVector<Decl *, 4> ExprCaptures;
10082 /// List of postupdate expressions.
10083 SmallVector<Expr *, 4> ExprPostUpdates;
10084 ReductionData() = delete;
10085 /// Reserves required memory for the reduction data.
10086 ReductionData(unsigned Size) {
10087 Vars.reserve(Size);
10088 Privates.reserve(Size);
10089 LHSs.reserve(Size);
10090 RHSs.reserve(Size);
10091 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010092 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010093 ExprCaptures.reserve(Size);
10094 ExprPostUpdates.reserve(Size);
10095 }
10096 /// Stores reduction item and reduction operation only (required for dependent
10097 /// reduction item).
10098 void push(Expr *Item, Expr *ReductionOp) {
10099 Vars.emplace_back(Item);
10100 Privates.emplace_back(nullptr);
10101 LHSs.emplace_back(nullptr);
10102 RHSs.emplace_back(nullptr);
10103 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010104 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010105 }
10106 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010107 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10108 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010109 Vars.emplace_back(Item);
10110 Privates.emplace_back(Private);
10111 LHSs.emplace_back(LHS);
10112 RHSs.emplace_back(RHS);
10113 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010114 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010115 }
10116};
10117} // namespace
10118
Alexey Bataeve3727102018-04-18 15:57:46 +000010119static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010120 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10121 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10122 const Expr *Length = OASE->getLength();
10123 if (Length == nullptr) {
10124 // For array sections of the form [1:] or [:], we would need to analyze
10125 // the lower bound...
10126 if (OASE->getColonLoc().isValid())
10127 return false;
10128
10129 // This is an array subscript which has implicit length 1!
10130 SingleElement = true;
10131 ArraySizes.push_back(llvm::APSInt::get(1));
10132 } else {
10133 llvm::APSInt ConstantLengthValue;
10134 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10135 return false;
10136
10137 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10138 ArraySizes.push_back(ConstantLengthValue);
10139 }
10140
10141 // Get the base of this array section and walk up from there.
10142 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10143
10144 // We require length = 1 for all array sections except the right-most to
10145 // guarantee that the memory region is contiguous and has no holes in it.
10146 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10147 Length = TempOASE->getLength();
10148 if (Length == nullptr) {
10149 // For array sections of the form [1:] or [:], we would need to analyze
10150 // the lower bound...
10151 if (OASE->getColonLoc().isValid())
10152 return false;
10153
10154 // This is an array subscript which has implicit length 1!
10155 ArraySizes.push_back(llvm::APSInt::get(1));
10156 } else {
10157 llvm::APSInt ConstantLengthValue;
10158 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10159 ConstantLengthValue.getSExtValue() != 1)
10160 return false;
10161
10162 ArraySizes.push_back(ConstantLengthValue);
10163 }
10164 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10165 }
10166
10167 // If we have a single element, we don't need to add the implicit lengths.
10168 if (!SingleElement) {
10169 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10170 // Has implicit length 1!
10171 ArraySizes.push_back(llvm::APSInt::get(1));
10172 Base = TempASE->getBase()->IgnoreParenImpCasts();
10173 }
10174 }
10175
10176 // This array section can be privatized as a single value or as a constant
10177 // sized array.
10178 return true;
10179}
10180
Alexey Bataeve3727102018-04-18 15:57:46 +000010181static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010182 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10183 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10184 SourceLocation ColonLoc, SourceLocation EndLoc,
10185 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010186 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010187 DeclarationName DN = ReductionId.getName();
10188 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010189 BinaryOperatorKind BOK = BO_Comma;
10190
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010191 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010192 // OpenMP [2.14.3.6, reduction clause]
10193 // C
10194 // reduction-identifier is either an identifier or one of the following
10195 // operators: +, -, *, &, |, ^, && and ||
10196 // C++
10197 // reduction-identifier is either an id-expression or one of the following
10198 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010199 switch (OOK) {
10200 case OO_Plus:
10201 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010202 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010203 break;
10204 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010205 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010206 break;
10207 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010208 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010209 break;
10210 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010211 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010212 break;
10213 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010214 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010215 break;
10216 case OO_AmpAmp:
10217 BOK = BO_LAnd;
10218 break;
10219 case OO_PipePipe:
10220 BOK = BO_LOr;
10221 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010222 case OO_New:
10223 case OO_Delete:
10224 case OO_Array_New:
10225 case OO_Array_Delete:
10226 case OO_Slash:
10227 case OO_Percent:
10228 case OO_Tilde:
10229 case OO_Exclaim:
10230 case OO_Equal:
10231 case OO_Less:
10232 case OO_Greater:
10233 case OO_LessEqual:
10234 case OO_GreaterEqual:
10235 case OO_PlusEqual:
10236 case OO_MinusEqual:
10237 case OO_StarEqual:
10238 case OO_SlashEqual:
10239 case OO_PercentEqual:
10240 case OO_CaretEqual:
10241 case OO_AmpEqual:
10242 case OO_PipeEqual:
10243 case OO_LessLess:
10244 case OO_GreaterGreater:
10245 case OO_LessLessEqual:
10246 case OO_GreaterGreaterEqual:
10247 case OO_EqualEqual:
10248 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000010249 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010250 case OO_PlusPlus:
10251 case OO_MinusMinus:
10252 case OO_Comma:
10253 case OO_ArrowStar:
10254 case OO_Arrow:
10255 case OO_Call:
10256 case OO_Subscript:
10257 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000010258 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010259 case NUM_OVERLOADED_OPERATORS:
10260 llvm_unreachable("Unexpected reduction identifier");
10261 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000010262 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010263 if (II->isStr("max"))
10264 BOK = BO_GT;
10265 else if (II->isStr("min"))
10266 BOK = BO_LT;
10267 }
10268 break;
10269 }
10270 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010271 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000010272 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010273 else
10274 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010275 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010276
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010277 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10278 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000010279 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010280 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000010281 // OpenMP [2.1, C/C++]
10282 // A list item is a variable or array section, subject to the restrictions
10283 // specified in Section 2.4 on page 42 and in each of the sections
10284 // describing clauses and directives for which a list appears.
10285 // OpenMP [2.14.3.3, Restrictions, p.1]
10286 // A variable that is part of another variable (as an array or
10287 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010288 if (!FirstIter && IR != ER)
10289 ++IR;
10290 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010291 SourceLocation ELoc;
10292 SourceRange ERange;
10293 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010294 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000010295 /*AllowArraySection=*/true);
10296 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010297 // Try to find 'declare reduction' corresponding construct before using
10298 // builtin/overloaded operators.
10299 QualType Type = Context.DependentTy;
10300 CXXCastPath BasePath;
10301 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010302 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010303 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010304 Expr *ReductionOp = nullptr;
10305 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010306 (DeclareReductionRef.isUnset() ||
10307 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010308 ReductionOp = DeclareReductionRef.get();
10309 // It will be analyzed later.
10310 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010311 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010312 ValueDecl *D = Res.first;
10313 if (!D)
10314 continue;
10315
Alexey Bataev88202be2017-07-27 13:20:36 +000010316 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000010317 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010318 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10319 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000010320 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000010321 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010322 } else if (OASE) {
10323 QualType BaseType =
10324 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10325 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000010326 Type = ATy->getElementType();
10327 else
10328 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000010329 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010330 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010331 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000010332 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010333 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000010334
Alexey Bataevc5e02582014-06-16 07:08:35 +000010335 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10336 // A variable that appears in a private clause must not have an incomplete
10337 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010338 if (S.RequireCompleteType(ELoc, Type,
10339 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010340 continue;
10341 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000010342 // A list item that appears in a reduction clause must not be
10343 // const-qualified.
10344 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010345 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010346 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010347 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10348 VarDecl::DeclarationOnly;
10349 S.Diag(D->getLocation(),
10350 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010351 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010352 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010353 continue;
10354 }
10355 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10356 // If a list-item is a reference type then it must bind to the same object
10357 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010358 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010359 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010360 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010361 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010362 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010363 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10364 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010365 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010366 continue;
10367 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010368 }
10369 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010370
Alexey Bataevc5e02582014-06-16 07:08:35 +000010371 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10372 // in a Construct]
10373 // Variables with the predetermined data-sharing attributes may not be
10374 // listed in data-sharing attributes clauses, except for the cases
10375 // listed below. For these exceptions only, listing a predetermined
10376 // variable in a data-sharing attribute clause is allowed and overrides
10377 // the variable's predetermined data-sharing attributes.
10378 // OpenMP [2.14.3.6, Restrictions, p.3]
10379 // Any number of reduction clauses can be specified on the directive,
10380 // but a list item can appear only once in the reduction clauses for that
10381 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +000010382 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010383 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010384 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010385 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010386 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010387 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010388 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010389 }
10390 if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010391 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010392 << getOpenMPClauseName(DVar.CKind)
10393 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000010394 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010395 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010396 }
10397
10398 // OpenMP [2.14.3.6, Restrictions, p.1]
10399 // A list item that appears in a reduction clause of a worksharing
10400 // construct must be shared in the parallel regions to which any of the
10401 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010402 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010403 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010404 !isOpenMPParallelDirective(CurrDir) &&
10405 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010406 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010407 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010408 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010409 << getOpenMPClauseName(OMPC_reduction)
10410 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010411 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010412 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010413 }
10414 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010415
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010416 // Try to find 'declare reduction' corresponding construct before using
10417 // builtin/overloaded operators.
10418 CXXCastPath BasePath;
10419 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010420 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010421 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10422 if (DeclareReductionRef.isInvalid())
10423 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010424 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010425 (DeclareReductionRef.isUnset() ||
10426 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010427 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010428 continue;
10429 }
10430 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10431 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010432 S.Diag(ReductionId.getLocStart(),
10433 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010434 << Type << ReductionIdRange;
10435 continue;
10436 }
10437
10438 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10439 // The type of a list item that appears in a reduction clause must be valid
10440 // for the reduction-identifier. For a max or min reduction in C, the type
10441 // of the list item must be an allowed arithmetic data type: char, int,
10442 // float, double, or _Bool, possibly modified with long, short, signed, or
10443 // unsigned. For a max or min reduction in C++, the type of the list item
10444 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10445 // double, or bool, possibly modified with long, short, signed, or unsigned.
10446 if (DeclareReductionRef.isUnset()) {
10447 if ((BOK == BO_GT || BOK == BO_LT) &&
10448 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010449 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10450 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010451 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010452 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010453 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10454 VarDecl::DeclarationOnly;
10455 S.Diag(D->getLocation(),
10456 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010457 << D;
10458 }
10459 continue;
10460 }
10461 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010462 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010463 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10464 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010465 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010466 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10467 VarDecl::DeclarationOnly;
10468 S.Diag(D->getLocation(),
10469 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010470 << D;
10471 }
10472 continue;
10473 }
10474 }
10475
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010476 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010477 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
10478 D->hasAttrs() ? &D->getAttrs() : nullptr);
10479 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
10480 D->hasAttrs() ? &D->getAttrs() : nullptr);
10481 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010482
10483 // Try if we can determine constant lengths for all array sections and avoid
10484 // the VLA.
10485 bool ConstantLengthOASE = false;
10486 if (OASE) {
10487 bool SingleElement;
10488 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000010489 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010490 Context, OASE, SingleElement, ArraySizes);
10491
10492 // If we don't have a single element, we must emit a constant array type.
10493 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010494 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010495 PrivateTy = Context.getConstantArrayType(
10496 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010497 }
10498 }
10499
10500 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010501 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010502 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010503 if (!Context.getTargetInfo().isVLASupported() &&
10504 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10505 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10506 S.Diag(ELoc, diag::note_vla_unsupported);
10507 continue;
10508 }
David Majnemer9d168222016-08-05 17:44:54 +000010509 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010510 // Create pseudo array type for private copy. The size for this array will
10511 // be generated during codegen.
10512 // For array subscripts or single variables Private Ty is the same as Type
10513 // (type of the variable or single array element).
10514 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010515 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010516 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010517 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010518 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000010519 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010520 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010521 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010522 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000010523 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010524 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
10525 D->hasAttrs() ? &D->getAttrs() : nullptr,
10526 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010527 // Add initializer for private variable.
10528 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010529 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10530 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010531 if (DeclareReductionRef.isUsable()) {
10532 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10533 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10534 if (DRD->getInitializer()) {
10535 Init = DRDRef;
10536 RHSVD->setInit(DRDRef);
10537 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010538 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010539 } else {
10540 switch (BOK) {
10541 case BO_Add:
10542 case BO_Xor:
10543 case BO_Or:
10544 case BO_LOr:
10545 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10546 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010547 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010548 break;
10549 case BO_Mul:
10550 case BO_LAnd:
10551 if (Type->isScalarType() || Type->isAnyComplexType()) {
10552 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010553 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010554 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010555 break;
10556 case BO_And: {
10557 // '&' reduction op - initializer is '~0'.
10558 QualType OrigType = Type;
10559 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10560 Type = ComplexTy->getElementType();
10561 if (Type->isRealFloatingType()) {
10562 llvm::APFloat InitValue =
10563 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10564 /*isIEEE=*/true);
10565 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10566 Type, ELoc);
10567 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010568 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010569 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10570 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10571 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10572 }
10573 if (Init && OrigType->isAnyComplexType()) {
10574 // Init = 0xFFFF + 0xFFFFi;
10575 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010576 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010577 }
10578 Type = OrigType;
10579 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010580 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010581 case BO_LT:
10582 case BO_GT: {
10583 // 'min' reduction op - initializer is 'Largest representable number in
10584 // the reduction list item type'.
10585 // 'max' reduction op - initializer is 'Least representable number in
10586 // the reduction list item type'.
10587 if (Type->isIntegerType() || Type->isPointerType()) {
10588 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000010589 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010590 QualType IntTy =
10591 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10592 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010593 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10594 : llvm::APInt::getMinValue(Size)
10595 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10596 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010597 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10598 if (Type->isPointerType()) {
10599 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010600 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010601 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010602 if (CastExpr.isInvalid())
10603 continue;
10604 Init = CastExpr.get();
10605 }
10606 } else if (Type->isRealFloatingType()) {
10607 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10608 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10609 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10610 Type, ELoc);
10611 }
10612 break;
10613 }
10614 case BO_PtrMemD:
10615 case BO_PtrMemI:
10616 case BO_MulAssign:
10617 case BO_Div:
10618 case BO_Rem:
10619 case BO_Sub:
10620 case BO_Shl:
10621 case BO_Shr:
10622 case BO_LE:
10623 case BO_GE:
10624 case BO_EQ:
10625 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000010626 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010627 case BO_AndAssign:
10628 case BO_XorAssign:
10629 case BO_OrAssign:
10630 case BO_Assign:
10631 case BO_AddAssign:
10632 case BO_SubAssign:
10633 case BO_DivAssign:
10634 case BO_RemAssign:
10635 case BO_ShlAssign:
10636 case BO_ShrAssign:
10637 case BO_Comma:
10638 llvm_unreachable("Unexpected reduction operation");
10639 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010640 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010641 if (Init && DeclareReductionRef.isUnset())
10642 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10643 else if (!Init)
10644 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010645 if (RHSVD->isInvalidDecl())
10646 continue;
10647 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010648 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10649 << Type << ReductionIdRange;
10650 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10651 VarDecl::DeclarationOnly;
10652 S.Diag(D->getLocation(),
10653 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010654 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010655 continue;
10656 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010657 // Store initializer for single element in private copy. Will be used during
10658 // codegen.
10659 PrivateVD->setInit(RHSVD->getInit());
10660 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000010661 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010662 ExprResult ReductionOp;
10663 if (DeclareReductionRef.isUsable()) {
10664 QualType RedTy = DeclareReductionRef.get()->getType();
10665 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010666 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10667 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010668 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010669 LHS = S.DefaultLvalueConversion(LHS.get());
10670 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010671 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10672 CK_UncheckedDerivedToBase, LHS.get(),
10673 &BasePath, LHS.get()->getValueKind());
10674 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10675 CK_UncheckedDerivedToBase, RHS.get(),
10676 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010677 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010678 FunctionProtoType::ExtProtoInfo EPI;
10679 QualType Params[] = {PtrRedTy, PtrRedTy};
10680 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10681 auto *OVE = new (Context) OpaqueValueExpr(
10682 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010683 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010684 Expr *Args[] = {LHS.get(), RHS.get()};
10685 ReductionOp = new (Context)
10686 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10687 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010688 ReductionOp = S.BuildBinOp(
10689 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010690 if (ReductionOp.isUsable()) {
10691 if (BOK != BO_LT && BOK != BO_GT) {
10692 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010693 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10694 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010695 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010696 auto *ConditionalOp = new (Context)
10697 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10698 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010699 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010700 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10701 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010702 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010703 if (ReductionOp.isUsable())
10704 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010705 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010706 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010707 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010708 }
10709
Alexey Bataevfa312f32017-07-21 18:48:21 +000010710 // OpenMP [2.15.4.6, Restrictions, p.2]
10711 // A list item that appears in an in_reduction clause of a task construct
10712 // must appear in a task_reduction clause of a construct associated with a
10713 // taskgroup region that includes the participating task in its taskgroup
10714 // set. The construct associated with the innermost region that meets this
10715 // condition must specify the same reduction-identifier as the in_reduction
10716 // clause.
10717 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010718 SourceRange ParentSR;
10719 BinaryOperatorKind ParentBOK;
10720 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010721 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010722 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010723 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10724 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010725 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010726 Stack->getTopMostTaskgroupReductionData(
10727 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010728 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10729 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10730 if (!IsParentBOK && !IsParentReductionOp) {
10731 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10732 continue;
10733 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010734 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10735 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10736 IsParentReductionOp) {
10737 bool EmitError = true;
10738 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10739 llvm::FoldingSetNodeID RedId, ParentRedId;
10740 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10741 DeclareReductionRef.get()->Profile(RedId, Context,
10742 /*Canonical=*/true);
10743 EmitError = RedId != ParentRedId;
10744 }
10745 if (EmitError) {
10746 S.Diag(ReductionId.getLocStart(),
10747 diag::err_omp_reduction_identifier_mismatch)
10748 << ReductionIdRange << RefExpr->getSourceRange();
10749 S.Diag(ParentSR.getBegin(),
10750 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010751 << ParentSR
10752 << (IsParentBOK ? ParentBOKDSA.RefExpr
10753 : ParentReductionOpDSA.RefExpr)
10754 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010755 continue;
10756 }
10757 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010758 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10759 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010760 }
10761
Alexey Bataev60da77e2016-02-29 05:54:20 +000010762 DeclRefExpr *Ref = nullptr;
10763 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010764 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010765 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010766 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010767 VarsExpr =
10768 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10769 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010770 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010771 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010772 }
Alexey Bataeve3727102018-04-18 15:57:46 +000010773 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010774 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010775 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010776 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010777 if (!RefRes.isUsable())
10778 continue;
10779 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010780 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10781 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010782 if (!PostUpdateRes.isUsable())
10783 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010784 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10785 Stack->getCurrentDirective() == OMPD_taskgroup) {
10786 S.Diag(RefExpr->getExprLoc(),
10787 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010788 << RefExpr->getSourceRange();
10789 continue;
10790 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010791 RD.ExprPostUpdates.emplace_back(
10792 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010793 }
10794 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010795 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010796 // All reduction items are still marked as reduction (to do not increase
10797 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010798 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010799 if (CurrDir == OMPD_taskgroup) {
10800 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010801 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10802 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010803 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010804 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010805 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010806 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10807 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010808 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010809 return RD.Vars.empty();
10810}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010811
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010812OMPClause *Sema::ActOnOpenMPReductionClause(
10813 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10814 SourceLocation ColonLoc, SourceLocation EndLoc,
10815 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10816 ArrayRef<Expr *> UnresolvedReductions) {
10817 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000010818 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000010819 StartLoc, LParenLoc, ColonLoc, EndLoc,
10820 ReductionIdScopeSpec, ReductionId,
10821 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010822 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010823
Alexey Bataevc5e02582014-06-16 07:08:35 +000010824 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010825 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10826 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10827 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10828 buildPreInits(Context, RD.ExprCaptures),
10829 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010830}
10831
Alexey Bataev169d96a2017-07-18 20:17:46 +000010832OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10833 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10834 SourceLocation ColonLoc, SourceLocation EndLoc,
10835 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10836 ArrayRef<Expr *> UnresolvedReductions) {
10837 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000010838 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
10839 StartLoc, LParenLoc, ColonLoc, EndLoc,
10840 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000010841 UnresolvedReductions, RD))
10842 return nullptr;
10843
10844 return OMPTaskReductionClause::Create(
10845 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10846 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10847 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10848 buildPreInits(Context, RD.ExprCaptures),
10849 buildPostUpdate(*this, RD.ExprPostUpdates));
10850}
10851
Alexey Bataevfa312f32017-07-21 18:48:21 +000010852OMPClause *Sema::ActOnOpenMPInReductionClause(
10853 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10854 SourceLocation ColonLoc, SourceLocation EndLoc,
10855 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10856 ArrayRef<Expr *> UnresolvedReductions) {
10857 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000010858 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010859 StartLoc, LParenLoc, ColonLoc, EndLoc,
10860 ReductionIdScopeSpec, ReductionId,
10861 UnresolvedReductions, RD))
10862 return nullptr;
10863
10864 return OMPInReductionClause::Create(
10865 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10866 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010867 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010868 buildPreInits(Context, RD.ExprCaptures),
10869 buildPostUpdate(*this, RD.ExprPostUpdates));
10870}
10871
Alexey Bataevecba70f2016-04-12 11:02:11 +000010872bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10873 SourceLocation LinLoc) {
10874 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10875 LinKind == OMPC_LINEAR_unknown) {
10876 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10877 return true;
10878 }
10879 return false;
10880}
10881
Alexey Bataeve3727102018-04-18 15:57:46 +000010882bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000010883 OpenMPLinearClauseKind LinKind,
10884 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010885 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000010886 // A variable must not have an incomplete type or a reference type.
10887 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10888 return true;
10889 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10890 !Type->isReferenceType()) {
10891 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10892 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10893 return true;
10894 }
10895 Type = Type.getNonReferenceType();
10896
10897 // A list item must not be const-qualified.
10898 if (Type.isConstant(Context)) {
10899 Diag(ELoc, diag::err_omp_const_variable)
10900 << getOpenMPClauseName(OMPC_linear);
10901 if (D) {
10902 bool IsDecl =
10903 !VD ||
10904 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10905 Diag(D->getLocation(),
10906 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10907 << D;
10908 }
10909 return true;
10910 }
10911
10912 // A list item must be of integral or pointer type.
10913 Type = Type.getUnqualifiedType().getCanonicalType();
10914 const auto *Ty = Type.getTypePtrOrNull();
10915 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10916 !Ty->isPointerType())) {
10917 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10918 if (D) {
10919 bool IsDecl =
10920 !VD ||
10921 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10922 Diag(D->getLocation(),
10923 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10924 << D;
10925 }
10926 return true;
10927 }
10928 return false;
10929}
10930
Alexey Bataev182227b2015-08-20 10:54:39 +000010931OMPClause *Sema::ActOnOpenMPLinearClause(
10932 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10933 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10934 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010935 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010936 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010937 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010938 SmallVector<Decl *, 4> ExprCaptures;
10939 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010940 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010941 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000010942 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010943 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010944 SourceLocation ELoc;
10945 SourceRange ERange;
10946 Expr *SimpleRefExpr = RefExpr;
10947 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10948 /*AllowArraySection=*/false);
10949 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010950 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010951 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010952 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010953 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010954 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010955 ValueDecl *D = Res.first;
10956 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010957 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010958
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010959 QualType Type = D->getType();
10960 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010961
10962 // OpenMP [2.14.3.7, linear clause]
10963 // A list-item cannot appear in more than one linear clause.
10964 // A list-item that appears in a linear clause cannot appear in any
10965 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000010966 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010967 if (DVar.RefExpr) {
10968 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10969 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000010970 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010971 continue;
10972 }
10973
Alexey Bataevecba70f2016-04-12 11:02:11 +000010974 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010975 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010976 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010977
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010978 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000010979 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010980 buildVarDecl(*this, ELoc, Type, D->getName(),
10981 D->hasAttrs() ? &D->getAttrs() : nullptr,
10982 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010983 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010984 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010985 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010986 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010987 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010988 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010989 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010990 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010991 ExprCaptures.push_back(Ref->getDecl());
10992 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10993 ExprResult RefRes = DefaultLvalueConversion(Ref);
10994 if (!RefRes.isUsable())
10995 continue;
10996 ExprResult PostUpdateRes =
10997 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10998 SimpleRefExpr, RefRes.get());
10999 if (!PostUpdateRes.isUsable())
11000 continue;
11001 ExprPostUpdates.push_back(
11002 IgnoredValueConversions(PostUpdateRes.get()).get());
11003 }
11004 }
11005 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011006 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011007 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011008 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011009 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011010 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011011 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011012 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011013
11014 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011015 Vars.push_back((VD || CurContext->isDependentContext())
11016 ? RefExpr->IgnoreParens()
11017 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011018 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000011019 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000011020 }
11021
11022 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011023 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011024
11025 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000011026 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011027 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11028 !Step->isInstantiationDependent() &&
11029 !Step->containsUnexpandedParameterPack()) {
11030 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011031 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000011032 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011033 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011034 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000011035
Alexander Musman3276a272015-03-21 10:12:56 +000011036 // Build var to save the step value.
11037 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011038 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000011039 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011040 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011041 ExprResult CalcStep =
11042 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011043 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000011044
Alexander Musman8dba6642014-04-22 13:09:42 +000011045 // Warn about zero linear step (it would be probably better specified as
11046 // making corresponding variables 'const').
11047 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000011048 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11049 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000011050 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11051 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000011052 if (!IsConstant && CalcStep.isUsable()) {
11053 // Calculate the step beforehand instead of doing this on each iteration.
11054 // (This is not used if the number of iterations may be kfold-ed).
11055 CalcStepExpr = CalcStep.get();
11056 }
Alexander Musman8dba6642014-04-22 13:09:42 +000011057 }
11058
Alexey Bataev182227b2015-08-20 10:54:39 +000011059 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11060 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011061 StepExpr, CalcStepExpr,
11062 buildPreInits(Context, ExprCaptures),
11063 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000011064}
11065
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011066static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11067 Expr *NumIterations, Sema &SemaRef,
11068 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000011069 // Walk the vars and build update/final expressions for the CodeGen.
11070 SmallVector<Expr *, 8> Updates;
11071 SmallVector<Expr *, 8> Finals;
11072 Expr *Step = Clause.getStep();
11073 Expr *CalcStep = Clause.getCalcStep();
11074 // OpenMP [2.14.3.7, linear clause]
11075 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000011076 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000011077 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011078 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000011079 Step = cast<BinaryOperator>(CalcStep)->getLHS();
11080 bool HasErrors = false;
11081 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011082 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000011083 OpenMPLinearClauseKind LinKind = Clause.getModifier();
11084 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011085 SourceLocation ELoc;
11086 SourceRange ERange;
11087 Expr *SimpleRefExpr = RefExpr;
11088 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
11089 /*AllowArraySection=*/false);
11090 ValueDecl *D = Res.first;
11091 if (Res.second || !D) {
11092 Updates.push_back(nullptr);
11093 Finals.push_back(nullptr);
11094 HasErrors = true;
11095 continue;
11096 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011097 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011098 // OpenMP [2.15.11, distribute simd Construct]
11099 // A list item may not appear in a linear clause, unless it is the loop
11100 // iteration variable.
11101 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11102 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11103 SemaRef.Diag(ELoc,
11104 diag::err_omp_linear_distribute_var_non_loop_iteration);
11105 Updates.push_back(nullptr);
11106 Finals.push_back(nullptr);
11107 HasErrors = true;
11108 continue;
11109 }
Alexander Musman3276a272015-03-21 10:12:56 +000011110 Expr *InitExpr = *CurInit;
11111
11112 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011113 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011114 Expr *CapturedRef;
11115 if (LinKind == OMPC_LINEAR_uval)
11116 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11117 else
11118 CapturedRef =
11119 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11120 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11121 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011122
11123 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011124 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000011125 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011126 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000011127 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011128 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011129 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011130 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011131 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
11132 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011133
11134 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011135 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000011136 if (!Info.first)
11137 Final =
11138 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11139 InitExpr, NumIterations, Step, /*Subtract=*/false);
11140 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011141 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011142 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
11143 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011144
Alexander Musman3276a272015-03-21 10:12:56 +000011145 if (!Update.isUsable() || !Final.isUsable()) {
11146 Updates.push_back(nullptr);
11147 Finals.push_back(nullptr);
11148 HasErrors = true;
11149 } else {
11150 Updates.push_back(Update.get());
11151 Finals.push_back(Final.get());
11152 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011153 ++CurInit;
11154 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011155 }
11156 Clause.setUpdates(Updates);
11157 Clause.setFinals(Finals);
11158 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011159}
11160
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011161OMPClause *Sema::ActOnOpenMPAlignedClause(
11162 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11163 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011164 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000011165 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011166 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11167 SourceLocation ELoc;
11168 SourceRange ERange;
11169 Expr *SimpleRefExpr = RefExpr;
11170 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11171 /*AllowArraySection=*/false);
11172 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011173 // It will be analyzed later.
11174 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011175 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011176 ValueDecl *D = Res.first;
11177 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011178 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011179
Alexey Bataev1efd1662016-03-29 10:59:56 +000011180 QualType QType = D->getType();
11181 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011182
11183 // OpenMP [2.8.1, simd construct, Restrictions]
11184 // The type of list items appearing in the aligned clause must be
11185 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011186 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011187 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011188 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011189 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011190 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011191 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011192 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011193 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011194 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011195 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011196 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011197 continue;
11198 }
11199
11200 // OpenMP [2.8.1, simd construct, Restrictions]
11201 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011202 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011203 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011204 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11205 << getOpenMPClauseName(OMPC_aligned);
11206 continue;
11207 }
11208
Alexey Bataev1efd1662016-03-29 10:59:56 +000011209 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011210 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000011211 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11212 Vars.push_back(DefaultFunctionArrayConversion(
11213 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11214 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011215 }
11216
11217 // OpenMP [2.8.1, simd construct, Description]
11218 // The parameter of the aligned clause, alignment, must be a constant
11219 // positive integer expression.
11220 // If no optional parameter is specified, implementation-defined default
11221 // alignments for SIMD instructions on the target platforms are assumed.
11222 if (Alignment != nullptr) {
11223 ExprResult AlignResult =
11224 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11225 if (AlignResult.isInvalid())
11226 return nullptr;
11227 Alignment = AlignResult.get();
11228 }
11229 if (Vars.empty())
11230 return nullptr;
11231
11232 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11233 EndLoc, Vars, Alignment);
11234}
11235
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011236OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11237 SourceLocation StartLoc,
11238 SourceLocation LParenLoc,
11239 SourceLocation EndLoc) {
11240 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011241 SmallVector<Expr *, 8> SrcExprs;
11242 SmallVector<Expr *, 8> DstExprs;
11243 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000011244 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011245 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11246 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011247 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011248 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011249 SrcExprs.push_back(nullptr);
11250 DstExprs.push_back(nullptr);
11251 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011252 continue;
11253 }
11254
Alexey Bataeved09d242014-05-28 05:53:51 +000011255 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011256 // OpenMP [2.1, C/C++]
11257 // A list item is a variable name.
11258 // OpenMP [2.14.4.1, Restrictions, p.1]
11259 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000011260 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011261 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011262 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11263 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011264 continue;
11265 }
11266
11267 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000011268 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011269
11270 QualType Type = VD->getType();
11271 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11272 // It will be analyzed later.
11273 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011274 SrcExprs.push_back(nullptr);
11275 DstExprs.push_back(nullptr);
11276 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011277 continue;
11278 }
11279
11280 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11281 // A list item that appears in a copyin clause must be threadprivate.
11282 if (!DSAStack->isThreadPrivate(VD)) {
11283 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000011284 << getOpenMPClauseName(OMPC_copyin)
11285 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011286 continue;
11287 }
11288
11289 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11290 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000011291 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011292 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011293 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
11294 VarDecl *SrcVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011295 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11296 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011297 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011298 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000011299 VarDecl *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011300 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11301 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011302 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011303 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011304 // For arrays generate assignment operation for single element and replace
11305 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000011306 ExprResult AssignmentOp =
11307 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
11308 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011309 if (AssignmentOp.isInvalid())
11310 continue;
11311 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11312 /*DiscardedValue=*/true);
11313 if (AssignmentOp.isInvalid())
11314 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011315
11316 DSAStack->addDSA(VD, DE, OMPC_copyin);
11317 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011318 SrcExprs.push_back(PseudoSrcExpr);
11319 DstExprs.push_back(PseudoDstExpr);
11320 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011321 }
11322
Alexey Bataeved09d242014-05-28 05:53:51 +000011323 if (Vars.empty())
11324 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011325
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011326 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11327 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011328}
11329
Alexey Bataevbae9a792014-06-27 10:37:06 +000011330OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11331 SourceLocation StartLoc,
11332 SourceLocation LParenLoc,
11333 SourceLocation EndLoc) {
11334 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000011335 SmallVector<Expr *, 8> SrcExprs;
11336 SmallVector<Expr *, 8> DstExprs;
11337 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000011338 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011339 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11340 SourceLocation ELoc;
11341 SourceRange ERange;
11342 Expr *SimpleRefExpr = RefExpr;
11343 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11344 /*AllowArraySection=*/false);
11345 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011346 // It will be analyzed later.
11347 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011348 SrcExprs.push_back(nullptr);
11349 DstExprs.push_back(nullptr);
11350 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011351 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011352 ValueDecl *D = Res.first;
11353 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011354 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011355
Alexey Bataeve122da12016-03-17 10:50:17 +000011356 QualType Type = D->getType();
11357 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011358
11359 // OpenMP [2.14.4.2, Restrictions, p.2]
11360 // A list item that appears in a copyprivate clause may not appear in a
11361 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011362 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011363 DSAStackTy::DSAVarData DVar =
11364 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011365 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11366 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011367 Diag(ELoc, diag::err_omp_wrong_dsa)
11368 << getOpenMPClauseName(DVar.CKind)
11369 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011370 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011371 continue;
11372 }
11373
11374 // OpenMP [2.11.4.2, Restrictions, p.1]
11375 // All list items that appear in a copyprivate clause must be either
11376 // threadprivate or private in the enclosing context.
11377 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011378 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011379 if (DVar.CKind == OMPC_shared) {
11380 Diag(ELoc, diag::err_omp_required_access)
11381 << getOpenMPClauseName(OMPC_copyprivate)
11382 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000011383 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011384 continue;
11385 }
11386 }
11387 }
11388
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011389 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011390 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011391 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011392 << getOpenMPClauseName(OMPC_copyprivate) << Type
11393 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011394 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011395 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011396 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011397 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011398 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011399 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011400 continue;
11401 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011402
Alexey Bataevbae9a792014-06-27 10:37:06 +000011403 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11404 // A variable of class type (or array thereof) that appears in a
11405 // copyin clause requires an accessible, unambiguous copy assignment
11406 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011407 Type = Context.getBaseElementType(Type.getNonReferenceType())
11408 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011409 VarDecl *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011410 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11411 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011412 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
11413 VarDecl *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011414 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11415 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011416 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
11417 ExprResult AssignmentOp = BuildBinOp(
11418 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011419 if (AssignmentOp.isInvalid())
11420 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011421 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011422 /*DiscardedValue=*/true);
11423 if (AssignmentOp.isInvalid())
11424 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011425
11426 // No need to mark vars as copyprivate, they are already threadprivate or
11427 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000011428 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000011429 Vars.push_back(
11430 VD ? RefExpr->IgnoreParens()
11431 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011432 SrcExprs.push_back(PseudoSrcExpr);
11433 DstExprs.push_back(PseudoDstExpr);
11434 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011435 }
11436
11437 if (Vars.empty())
11438 return nullptr;
11439
Alexey Bataeva63048e2015-03-23 06:18:07 +000011440 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11441 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011442}
11443
Alexey Bataev6125da92014-07-21 11:26:11 +000011444OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11445 SourceLocation StartLoc,
11446 SourceLocation LParenLoc,
11447 SourceLocation EndLoc) {
11448 if (VarList.empty())
11449 return nullptr;
11450
11451 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11452}
Alexey Bataevdea47612014-07-23 07:46:59 +000011453
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011454OMPClause *
11455Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11456 SourceLocation DepLoc, SourceLocation ColonLoc,
11457 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11458 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011459 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011460 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011461 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011462 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011463 return nullptr;
11464 }
11465 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011466 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11467 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011468 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011469 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011470 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11471 /*Last=*/OMPC_DEPEND_unknown, Except)
11472 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011473 return nullptr;
11474 }
11475 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011476 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011477 llvm::APSInt DepCounter(/*BitWidth=*/32);
11478 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11479 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011480 if (const Expr *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011481 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11482 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011483 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011484 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011485 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000011486 assert(RefExpr && "NULL expr in OpenMP shared clause.");
11487 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11488 // It will be analyzed later.
11489 Vars.push_back(RefExpr);
11490 continue;
11491 }
11492
11493 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000011494 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000011495 if (DepKind == OMPC_DEPEND_sink) {
11496 if (DSAStack->getParentOrderedRegionParam() &&
11497 DepCounter >= TotalDepCount) {
11498 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11499 continue;
11500 }
11501 ++DepCounter;
11502 // OpenMP [2.13.9, Summary]
11503 // depend(dependence-type : vec), where dependence-type is:
11504 // 'sink' and where vec is the iteration vector, which has the form:
11505 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11506 // where n is the value specified by the ordered clause in the loop
11507 // directive, xi denotes the loop iteration variable of the i-th nested
11508 // loop associated with the loop directive, and di is a constant
11509 // non-negative integer.
11510 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011511 // It will be analyzed later.
11512 Vars.push_back(RefExpr);
11513 continue;
11514 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011515 SimpleExpr = SimpleExpr->IgnoreImplicit();
11516 OverloadedOperatorKind OOK = OO_None;
11517 SourceLocation OOLoc;
11518 Expr *LHS = SimpleExpr;
11519 Expr *RHS = nullptr;
11520 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11521 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11522 OOLoc = BO->getOperatorLoc();
11523 LHS = BO->getLHS()->IgnoreParenImpCasts();
11524 RHS = BO->getRHS()->IgnoreParenImpCasts();
11525 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11526 OOK = OCE->getOperator();
11527 OOLoc = OCE->getOperatorLoc();
11528 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11529 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11530 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11531 OOK = MCE->getMethodDecl()
11532 ->getNameInfo()
11533 .getName()
11534 .getCXXOverloadedOperator();
11535 OOLoc = MCE->getCallee()->getExprLoc();
11536 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11537 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011538 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011539 SourceLocation ELoc;
11540 SourceRange ERange;
11541 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11542 /*AllowArraySection=*/false);
11543 if (Res.second) {
11544 // It will be analyzed later.
11545 Vars.push_back(RefExpr);
11546 }
11547 ValueDecl *D = Res.first;
11548 if (!D)
11549 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011550
Alexey Bataev17daedf2018-02-15 22:42:57 +000011551 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11552 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11553 continue;
11554 }
11555 if (RHS) {
11556 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11557 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11558 if (RHSRes.isInvalid())
11559 continue;
11560 }
11561 if (!CurContext->isDependentContext() &&
11562 DSAStack->getParentOrderedRegionParam() &&
11563 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011564 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000011565 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000011566 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000011567 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11568 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000011569 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000011570 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000011571 continue;
11572 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011573 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000011574 } else {
11575 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
11576 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
11577 (ASE &&
11578 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
11579 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
11580 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11581 << RefExpr->getSourceRange();
11582 continue;
11583 }
11584 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11585 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
11586 ExprResult Res =
11587 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
11588 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11589 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11590 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11591 << RefExpr->getSourceRange();
11592 continue;
11593 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011594 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011595 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011596 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011597
11598 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11599 TotalDepCount > VarList.size() &&
11600 DSAStack->getParentOrderedRegionParam() &&
11601 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11602 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
11603 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11604 }
11605 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11606 Vars.empty())
11607 return nullptr;
11608
Alexey Bataev8b427062016-05-25 12:36:08 +000011609 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11610 DepKind, DepLoc, ColonLoc, Vars);
Alexey Bataev17daedf2018-02-15 22:42:57 +000011611 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
11612 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000011613 DSAStack->addDoacrossDependClause(C, OpsOffs);
11614 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011615}
Michael Wonge710d542015-08-07 16:16:36 +000011616
11617OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11618 SourceLocation LParenLoc,
11619 SourceLocation EndLoc) {
11620 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011621 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011622
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011623 // OpenMP [2.9.1, Restrictions]
11624 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011625 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000011626 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011627 return nullptr;
11628
Alexey Bataev931e19b2017-10-02 16:32:39 +000011629 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011630 OpenMPDirectiveKind CaptureRegion =
11631 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11632 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011633 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011634 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011635 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11636 HelperValStmt = buildPreInits(Context, Captures);
11637 }
11638
Alexey Bataev8451efa2018-01-15 19:06:12 +000011639 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11640 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011641}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011642
Alexey Bataeve3727102018-04-18 15:57:46 +000011643static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000011644 DSAStackTy *Stack, QualType QTy,
11645 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000011646 NamedDecl *ND;
11647 if (QTy->isIncompleteType(&ND)) {
11648 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11649 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011650 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000011651 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
11652 !QTy.isTrivialType(SemaRef.Context))
11653 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011654 return true;
11655}
11656
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011657/// \brief Return true if it can be proven that the provided array expression
11658/// (array section or array subscript) does NOT specify the whole size of the
11659/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011660static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011661 const Expr *E,
11662 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011663 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011664
11665 // If this is an array subscript, it refers to the whole size if the size of
11666 // the dimension is constant and equals 1. Also, an array section assumes the
11667 // format of an array subscript if no colon is used.
11668 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011669 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011670 return ATy->getSize().getSExtValue() != 1;
11671 // Size can't be evaluated statically.
11672 return false;
11673 }
11674
11675 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000011676 const Expr *LowerBound = OASE->getLowerBound();
11677 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011678
11679 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011680 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011681 if (LowerBound) {
11682 llvm::APSInt ConstLowerBound;
11683 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11684 return false; // Can't get the integer value as a constant.
11685 if (ConstLowerBound.getSExtValue())
11686 return true;
11687 }
11688
11689 // If we don't have a length we covering the whole dimension.
11690 if (!Length)
11691 return false;
11692
11693 // If the base is a pointer, we don't have a way to get the size of the
11694 // pointee.
11695 if (BaseQTy->isPointerType())
11696 return false;
11697
11698 // We can only check if the length is the same as the size of the dimension
11699 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000011700 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011701 if (!CATy)
11702 return false;
11703
11704 llvm::APSInt ConstLength;
11705 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11706 return false; // Can't get the integer value as a constant.
11707
11708 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11709}
11710
11711// Return true if it can be proven that the provided array expression (array
11712// section or array subscript) does NOT specify a single element of the array
11713// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011714static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011715 const Expr *E,
11716 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011717 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011718
11719 // An array subscript always refer to a single element. Also, an array section
11720 // assumes the format of an array subscript if no colon is used.
11721 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11722 return false;
11723
11724 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000011725 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011726
11727 // If we don't have a length we have to check if the array has unitary size
11728 // for this dimension. Also, we should always expect a length if the base type
11729 // is pointer.
11730 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011731 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011732 return ATy->getSize().getSExtValue() != 1;
11733 // We cannot assume anything.
11734 return false;
11735 }
11736
11737 // Check if the length evaluates to 1.
11738 llvm::APSInt ConstLength;
11739 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11740 return false; // Can't get the integer value as a constant.
11741
11742 return ConstLength.getSExtValue() != 1;
11743}
11744
Samuel Antao661c0902016-05-26 17:39:58 +000011745// Return the expression of the base of the mappable expression or null if it
11746// cannot be determined and do all the necessary checks to see if the expression
11747// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011748// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000011749static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000011750 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011751 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011752 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011753 SourceLocation ELoc = E->getExprLoc();
11754 SourceRange ERange = E->getSourceRange();
11755
11756 // The base of elements of list in a map clause have to be either:
11757 // - a reference to variable or field.
11758 // - a member expression.
11759 // - an array expression.
11760 //
11761 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11762 // reference to 'r'.
11763 //
11764 // If we have:
11765 //
11766 // struct SS {
11767 // Bla S;
11768 // foo() {
11769 // #pragma omp target map (S.Arr[:12]);
11770 // }
11771 // }
11772 //
11773 // We want to retrieve the member expression 'this->S';
11774
Alexey Bataeve3727102018-04-18 15:57:46 +000011775 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011776
Samuel Antao5de996e2016-01-22 20:21:36 +000011777 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11778 // If a list item is an array section, it must specify contiguous storage.
11779 //
11780 // For this restriction it is sufficient that we make sure only references
11781 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011782 // exist except in the rightmost expression (unless they cover the whole
11783 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011784 //
11785 // r.ArrS[3:5].Arr[6:7]
11786 //
11787 // r.ArrS[3:5].x
11788 //
11789 // but these would be valid:
11790 // r.ArrS[3].Arr[6:7]
11791 //
11792 // r.ArrS[3].x
11793
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011794 bool AllowUnitySizeArraySection = true;
11795 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011796
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011797 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011798 E = E->IgnoreParenImpCasts();
11799
11800 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11801 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000011802 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011803
11804 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011805
11806 // If we got a reference to a declaration, we should not expect any array
11807 // section before that.
11808 AllowUnitySizeArraySection = false;
11809 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011810
11811 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011812 CurComponents.emplace_back(CurE, CurE->getDecl());
11813 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011814 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000011815
11816 if (isa<CXXThisExpr>(BaseE))
11817 // We found a base expression: this->Val.
11818 RelevantExpr = CurE;
11819 else
11820 E = BaseE;
11821
11822 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011823 if (!NoDiagnose) {
11824 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11825 << CurE->getSourceRange();
11826 return nullptr;
11827 }
11828 if (RelevantExpr)
11829 return nullptr;
11830 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011831 }
11832
11833 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11834
11835 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11836 // A bit-field cannot appear in a map clause.
11837 //
11838 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011839 if (!NoDiagnose) {
11840 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11841 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11842 return nullptr;
11843 }
11844 if (RelevantExpr)
11845 return nullptr;
11846 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011847 }
11848
11849 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11850 // If the type of a list item is a reference to a type T then the type
11851 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011852 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011853
11854 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11855 // A list item cannot be a variable that is a member of a structure with
11856 // a union type.
11857 //
Alexey Bataeve3727102018-04-18 15:57:46 +000011858 if (CurType->isUnionType()) {
11859 if (!NoDiagnose) {
11860 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11861 << CurE->getSourceRange();
11862 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011863 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011864 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011865 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011866
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011867 // If we got a member expression, we should not expect any array section
11868 // before that:
11869 //
11870 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11871 // If a list item is an element of a structure, only the rightmost symbol
11872 // of the variable reference can be an array section.
11873 //
11874 AllowUnitySizeArraySection = false;
11875 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011876
11877 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011878 CurComponents.emplace_back(CurE, FD);
11879 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011880 E = CurE->getBase()->IgnoreParenImpCasts();
11881
11882 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011883 if (!NoDiagnose) {
11884 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11885 << 0 << CurE->getSourceRange();
11886 return nullptr;
11887 }
11888 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011889 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011890
11891 // If we got an array subscript that express the whole dimension we
11892 // can have any array expressions before. If it only expressing part of
11893 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000011894 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011895 E->getType()))
11896 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011897
11898 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011899 CurComponents.emplace_back(CurE, nullptr);
11900 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011901 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000011902 E = CurE->getBase()->IgnoreParenImpCasts();
11903
Alexey Bataev27041fa2017-12-05 15:22:49 +000011904 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011905 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11906
Samuel Antao5de996e2016-01-22 20:21:36 +000011907 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11908 // If the type of a list item is a reference to a type T then the type
11909 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011910 if (CurType->isReferenceType())
11911 CurType = CurType->getPointeeType();
11912
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011913 bool IsPointer = CurType->isAnyPointerType();
11914
11915 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011916 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11917 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011918 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011919 }
11920
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011921 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000011922 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011923 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000011924 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011925
Samuel Antaodab51bb2016-07-18 23:22:11 +000011926 if (AllowWholeSizeArraySection) {
11927 // Any array section is currently allowed. Allowing a whole size array
11928 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011929 //
11930 // If this array section refers to the whole dimension we can still
11931 // accept other array sections before this one, except if the base is a
11932 // pointer. Otherwise, only unitary sections are accepted.
11933 if (NotWhole || IsPointer)
11934 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011935 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011936 // A unity or whole array section is not allowed and that is not
11937 // compatible with the properties of the current array section.
11938 SemaRef.Diag(
11939 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11940 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011941 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011942 }
Samuel Antao90927002016-04-26 14:54:23 +000011943
11944 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011945 CurComponents.emplace_back(CurE, nullptr);
11946 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011947 if (!NoDiagnose) {
11948 // If nothing else worked, this is not a valid map clause expression.
11949 SemaRef.Diag(
11950 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11951 << ERange;
11952 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000011953 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011954 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011955 }
11956
11957 return RelevantExpr;
11958}
11959
11960// Return true if expression E associated with value VD has conflicts with other
11961// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000011962static bool checkMapConflicts(
11963 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000011964 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011965 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11966 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011967 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011968 SourceLocation ELoc = E->getExprLoc();
11969 SourceRange ERange = E->getSourceRange();
11970
11971 // In order to easily check the conflicts we need to match each component of
11972 // the expression under test with the components of the expressions that are
11973 // already in the stack.
11974
Samuel Antao5de996e2016-01-22 20:21:36 +000011975 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011976 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011977 "Map clause expression with unexpected base!");
11978
11979 // Variables to help detecting enclosing problems in data environment nests.
11980 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011981 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011982
Samuel Antao90927002016-04-26 14:54:23 +000011983 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11984 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000011985 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
11986 ERange, CKind, &EnclosingExpr,
11987 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
11988 StackComponents,
11989 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011990 assert(!StackComponents.empty() &&
11991 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011992 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011993 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000011994 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011995
Samuel Antao90927002016-04-26 14:54:23 +000011996 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000011997 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000011998
Samuel Antao5de996e2016-01-22 20:21:36 +000011999 // Expressions must start from the same base. Here we detect at which
12000 // point both expressions diverge from each other and see if we can
12001 // detect if the memory referred to both expressions is contiguous and
12002 // do not overlap.
12003 auto CI = CurComponents.rbegin();
12004 auto CE = CurComponents.rend();
12005 auto SI = StackComponents.rbegin();
12006 auto SE = StackComponents.rend();
12007 for (; CI != CE && SI != SE; ++CI, ++SI) {
12008
12009 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12010 // At most one list item can be an array item derived from a given
12011 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000012012 if (CurrentRegionOnly &&
12013 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12014 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12015 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12016 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12017 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000012018 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000012019 << CI->getAssociatedExpression()->getSourceRange();
12020 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12021 diag::note_used_here)
12022 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000012023 return true;
12024 }
12025
12026 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000012027 if (CI->getAssociatedExpression()->getStmtClass() !=
12028 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000012029 break;
12030
12031 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000012032 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000012033 break;
12034 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000012035 // Check if the extra components of the expressions in the enclosing
12036 // data environment are redundant for the current base declaration.
12037 // If they are, the maps completely overlap, which is legal.
12038 for (; SI != SE; ++SI) {
12039 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000012040 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000012041 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000012042 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012043 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000012044 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012045 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000012046 Type =
12047 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12048 }
12049 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012050 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000012051 SemaRef, SI->getAssociatedExpression(), Type))
12052 break;
12053 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012054
12055 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12056 // List items of map clauses in the same construct must not share
12057 // original storage.
12058 //
12059 // If the expressions are exactly the same or one is a subset of the
12060 // other, it means they are sharing storage.
12061 if (CI == CE && SI == SE) {
12062 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012063 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000012064 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012065 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012066 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012067 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12068 << ERange;
12069 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012070 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12071 << RE->getSourceRange();
12072 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012073 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012074 // If we find the same expression in the enclosing data environment,
12075 // that is legal.
12076 IsEnclosedByDataEnvironmentExpr = true;
12077 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000012078 }
12079
Samuel Antao90927002016-04-26 14:54:23 +000012080 QualType DerivedType =
12081 std::prev(CI)->getAssociatedDeclaration()->getType();
12082 SourceLocation DerivedLoc =
12083 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000012084
12085 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12086 // If the type of a list item is a reference to a type T then the type
12087 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012088 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012089
12090 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12091 // A variable for which the type is pointer and an array section
12092 // derived from that variable must not appear as list items of map
12093 // clauses of the same construct.
12094 //
12095 // Also, cover one of the cases in:
12096 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12097 // If any part of the original storage of a list item has corresponding
12098 // storage in the device data environment, all of the original storage
12099 // must have corresponding storage in the device data environment.
12100 //
12101 if (DerivedType->isAnyPointerType()) {
12102 if (CI == CE || SI == SE) {
12103 SemaRef.Diag(
12104 DerivedLoc,
12105 diag::err_omp_pointer_mapped_along_with_derived_section)
12106 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012107 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12108 << RE->getSourceRange();
12109 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000012110 }
12111 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000012112 SI->getAssociatedExpression()->getStmtClass() ||
12113 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12114 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012115 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000012116 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000012117 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012118 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12119 << RE->getSourceRange();
12120 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012121 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012122 }
12123
12124 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12125 // List items of map clauses in the same construct must not share
12126 // original storage.
12127 //
12128 // An expression is a subset of the other.
12129 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012130 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000012131 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012132 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012133 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012134 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12135 << ERange;
12136 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012137 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12138 << RE->getSourceRange();
12139 return true;
12140 }
12141
12142 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012143 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012144 if (!CurrentRegionOnly && SI != SE)
12145 EnclosingExpr = RE;
12146
12147 // The current expression is a subset of the expression in the data
12148 // environment.
12149 IsEnclosedByDataEnvironmentExpr |=
12150 (!CurrentRegionOnly && CI != CE && SI == SE);
12151
12152 return false;
12153 });
12154
12155 if (CurrentRegionOnly)
12156 return FoundError;
12157
12158 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12159 // If any part of the original storage of a list item has corresponding
12160 // storage in the device data environment, all of the original storage must
12161 // have corresponding storage in the device data environment.
12162 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12163 // If a list item is an element of a structure, and a different element of
12164 // the structure has a corresponding list item in the device data environment
12165 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012166 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012167 // data environment prior to the task encountering the construct.
12168 //
12169 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12170 SemaRef.Diag(ELoc,
12171 diag::err_omp_original_storage_is_shared_and_does_not_contain)
12172 << ERange;
12173 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12174 << EnclosingExpr->getSourceRange();
12175 return true;
12176 }
12177
12178 return FoundError;
12179}
12180
Samuel Antao661c0902016-05-26 17:39:58 +000012181namespace {
12182// Utility struct that gathers all the related lists associated with a mappable
12183// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012184struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000012185 // The list of expressions.
12186 ArrayRef<Expr *> VarList;
12187 // The list of processed expressions.
12188 SmallVector<Expr *, 16> ProcessedVarList;
12189 // The mappble components for each expression.
12190 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12191 // The base declaration of the variable.
12192 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12193
12194 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12195 // We have a list of components and base declarations for each entry in the
12196 // variable list.
12197 VarComponents.reserve(VarList.size());
12198 VarBaseDeclarations.reserve(VarList.size());
12199 }
12200};
12201}
12202
12203// Check the validity of the provided variable list for the provided clause kind
12204// \a CKind. In the check process the valid expressions, and mappable expression
12205// components and variables are extracted and used to fill \a Vars,
12206// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12207// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12208static void
12209checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12210 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12211 SourceLocation StartLoc,
12212 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12213 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012214 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12215 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000012216 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012217
Samuel Antao90927002016-04-26 14:54:23 +000012218 // Keep track of the mappable components and base declarations in this clause.
12219 // Each entry in the list is going to have a list of components associated. We
12220 // record each set of the components so that we can build the clause later on.
12221 // In the end we should have the same amount of declarations and component
12222 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000012223
Alexey Bataeve3727102018-04-18 15:57:46 +000012224 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012225 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012226 SourceLocation ELoc = RE->getExprLoc();
12227
Alexey Bataeve3727102018-04-18 15:57:46 +000012228 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012229
12230 if (VE->isValueDependent() || VE->isTypeDependent() ||
12231 VE->isInstantiationDependent() ||
12232 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012233 // We can only analyze this information once the missing information is
12234 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000012235 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012236 continue;
12237 }
12238
Alexey Bataeve3727102018-04-18 15:57:46 +000012239 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012240
Samuel Antao5de996e2016-01-22 20:21:36 +000012241 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000012242 SemaRef.Diag(ELoc,
12243 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000012244 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012245 continue;
12246 }
12247
Samuel Antao90927002016-04-26 14:54:23 +000012248 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12249 ValueDecl *CurDeclaration = nullptr;
12250
12251 // Obtain the array or member expression bases if required. Also, fill the
12252 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000012253 const Expr *BE = checkMapClauseExpressionBase(
12254 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000012255 if (!BE)
12256 continue;
12257
Samuel Antao90927002016-04-26 14:54:23 +000012258 assert(!CurComponents.empty() &&
12259 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012260
Samuel Antao90927002016-04-26 14:54:23 +000012261 // For the following checks, we rely on the base declaration which is
12262 // expected to be associated with the last component. The declaration is
12263 // expected to be a variable or a field (if 'this' is being mapped).
12264 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12265 assert(CurDeclaration && "Null decl on map clause.");
12266 assert(
12267 CurDeclaration->isCanonicalDecl() &&
12268 "Expecting components to have associated only canonical declarations.");
12269
12270 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000012271 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000012272
12273 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000012274 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012275
12276 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000012277 // threadprivate variables cannot appear in a map clause.
12278 // OpenMP 4.5 [2.10.5, target update Construct]
12279 // threadprivate variables cannot appear in a from clause.
12280 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012281 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000012282 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12283 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012284 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012285 continue;
12286 }
12287
Samuel Antao5de996e2016-01-22 20:21:36 +000012288 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12289 // A list item cannot appear in both a map clause and a data-sharing
12290 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000012291
Samuel Antao5de996e2016-01-22 20:21:36 +000012292 // Check conflicts with other map clause expressions. We check the conflicts
12293 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000012294 // environment, because the restrictions are different. We only have to
12295 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000012296 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000012297 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012298 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012299 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000012300 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000012301 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012302 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012303
Samuel Antao661c0902016-05-26 17:39:58 +000012304 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000012305 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12306 // If the type of a list item is a reference to a type T then the type will
12307 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012308 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012309
Samuel Antao661c0902016-05-26 17:39:58 +000012310 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12311 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000012312 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000012313 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012314 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000012315 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000012316 continue;
12317
Samuel Antao661c0902016-05-26 17:39:58 +000012318 if (CKind == OMPC_map) {
12319 // target enter data
12320 // OpenMP [2.10.2, Restrictions, p. 99]
12321 // A map-type must be specified in all map clauses and must be either
12322 // to or alloc.
12323 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12324 if (DKind == OMPD_target_enter_data &&
12325 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12326 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12327 << (IsMapTypeImplicit ? 1 : 0)
12328 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12329 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012330 continue;
12331 }
Samuel Antao661c0902016-05-26 17:39:58 +000012332
12333 // target exit_data
12334 // OpenMP [2.10.3, Restrictions, p. 102]
12335 // A map-type must be specified in all map clauses and must be either
12336 // from, release, or delete.
12337 if (DKind == OMPD_target_exit_data &&
12338 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12339 MapType == OMPC_MAP_delete)) {
12340 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12341 << (IsMapTypeImplicit ? 1 : 0)
12342 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12343 << getOpenMPDirectiveName(DKind);
12344 continue;
12345 }
12346
12347 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12348 // A list item cannot appear in both a map clause and a data-sharing
12349 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000012350 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
12351 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000012352 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000012353 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000012354 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000012355 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000012356 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012357 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000012358 continue;
12359 }
12360 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012361 }
12362
Samuel Antao90927002016-04-26 14:54:23 +000012363 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012364 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012365
12366 // Store the components in the stack so that they can be used to check
12367 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012368 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12369 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012370
12371 // Save the components and declaration to create the clause. For purposes of
12372 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012373 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012374 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12375 MVLI.VarComponents.back().append(CurComponents.begin(),
12376 CurComponents.end());
12377 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12378 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012379 }
Samuel Antao661c0902016-05-26 17:39:58 +000012380}
12381
12382OMPClause *
12383Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12384 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12385 SourceLocation MapLoc, SourceLocation ColonLoc,
12386 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12387 SourceLocation LParenLoc, SourceLocation EndLoc) {
12388 MappableVarListInfo MVLI(VarList);
12389 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12390 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012391
Samuel Antao5de996e2016-01-22 20:21:36 +000012392 // We need to produce a map clause even if we don't have variables so that
12393 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012394 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12395 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12396 MVLI.VarComponents, MapTypeModifier, MapType,
12397 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012398}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012399
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012400QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12401 TypeResult ParsedType) {
12402 assert(ParsedType.isUsable());
12403
12404 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12405 if (ReductionType.isNull())
12406 return QualType();
12407
12408 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12409 // A type name in a declare reduction directive cannot be a function type, an
12410 // array type, a reference type, or a type qualified with const, volatile or
12411 // restrict.
12412 if (ReductionType.hasQualifiers()) {
12413 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12414 return QualType();
12415 }
12416
12417 if (ReductionType->isFunctionType()) {
12418 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12419 return QualType();
12420 }
12421 if (ReductionType->isReferenceType()) {
12422 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12423 return QualType();
12424 }
12425 if (ReductionType->isArrayType()) {
12426 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12427 return QualType();
12428 }
12429 return ReductionType;
12430}
12431
12432Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12433 Scope *S, DeclContext *DC, DeclarationName Name,
12434 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12435 AccessSpecifier AS, Decl *PrevDeclInScope) {
12436 SmallVector<Decl *, 8> Decls;
12437 Decls.reserve(ReductionTypes.size());
12438
12439 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012440 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012441 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12442 // A reduction-identifier may not be re-declared in the current scope for the
12443 // same type or for a type that is compatible according to the base language
12444 // rules.
12445 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12446 OMPDeclareReductionDecl *PrevDRD = nullptr;
12447 bool InCompoundScope = true;
12448 if (S != nullptr) {
12449 // Find previous declaration with the same name not referenced in other
12450 // declarations.
12451 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12452 InCompoundScope =
12453 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12454 LookupName(Lookup, S);
12455 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12456 /*AllowInlineNamespace=*/false);
12457 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000012458 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012459 while (Filter.hasNext()) {
12460 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12461 if (InCompoundScope) {
12462 auto I = UsedAsPrevious.find(PrevDecl);
12463 if (I == UsedAsPrevious.end())
12464 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000012465 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012466 UsedAsPrevious[D] = true;
12467 }
12468 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12469 PrevDecl->getLocation();
12470 }
12471 Filter.done();
12472 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012473 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012474 if (!PrevData.second) {
12475 PrevDRD = PrevData.first;
12476 break;
12477 }
12478 }
12479 }
12480 } else if (PrevDeclInScope != nullptr) {
12481 auto *PrevDRDInScope = PrevDRD =
12482 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12483 do {
12484 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12485 PrevDRDInScope->getLocation();
12486 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12487 } while (PrevDRDInScope != nullptr);
12488 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012489 for (const auto &TyData : ReductionTypes) {
12490 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012491 bool Invalid = false;
12492 if (I != PreviousRedeclTypes.end()) {
12493 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12494 << TyData.first;
12495 Diag(I->second, diag::note_previous_definition);
12496 Invalid = true;
12497 }
12498 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12499 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12500 Name, TyData.first, PrevDRD);
12501 DC->addDecl(DRD);
12502 DRD->setAccess(AS);
12503 Decls.push_back(DRD);
12504 if (Invalid)
12505 DRD->setInvalidDecl();
12506 else
12507 PrevDRD = DRD;
12508 }
12509
12510 return DeclGroupPtrTy::make(
12511 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12512}
12513
12514void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12515 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12516
12517 // Enter new function scope.
12518 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000012519 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012520 getCurFunction()->setHasOMPDeclareReductionCombiner();
12521
12522 if (S != nullptr)
12523 PushDeclContext(S, DRD);
12524 else
12525 CurContext = DRD;
12526
Faisal Valid143a0c2017-04-01 21:30:49 +000012527 PushExpressionEvaluationContext(
12528 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012529
12530 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012531 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12532 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12533 // uses semantics of argument handles by value, but it should be passed by
12534 // reference. C lang does not support references, so pass all parameters as
12535 // pointers.
12536 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000012537 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012538 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012539 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12540 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12541 // uses semantics of argument handles by value, but it should be passed by
12542 // reference. C lang does not support references, so pass all parameters as
12543 // pointers.
12544 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000012545 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012546 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12547 if (S != nullptr) {
12548 PushOnScopeChains(OmpInParm, S);
12549 PushOnScopeChains(OmpOutParm, S);
12550 } else {
12551 DRD->addDecl(OmpInParm);
12552 DRD->addDecl(OmpOutParm);
12553 }
12554}
12555
12556void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12557 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12558 DiscardCleanupsInEvaluationContext();
12559 PopExpressionEvaluationContext();
12560
12561 PopDeclContext();
12562 PopFunctionScopeInfo();
12563
12564 if (Combiner != nullptr)
12565 DRD->setCombiner(Combiner);
12566 else
12567 DRD->setInvalidDecl();
12568}
12569
Alexey Bataev070f43a2017-09-06 14:49:58 +000012570VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012571 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12572
12573 // Enter new function scope.
12574 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000012575 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012576
12577 if (S != nullptr)
12578 PushDeclContext(S, DRD);
12579 else
12580 CurContext = DRD;
12581
Faisal Valid143a0c2017-04-01 21:30:49 +000012582 PushExpressionEvaluationContext(
12583 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012584
12585 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012586 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12587 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12588 // uses semantics of argument handles by value, but it should be passed by
12589 // reference. C lang does not support references, so pass all parameters as
12590 // pointers.
12591 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000012592 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012593 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012594 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12595 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12596 // uses semantics of argument handles by value, but it should be passed by
12597 // reference. C lang does not support references, so pass all parameters as
12598 // pointers.
12599 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000012600 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012601 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012602 if (S != nullptr) {
12603 PushOnScopeChains(OmpPrivParm, S);
12604 PushOnScopeChains(OmpOrigParm, S);
12605 } else {
12606 DRD->addDecl(OmpPrivParm);
12607 DRD->addDecl(OmpOrigParm);
12608 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012609 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012610}
12611
Alexey Bataev070f43a2017-09-06 14:49:58 +000012612void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12613 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012614 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12615 DiscardCleanupsInEvaluationContext();
12616 PopExpressionEvaluationContext();
12617
12618 PopDeclContext();
12619 PopFunctionScopeInfo();
12620
Alexey Bataev070f43a2017-09-06 14:49:58 +000012621 if (Initializer != nullptr) {
12622 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12623 } else if (OmpPrivParm->hasInit()) {
12624 DRD->setInitializer(OmpPrivParm->getInit(),
12625 OmpPrivParm->isDirectInit()
12626 ? OMPDeclareReductionDecl::DirectInit
12627 : OMPDeclareReductionDecl::CopyInit);
12628 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012629 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012630 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012631}
12632
12633Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12634 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012635 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012636 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012637 if (S)
12638 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
12639 /*AddToContext=*/false);
12640 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012641 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012642 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012643 }
12644 return DeclReductions;
12645}
12646
David Majnemer9d168222016-08-05 17:44:54 +000012647OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012648 SourceLocation StartLoc,
12649 SourceLocation LParenLoc,
12650 SourceLocation EndLoc) {
12651 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012652 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012653
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012654 // OpenMP [teams Constrcut, Restrictions]
12655 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012656 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000012657 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012658 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012659
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012660 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012661 OpenMPDirectiveKind CaptureRegion =
12662 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12663 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012664 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012665 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012666 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12667 HelperValStmt = buildPreInits(Context, Captures);
12668 }
12669
12670 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12671 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012672}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012673
12674OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12675 SourceLocation StartLoc,
12676 SourceLocation LParenLoc,
12677 SourceLocation EndLoc) {
12678 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012679 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012680
12681 // OpenMP [teams Constrcut, Restrictions]
12682 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012683 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000012684 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012685 return nullptr;
12686
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012687 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012688 OpenMPDirectiveKind CaptureRegion =
12689 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12690 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012691 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012692 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012693 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12694 HelperValStmt = buildPreInits(Context, Captures);
12695 }
12696
12697 return new (Context) OMPThreadLimitClause(
12698 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012699}
Alexey Bataeva0569352015-12-01 10:17:31 +000012700
12701OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12702 SourceLocation StartLoc,
12703 SourceLocation LParenLoc,
12704 SourceLocation EndLoc) {
12705 Expr *ValExpr = Priority;
12706
12707 // OpenMP [2.9.1, task Constrcut]
12708 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012709 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000012710 /*StrictlyPositive=*/false))
12711 return nullptr;
12712
12713 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12714}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012715
12716OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12717 SourceLocation StartLoc,
12718 SourceLocation LParenLoc,
12719 SourceLocation EndLoc) {
12720 Expr *ValExpr = Grainsize;
12721
12722 // OpenMP [2.9.2, taskloop Constrcut]
12723 // The parameter of the grainsize clause must be a positive integer
12724 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012725 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012726 /*StrictlyPositive=*/true))
12727 return nullptr;
12728
12729 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12730}
Alexey Bataev382967a2015-12-08 12:06:20 +000012731
12732OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12733 SourceLocation StartLoc,
12734 SourceLocation LParenLoc,
12735 SourceLocation EndLoc) {
12736 Expr *ValExpr = NumTasks;
12737
12738 // OpenMP [2.9.2, taskloop Constrcut]
12739 // The parameter of the num_tasks clause must be a positive integer
12740 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012741 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000012742 /*StrictlyPositive=*/true))
12743 return nullptr;
12744
12745 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12746}
12747
Alexey Bataev28c75412015-12-15 08:19:24 +000012748OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12749 SourceLocation LParenLoc,
12750 SourceLocation EndLoc) {
12751 // OpenMP [2.13.2, critical construct, Description]
12752 // ... where hint-expression is an integer constant expression that evaluates
12753 // to a valid lock hint.
12754 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12755 if (HintExpr.isInvalid())
12756 return nullptr;
12757 return new (Context)
12758 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12759}
12760
Carlo Bertollib4adf552016-01-15 18:50:31 +000012761OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12762 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12763 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12764 SourceLocation EndLoc) {
12765 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12766 std::string Values;
12767 Values += "'";
12768 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12769 Values += "'";
12770 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12771 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12772 return nullptr;
12773 }
12774 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012775 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012776 if (ChunkSize) {
12777 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12778 !ChunkSize->isInstantiationDependent() &&
12779 !ChunkSize->containsUnexpandedParameterPack()) {
12780 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12781 ExprResult Val =
12782 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12783 if (Val.isInvalid())
12784 return nullptr;
12785
12786 ValExpr = Val.get();
12787
12788 // OpenMP [2.7.1, Restrictions]
12789 // chunk_size must be a loop invariant integer expression with a positive
12790 // value.
12791 llvm::APSInt Result;
12792 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12793 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12794 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12795 << "dist_schedule" << ChunkSize->getSourceRange();
12796 return nullptr;
12797 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012798 } else if (getOpenMPCaptureRegionForClause(
12799 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12800 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012801 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012802 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012803 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012804 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12805 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012806 }
12807 }
12808 }
12809
12810 return new (Context)
12811 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012812 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012813}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012814
12815OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12816 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12817 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12818 SourceLocation KindLoc, SourceLocation EndLoc) {
12819 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012820 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012821 std::string Value;
12822 SourceLocation Loc;
12823 Value += "'";
12824 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12825 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012826 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012827 Loc = MLoc;
12828 } else {
12829 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012830 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012831 Loc = KindLoc;
12832 }
12833 Value += "'";
12834 Diag(Loc, diag::err_omp_unexpected_clause_value)
12835 << Value << getOpenMPClauseName(OMPC_defaultmap);
12836 return nullptr;
12837 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012838 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012839
12840 return new (Context)
12841 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12842}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012843
12844bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12845 DeclContext *CurLexicalContext = getCurLexicalContext();
12846 if (!CurLexicalContext->isFileContext() &&
12847 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012848 !CurLexicalContext->isExternCXXContext() &&
12849 !isa<CXXRecordDecl>(CurLexicalContext) &&
12850 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12851 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12852 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012853 Diag(Loc, diag::err_omp_region_not_file_context);
12854 return false;
12855 }
12856 if (IsInOpenMPDeclareTargetContext) {
12857 Diag(Loc, diag::err_omp_enclosed_declare_target);
12858 return false;
12859 }
12860
12861 IsInOpenMPDeclareTargetContext = true;
12862 return true;
12863}
12864
12865void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12866 assert(IsInOpenMPDeclareTargetContext &&
12867 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012868 IsInOpenMPDeclareTargetContext = false;
12869}
12870
David Majnemer9d168222016-08-05 17:44:54 +000012871void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12872 CXXScopeSpec &ScopeSpec,
12873 const DeclarationNameInfo &Id,
12874 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12875 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012876 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12877 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12878
12879 if (Lookup.isAmbiguous())
12880 return;
12881 Lookup.suppressDiagnostics();
12882
12883 if (!Lookup.isSingleResult()) {
12884 if (TypoCorrection Corrected =
12885 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12886 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12887 CTK_ErrorRecovery)) {
12888 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12889 << Id.getName());
12890 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12891 return;
12892 }
12893
12894 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12895 return;
12896 }
12897
12898 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12899 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12900 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12901 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012902 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012903 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012904 ND->addAttr(A);
12905 if (ASTMutationListener *ML = Context.getASTMutationListener())
12906 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000012907 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012908 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12909 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12910 << Id.getName();
12911 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012912 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012913 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000012914 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012915}
12916
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012917static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12918 Sema &SemaRef, Decl *D) {
12919 if (!D)
12920 return;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012921 const Decl *LD = nullptr;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012922 if (isa<TagDecl>(D)) {
12923 LD = cast<TagDecl>(D)->getDefinition();
12924 } else if (isa<VarDecl>(D)) {
12925 LD = cast<VarDecl>(D)->getDefinition();
12926
12927 // If this is an implicit variable that is legal and we do not need to do
12928 // anything.
12929 if (cast<VarDecl>(D)->isImplicit()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012930 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012931 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12932 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012933 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012934 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012935 return;
12936 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012937 } else if (const auto *F = dyn_cast<FunctionDecl>(D)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012938 const FunctionDecl *FD = nullptr;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012939 if (cast<FunctionDecl>(D)->hasBody(FD)) {
12940 LD = FD;
12941 // If the definition is associated with the current declaration in the
12942 // target region (it can be e.g. a lambda) that is legal and we do not
12943 // need to do anything else.
12944 if (LD == D) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012945 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev8e39c342018-02-16 21:23:23 +000012946 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12947 D->addAttr(A);
12948 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12949 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12950 return;
12951 }
12952 } else if (F->isFunctionTemplateSpecialization() &&
12953 F->getTemplateSpecializationKind() ==
12954 TSK_ImplicitInstantiation) {
12955 // Check if the function is implicitly instantiated from the template
12956 // defined in the declare target region.
12957 const FunctionTemplateDecl *FTD = F->getPrimaryTemplate();
12958 if (FTD && FTD->hasAttr<OMPDeclareTargetDeclAttr>())
12959 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012960 }
12961 }
12962 if (!LD)
12963 LD = D;
12964 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
Alexey Bataevd0df36a2018-04-30 18:28:08 +000012965 ((isa<VarDecl>(LD) && !isa<ParmVarDecl>(LD)) || isa<FunctionDecl>(LD))) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012966 // Outlined declaration is not declared target.
Alexey Bataevdcc815d2018-05-02 17:39:00 +000012967 if (!isa<FunctionDecl>(LD)) {
12968 if (LD->isOutOfLine()) {
12969 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12970 SemaRef.Diag(SL, diag::note_used_here) << SR;
12971 } else {
12972 const DeclContext *DC = LD->getDeclContext();
12973 while (DC &&
12974 (!isa<FunctionDecl>(DC) ||
12975 !cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()))
12976 DC = DC->getParent();
12977 if (DC)
12978 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012979
Alexey Bataevdcc815d2018-05-02 17:39:00 +000012980 // Is not declared in target context.
12981 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12982 SemaRef.Diag(SL, diag::note_used_here) << SR;
12983 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012984 }
12985 // Mark decl as declared target to prevent further diagnostic.
Alexey Bataeve3727102018-04-18 15:57:46 +000012986 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012987 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12988 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012989 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012990 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012991 }
12992}
12993
12994static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12995 Sema &SemaRef, DSAStackTy *Stack,
12996 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012997 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
12998 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
12999 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013000}
13001
Kelvin Li1ce87c72017-12-12 20:08:12 +000013002void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
13003 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013004 if (!D || D->isInvalidDecl())
13005 return;
13006 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
13007 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
13008 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
Alexey Bataeve3727102018-04-18 15:57:46 +000013009 if (auto *VD = dyn_cast<VarDecl>(D)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013010 if (DSAStack->isThreadPrivate(VD)) {
13011 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000013012 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013013 return;
13014 }
13015 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013016 if (auto *VD = dyn_cast<ValueDecl>(D)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013017 // Problem if any with var declared with incomplete type will be reported
13018 // as normal, so no need to check it here.
13019 if ((E || !VD->getType()->isIncompleteType()) &&
13020 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
13021 // Mark decl as declared target to prevent further diagnostic.
Alexey Bataev8e39c342018-02-16 21:23:23 +000013022 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD) ||
13023 isa<FunctionTemplateDecl>(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013024 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013025 Context, OMPDeclareTargetDeclAttr::MT_To);
13026 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013027 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013028 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013029 }
13030 return;
13031 }
13032 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013033 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000013034 if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
13035 (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
13036 OMPDeclareTargetDeclAttr::MT_Link)) {
13037 assert(IdLoc.isValid() && "Source location is expected");
13038 Diag(IdLoc, diag::err_omp_function_in_link_clause);
13039 Diag(FD->getLocation(), diag::note_defined_here) << FD;
13040 return;
13041 }
13042 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013043 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
Alexey Bataev8e39c342018-02-16 21:23:23 +000013044 if (FTD->hasAttr<OMPDeclareTargetDeclAttr>() &&
13045 (FTD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
13046 OMPDeclareTargetDeclAttr::MT_Link)) {
13047 assert(IdLoc.isValid() && "Source location is expected");
13048 Diag(IdLoc, diag::err_omp_function_in_link_clause);
13049 Diag(FTD->getLocation(), diag::note_defined_here) << FTD;
13050 return;
13051 }
13052 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013053 if (!E) {
13054 // Checking declaration inside declare target region.
13055 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
Alexey Bataev8e39c342018-02-16 21:23:23 +000013056 (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13057 isa<FunctionTemplateDecl>(D))) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013058 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013059 Context, OMPDeclareTargetDeclAttr::MT_To);
13060 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013061 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013062 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013063 }
13064 return;
13065 }
13066 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13067}
Samuel Antao661c0902016-05-26 17:39:58 +000013068
13069OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13070 SourceLocation StartLoc,
13071 SourceLocation LParenLoc,
13072 SourceLocation EndLoc) {
13073 MappableVarListInfo MVLI(VarList);
13074 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13075 if (MVLI.ProcessedVarList.empty())
13076 return nullptr;
13077
13078 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13079 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13080 MVLI.VarComponents);
13081}
Samuel Antaoec172c62016-05-26 17:49:04 +000013082
13083OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13084 SourceLocation StartLoc,
13085 SourceLocation LParenLoc,
13086 SourceLocation EndLoc) {
13087 MappableVarListInfo MVLI(VarList);
13088 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13089 if (MVLI.ProcessedVarList.empty())
13090 return nullptr;
13091
13092 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13093 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13094 MVLI.VarComponents);
13095}
Carlo Bertolli2404b172016-07-13 15:37:16 +000013096
13097OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13098 SourceLocation StartLoc,
13099 SourceLocation LParenLoc,
13100 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000013101 MappableVarListInfo MVLI(VarList);
13102 SmallVector<Expr *, 8> PrivateCopies;
13103 SmallVector<Expr *, 8> Inits;
13104
Alexey Bataeve3727102018-04-18 15:57:46 +000013105 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000013106 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13107 SourceLocation ELoc;
13108 SourceRange ERange;
13109 Expr *SimpleRefExpr = RefExpr;
13110 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13111 if (Res.second) {
13112 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000013113 MVLI.ProcessedVarList.push_back(RefExpr);
13114 PrivateCopies.push_back(nullptr);
13115 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013116 }
13117 ValueDecl *D = Res.first;
13118 if (!D)
13119 continue;
13120
13121 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000013122 Type = Type.getNonReferenceType().getUnqualifiedType();
13123
13124 auto *VD = dyn_cast<VarDecl>(D);
13125
13126 // Item should be a pointer or reference to pointer.
13127 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000013128 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13129 << 0 << RefExpr->getSourceRange();
13130 continue;
13131 }
Samuel Antaocc10b852016-07-28 14:23:26 +000013132
13133 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013134 auto VDPrivate =
13135 buildVarDecl(*this, ELoc, Type, D->getName(),
13136 D->hasAttrs() ? &D->getAttrs() : nullptr,
13137 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000013138 if (VDPrivate->isInvalidDecl())
13139 continue;
13140
13141 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013142 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000013143 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13144
13145 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000013146 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000013147 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000013148 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
13149 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000013150 AddInitializerToDecl(VDPrivate,
13151 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013152 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000013153
13154 // If required, build a capture to implement the privatization initialized
13155 // with the current list item value.
13156 DeclRefExpr *Ref = nullptr;
13157 if (!VD)
13158 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13159 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13160 PrivateCopies.push_back(VDPrivateRefExpr);
13161 Inits.push_back(VDInitRefExpr);
13162
13163 // We need to add a data sharing attribute for this variable to make sure it
13164 // is correctly captured. A variable that shows up in a use_device_ptr has
13165 // similar properties of a first private variable.
13166 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13167
13168 // Create a mappable component for the list item. List items in this clause
13169 // only need a component.
13170 MVLI.VarBaseDeclarations.push_back(D);
13171 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13172 MVLI.VarComponents.back().push_back(
13173 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000013174 }
13175
Samuel Antaocc10b852016-07-28 14:23:26 +000013176 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000013177 return nullptr;
13178
Samuel Antaocc10b852016-07-28 14:23:26 +000013179 return OMPUseDevicePtrClause::Create(
13180 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13181 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013182}
Carlo Bertolli70594e92016-07-13 17:16:49 +000013183
13184OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13185 SourceLocation StartLoc,
13186 SourceLocation LParenLoc,
13187 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000013188 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000013189 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000013190 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000013191 SourceLocation ELoc;
13192 SourceRange ERange;
13193 Expr *SimpleRefExpr = RefExpr;
13194 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13195 if (Res.second) {
13196 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000013197 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013198 }
13199 ValueDecl *D = Res.first;
13200 if (!D)
13201 continue;
13202
13203 QualType Type = D->getType();
13204 // item should be a pointer or array or reference to pointer or array
13205 if (!Type.getNonReferenceType()->isPointerType() &&
13206 !Type.getNonReferenceType()->isArrayType()) {
13207 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13208 << 0 << RefExpr->getSourceRange();
13209 continue;
13210 }
Samuel Antao6890b092016-07-28 14:25:09 +000013211
13212 // Check if the declaration in the clause does not show up in any data
13213 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000013214 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000013215 if (isOpenMPPrivate(DVar.CKind)) {
13216 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13217 << getOpenMPClauseName(DVar.CKind)
13218 << getOpenMPClauseName(OMPC_is_device_ptr)
13219 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013220 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000013221 continue;
13222 }
13223
Alexey Bataeve3727102018-04-18 15:57:46 +000013224 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000013225 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013226 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000013227 [&ConflictExpr](
13228 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13229 OpenMPClauseKind) -> bool {
13230 ConflictExpr = R.front().getAssociatedExpression();
13231 return true;
13232 })) {
13233 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13234 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13235 << ConflictExpr->getSourceRange();
13236 continue;
13237 }
13238
13239 // Store the components in the stack so that they can be used to check
13240 // against other clauses later on.
13241 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13242 DSAStack->addMappableExpressionComponents(
13243 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13244
13245 // Record the expression we've just processed.
13246 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13247
13248 // Create a mappable component for the list item. List items in this clause
13249 // only need a component. We use a null declaration to signal fields in
13250 // 'this'.
13251 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13252 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13253 "Unexpected device pointer expression!");
13254 MVLI.VarBaseDeclarations.push_back(
13255 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13256 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13257 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013258 }
13259
Samuel Antao6890b092016-07-28 14:25:09 +000013260 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000013261 return nullptr;
13262
Samuel Antao6890b092016-07-28 14:25:09 +000013263 return OMPIsDevicePtrClause::Create(
13264 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13265 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013266}