blob: 72a7daa919c069133d8e5955efd734459f0ea569 [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 Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Samuel Antaof8b50122015-07-13 22:54:53 +000027#include "clang/Basic/TargetInfo.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "clang/Lex/Preprocessor.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000029#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000030#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000031#include "clang/Sema/Scope.h"
32#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000033#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000034#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000035using namespace clang;
36
Alexey Bataev758e55e2013-09-06 18:03:48 +000037//===----------------------------------------------------------------------===//
38// Stack of data-sharing attributes for variables
39//===----------------------------------------------------------------------===//
40
41namespace {
42/// \brief Default data sharing attributes, which can be applied to directive.
43enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000044 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
45 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
46 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000047};
Alexey Bataev7ff55242014-06-19 09:13:45 +000048
Alexey Bataev758e55e2013-09-06 18:03:48 +000049/// \brief Stack for tracking declarations used in OpenMP directives and
50/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000051class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000052public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000053 struct DSAVarData final {
54 OpenMPDirectiveKind DKind = OMPD_unknown;
55 OpenMPClauseKind CKind = OMPC_unknown;
56 Expr *RefExpr = nullptr;
57 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000058 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000059 DSAVarData() = default;
Alexey Bataevf189cb72017-07-24 14:52:13 +000060 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
61 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
62 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
63 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000064 };
Alexey Bataev8b427062016-05-25 12:36:08 +000065 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
66 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000067
Alexey Bataev758e55e2013-09-06 18:03:48 +000068private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000069 struct DSAInfo final {
70 OpenMPClauseKind Attributes = OMPC_unknown;
71 /// Pointer to a reference expression and a flag which shows that the
72 /// variable is marked as lastprivate(true) or not (false).
73 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
74 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000075 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000076 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
77 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000078 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
79 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000080 /// Struct that associates a component with the clause kind where they are
81 /// found.
82 struct MappedExprComponentTy {
83 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
84 OpenMPClauseKind Kind = OMPC_unknown;
85 };
86 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000087 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000088 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
89 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000090 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
91 DoacrossDependMapTy;
Alexey Bataevfa312f32017-07-21 18:48:21 +000092 struct ReductionData {
Alexey Bataevf87fa882017-07-21 19:26:22 +000093 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
Alexey Bataevfa312f32017-07-21 18:48:21 +000094 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +000095 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +000096 ReductionData() = default;
97 void set(BinaryOperatorKind BO, SourceRange RR) {
98 ReductionRange = RR;
99 ReductionOp = BO;
100 }
101 void set(const Expr *RefExpr, SourceRange RR) {
102 ReductionRange = RR;
103 ReductionOp = RefExpr;
104 }
105 };
106 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000107
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000108 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000109 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000110 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000111 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000112 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000113 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000114 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000115 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000116 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000117 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000118 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000119 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000120 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
121 /// get the data (loop counters etc.) about enclosing loop-based construct.
122 /// This data is required during codegen.
123 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000124 /// \brief first argument (Expr *) contains optional argument of the
125 /// 'ordered' clause, the second one is true if the regions has 'ordered'
126 /// clause, false otherwise.
127 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000128 bool NowaitRegion = false;
129 bool CancelRegion = false;
130 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000131 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000132 /// Reference to the taskgroup task_reduction reference expression.
133 Expr *TaskgroupReductionRef = nullptr;
Alexey Bataeved09d242014-05-28 05:53:51 +0000134 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000135 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000136 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
137 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000138 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000139 };
140
Axel Naumann323862e2016-02-03 10:45:22 +0000141 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000142
143 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000144 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000145 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
146 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000147 /// \brief true, if check for DSA must be from parent directive, false, if
148 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000149 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000150 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000151 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000152 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000153
154 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
155
David Majnemer9d168222016-08-05 17:44:54 +0000156 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000157
158 /// \brief Checks if the variable is a local for OpenMP region.
159 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000160
Alexey Bataev4b465392017-04-26 15:06:24 +0000161 bool isStackEmpty() const {
162 return Stack.empty() ||
163 Stack.back().second != CurrentNonCapturingFunctionScope ||
164 Stack.back().first.empty();
165 }
166
Alexey Bataev758e55e2013-09-06 18:03:48 +0000167public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000168 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000169
Alexey Bataevaac108a2015-06-23 04:51:00 +0000170 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
171 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000172
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000173 bool isForceVarCapturing() const { return ForceCapturing; }
174 void setForceVarCapturing(bool V) { ForceCapturing = V; }
175
Alexey Bataev758e55e2013-09-06 18:03:48 +0000176 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000177 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000178 if (Stack.empty() ||
179 Stack.back().second != CurrentNonCapturingFunctionScope)
180 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
181 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
182 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000183 }
184
185 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000186 assert(!Stack.back().first.empty() &&
187 "Data-sharing attributes stack is empty!");
188 Stack.back().first.pop_back();
189 }
190
191 /// Start new OpenMP region stack in new non-capturing function.
192 void pushFunction() {
193 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
194 assert(!isa<CapturingScopeInfo>(CurFnScope));
195 CurrentNonCapturingFunctionScope = CurFnScope;
196 }
197 /// Pop region stack for non-capturing function.
198 void popFunction(const FunctionScopeInfo *OldFSI) {
199 if (!Stack.empty() && Stack.back().second == OldFSI) {
200 assert(Stack.back().first.empty());
201 Stack.pop_back();
202 }
203 CurrentNonCapturingFunctionScope = nullptr;
204 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
205 if (!isa<CapturingScopeInfo>(FSI)) {
206 CurrentNonCapturingFunctionScope = FSI;
207 break;
208 }
209 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000210 }
211
Alexey Bataev28c75412015-12-15 08:19:24 +0000212 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
213 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
214 }
215 const std::pair<OMPCriticalDirective *, llvm::APSInt>
216 getCriticalWithHint(const DeclarationNameInfo &Name) const {
217 auto I = Criticals.find(Name.getAsString());
218 if (I != Criticals.end())
219 return I->second;
220 return std::make_pair(nullptr, llvm::APSInt());
221 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000222 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000223 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000224 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000225 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000226
Alexey Bataev9c821032015-04-30 04:23:23 +0000227 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000228 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000229 /// \brief Check if the specified variable is a loop control variable for
230 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000231 /// \return The index of the loop control variable in the list of associated
232 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000233 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000234 /// \brief Check if the specified variable is a loop control variable for
235 /// parent region.
236 /// \return The index of the loop control variable in the list of associated
237 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000238 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000239 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
240 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000241 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000242
Alexey Bataev758e55e2013-09-06 18:03:48 +0000243 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000244 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
245 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246
Alexey Bataevfa312f32017-07-21 18:48:21 +0000247 /// Adds additional information for the reduction items with the reduction id
248 /// represented as an operator.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000249 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
250 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000251 /// Adds additional information for the reduction items with the reduction id
252 /// represented as reduction identifier.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000253 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
254 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000255 /// Returns the location and reduction operation from the innermost parent
256 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000257 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000258 BinaryOperatorKind &BOK,
259 Expr *&TaskgroupDescriptor);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000260 /// Returns the location and reduction operation from the innermost parent
261 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000262 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000263 const Expr *&ReductionRef,
264 Expr *&TaskgroupDescriptor);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000265 /// Return reduction reference expression for the current taskgroup.
266 Expr *getTaskgroupReductionRef() const {
267 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
268 "taskgroup reference expression requested for non taskgroup "
269 "directive.");
270 return Stack.back().first.back().TaskgroupReductionRef;
271 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000272 /// Checks if the given \p VD declaration is actually a taskgroup reduction
273 /// descriptor variable at the \p Level of OpenMP regions.
274 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
275 return Stack.back().first[Level].TaskgroupReductionRef &&
276 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
277 ->getDecl() == VD;
278 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000279
Alexey Bataev758e55e2013-09-06 18:03:48 +0000280 /// \brief Returns data sharing attributes from top of the stack for the
281 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000282 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000283 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000284 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000285 /// \brief Checks if the specified variables has data-sharing attributes which
286 /// match specified \a CPred predicate in any directive which matches \a DPred
287 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000288 DSAVarData hasDSA(ValueDecl *D,
289 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
290 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
291 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000292 /// \brief Checks if the specified variables has data-sharing attributes which
293 /// match specified \a CPred predicate in any innermost directive which
294 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000295 DSAVarData
296 hasInnermostDSA(ValueDecl *D,
297 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
298 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
299 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000300 /// \brief Checks if the specified variables has explicit data-sharing
301 /// attributes which match specified \a CPred predicate at the specified
302 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000303 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000304 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000305 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000306
307 /// \brief Returns true if the directive at level \Level matches in the
308 /// specified \a DPred predicate.
309 bool hasExplicitDirective(
310 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
311 unsigned Level);
312
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000313 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000314 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
315 const DeclarationNameInfo &,
316 SourceLocation)> &DPred,
317 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000318
Alexey Bataev758e55e2013-09-06 18:03:48 +0000319 /// \brief Returns currently analyzed directive.
320 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000321 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000322 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000323 /// \brief Returns parent directive.
324 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000325 if (isStackEmpty() || Stack.back().first.size() == 1)
326 return OMPD_unknown;
327 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000328 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000329
330 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000331 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000332 assert(!isStackEmpty());
333 Stack.back().first.back().DefaultAttr = DSA_none;
334 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000335 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000336 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000337 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000338 assert(!isStackEmpty());
339 Stack.back().first.back().DefaultAttr = DSA_shared;
340 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000341 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000342
343 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000344 return isStackEmpty() ? DSA_unspecified
345 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000346 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000347 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000348 return isStackEmpty() ? SourceLocation()
349 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000350 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000351
Alexey Bataevf29276e2014-06-18 04:14:57 +0000352 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000353 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000354 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000355 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000356 }
357
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000358 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000359 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000360 assert(!isStackEmpty());
361 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
362 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000363 }
364 /// \brief Returns true, if parent region is ordered (has associated
365 /// 'ordered' clause), false - otherwise.
366 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000367 if (isStackEmpty() || Stack.back().first.size() == 1)
368 return false;
369 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000370 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000371 /// \brief Returns optional parameter for the ordered region.
372 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000373 if (isStackEmpty() || Stack.back().first.size() == 1)
374 return nullptr;
375 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000376 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000377 /// \brief Marks current region as nowait (it has a 'nowait' clause).
378 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000379 assert(!isStackEmpty());
380 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000381 }
382 /// \brief Returns true, if parent region is nowait (has associated
383 /// 'nowait' clause), false - otherwise.
384 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000385 if (isStackEmpty() || Stack.back().first.size() == 1)
386 return false;
387 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000388 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000389 /// \brief Marks parent region as cancel region.
390 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000391 if (!isStackEmpty() && Stack.back().first.size() > 1) {
392 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
393 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
394 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000395 }
396 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000397 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000398 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000399 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000400
Alexey Bataev9c821032015-04-30 04:23:23 +0000401 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000402 void setAssociatedLoops(unsigned Val) {
403 assert(!isStackEmpty());
404 Stack.back().first.back().AssociatedLoops = Val;
405 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000406 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000407 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000408 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000409 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000410
Alexey Bataev13314bf2014-10-09 04:18:56 +0000411 /// \brief Marks current target region as one with closely nested teams
412 /// region.
413 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000414 if (!isStackEmpty() && Stack.back().first.size() > 1) {
415 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
416 TeamsRegionLoc;
417 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000418 }
419 /// \brief Returns true, if current region has closely nested teams region.
420 bool hasInnerTeamsRegion() const {
421 return getInnerTeamsRegionLoc().isValid();
422 }
423 /// \brief Returns location of the nested teams region (if any).
424 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000425 return isStackEmpty() ? SourceLocation()
426 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000427 }
428
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000429 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000430 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000431 }
432 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000433 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000434 }
435 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000436 return isStackEmpty() ? SourceLocation()
437 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000438 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000439
Samuel Antao4c8035b2016-12-12 18:00:20 +0000440 /// Do the check specified in \a Check to all component lists and return true
441 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000442 bool checkMappableExprComponentListsForDecl(
443 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000444 const llvm::function_ref<
445 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
446 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000447 if (isStackEmpty())
448 return false;
449 auto SI = Stack.back().first.rbegin();
450 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000451
452 if (SI == SE)
453 return false;
454
455 if (CurrentRegionOnly) {
456 SE = std::next(SI);
457 } else {
458 ++SI;
459 }
460
461 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000462 auto MI = SI->MappedExprComponents.find(VD);
463 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000464 for (auto &L : MI->second.Components)
465 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000466 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000467 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000468 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000469 }
470
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000471 /// Do the check specified in \a Check to all component lists at a given level
472 /// and return true if any issue is found.
473 bool checkMappableExprComponentListsForDeclAtLevel(
474 ValueDecl *VD, unsigned Level,
475 const llvm::function_ref<
476 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
477 OpenMPClauseKind)> &Check) {
478 if (isStackEmpty())
479 return false;
480
481 auto StartI = Stack.back().first.begin();
482 auto EndI = Stack.back().first.end();
483 if (std::distance(StartI, EndI) <= (int)Level)
484 return false;
485 std::advance(StartI, Level);
486
487 auto MI = StartI->MappedExprComponents.find(VD);
488 if (MI != StartI->MappedExprComponents.end())
489 for (auto &L : MI->second.Components)
490 if (Check(L, MI->second.Kind))
491 return true;
492 return false;
493 }
494
Samuel Antao4c8035b2016-12-12 18:00:20 +0000495 /// Create a new mappable expression component list associated with a given
496 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000497 void addMappableExpressionComponents(
498 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000499 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
500 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000501 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000502 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000503 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000504 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000505 MEC.Components.resize(MEC.Components.size() + 1);
506 MEC.Components.back().append(Components.begin(), Components.end());
507 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000508 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000509
510 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000511 assert(!isStackEmpty());
512 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000513 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000514 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000515 assert(!isStackEmpty() && Stack.back().first.size() > 1);
516 auto &StackElem = *std::next(Stack.back().first.rbegin());
517 assert(isOpenMPWorksharingDirective(StackElem.Directive));
518 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000519 }
520 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
521 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000522 assert(!isStackEmpty());
523 auto &StackElem = Stack.back().first.back();
524 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
525 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000526 return llvm::make_range(Ref.begin(), Ref.end());
527 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000528 return llvm::make_range(StackElem.DoacrossDepends.end(),
529 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000530 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000531};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000532bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000533 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
534 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000535}
Alexey Bataeved09d242014-05-28 05:53:51 +0000536} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000537
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000538static Expr *getExprAsWritten(Expr *E) {
539 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
540 E = ExprTemp->getSubExpr();
541
542 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
543 E = MTE->GetTemporaryExpr();
544
545 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
546 E = Binder->getSubExpr();
547
548 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
549 E = ICE->getSubExprAsWritten();
550 return E->IgnoreParens();
551}
552
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000554 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
555 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
556 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000557 auto *VD = dyn_cast<VarDecl>(D);
558 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000559 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000560 VD = VD->getCanonicalDecl();
561 D = VD;
562 } else {
563 assert(FD);
564 FD = FD->getCanonicalDecl();
565 D = FD;
566 }
567 return D;
568}
569
David Majnemer9d168222016-08-05 17:44:54 +0000570DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000571 ValueDecl *D) {
572 D = getCanonicalDecl(D);
573 auto *VD = dyn_cast<VarDecl>(D);
574 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000575 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000576 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000577 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
578 // in a region but not in construct]
579 // File-scope or namespace-scope variables referenced in called routines
580 // in the region are shared unless they appear in a threadprivate
581 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000582 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000583 DVar.CKind = OMPC_shared;
584
585 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
586 // in a region but not in construct]
587 // Variables with static storage duration that are declared in called
588 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000589 if (VD && VD->hasGlobalStorage())
590 DVar.CKind = OMPC_shared;
591
592 // Non-static data members are shared by default.
593 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000594 DVar.CKind = OMPC_shared;
595
Alexey Bataev758e55e2013-09-06 18:03:48 +0000596 return DVar;
597 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000598
Alexey Bataevec3da872014-01-31 05:15:34 +0000599 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
600 // in a Construct, C/C++, predetermined, p.1]
601 // Variables with automatic storage duration that are declared in a scope
602 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000603 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
604 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000605 DVar.CKind = OMPC_private;
606 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000607 }
608
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000609 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000610 // Explicitly specified attributes and local variables with predetermined
611 // attributes.
612 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000613 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000614 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000615 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000616 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000617 return DVar;
618 }
619
620 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
621 // in a Construct, C/C++, implicitly determined, p.1]
622 // In a parallel or task construct, the data-sharing attributes of these
623 // variables are determined by the default clause, if present.
624 switch (Iter->DefaultAttr) {
625 case DSA_shared:
626 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000627 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000628 return DVar;
629 case DSA_none:
630 return DVar;
631 case DSA_unspecified:
632 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
633 // in a Construct, implicitly determined, p.2]
634 // In a parallel construct, if no default clause is present, these
635 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000636 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000637 if (isOpenMPParallelDirective(DVar.DKind) ||
638 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000639 DVar.CKind = OMPC_shared;
640 return DVar;
641 }
642
643 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
644 // in a Construct, implicitly determined, p.4]
645 // In a task construct, if no default clause is present, a variable that in
646 // the enclosing context is determined to be shared by all implicit tasks
647 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000648 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000649 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000650 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000651 do {
652 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000653 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000654 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000655 // In a task construct, if no default clause is present, a variable
656 // whose data-sharing attribute is not determined by the rules above is
657 // firstprivate.
658 DVarTemp = getDSA(I, D);
659 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000660 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000661 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000662 return DVar;
663 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000664 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000665 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000666 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 return DVar;
668 }
669 }
670 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
671 // in a Construct, implicitly determined, p.3]
672 // For constructs other than task, if no default clause is present, these
673 // variables inherit their data-sharing attributes from the enclosing
674 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000675 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000676}
677
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000678Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000679 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000680 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000681 auto &StackElem = Stack.back().first.back();
682 auto It = StackElem.AlignedMap.find(D);
683 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000684 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000685 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000686 return nullptr;
687 } else {
688 assert(It->second && "Unexpected nullptr expr in the aligned map");
689 return It->second;
690 }
691 return nullptr;
692}
693
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000694void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000695 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000696 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000697 auto &StackElem = Stack.back().first.back();
698 StackElem.LCVMap.insert(
699 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000700}
701
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000702DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000703 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000704 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000705 auto &StackElem = Stack.back().first.back();
706 auto It = StackElem.LCVMap.find(D);
707 if (It != StackElem.LCVMap.end())
708 return It->second;
709 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000710}
711
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000712DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000713 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
714 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000715 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000716 auto &StackElem = *std::next(Stack.back().first.rbegin());
717 auto It = StackElem.LCVMap.find(D);
718 if (It != StackElem.LCVMap.end())
719 return It->second;
720 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000721}
722
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000723ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000724 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
725 "Data-sharing attributes stack is empty");
726 auto &StackElem = *std::next(Stack.back().first.rbegin());
727 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000728 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000729 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000730 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000731 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000732 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000733}
734
Alexey Bataev90c228f2016-02-08 09:29:13 +0000735void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
736 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000737 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000738 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000739 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000740 Data.Attributes = A;
741 Data.RefExpr.setPointer(E);
742 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000743 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000744 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
745 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000746 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
747 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
748 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
749 (isLoopControlVariable(D).first && A == OMPC_private));
750 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
751 Data.RefExpr.setInt(/*IntVal=*/true);
752 return;
753 }
754 const bool IsLastprivate =
755 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
756 Data.Attributes = A;
757 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
758 Data.PrivateCopy = PrivateCopy;
759 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000760 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000761 Data.Attributes = A;
762 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
763 Data.PrivateCopy = nullptr;
764 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000765 }
766}
767
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000768/// \brief Build a variable declaration for OpenMP loop iteration variable.
769static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
770 StringRef Name, const AttrVec *Attrs = nullptr) {
771 DeclContext *DC = SemaRef.CurContext;
772 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
773 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
774 VarDecl *Decl =
775 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
776 if (Attrs) {
777 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
778 I != E; ++I)
779 Decl->addAttr(*I);
780 }
781 Decl->setImplicit();
782 return Decl;
783}
784
785static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
786 SourceLocation Loc,
787 bool RefersToCapture = false) {
788 D->setReferenced();
789 D->markUsed(S.Context);
790 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
791 SourceLocation(), D, RefersToCapture, Loc, Ty,
792 VK_LValue);
793}
794
795void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
796 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000797 D = getCanonicalDecl(D);
798 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000799 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000800 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000801 "Additional reduction info may be specified only for reduction items.");
802 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
803 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000804 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000805 "Additional reduction info may be specified only once for reduction "
806 "items.");
807 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000808 Expr *&TaskgroupReductionRef =
809 Stack.back().first.back().TaskgroupReductionRef;
810 if (!TaskgroupReductionRef) {
811 auto *VD = buildVarDecl(SemaRef, SourceLocation(),
812 SemaRef.Context.VoidPtrTy, ".task_red.");
813 TaskgroupReductionRef = buildDeclRefExpr(
814 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
815 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000816}
817
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000818void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
819 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000820 D = getCanonicalDecl(D);
821 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000822 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000823 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000824 "Additional reduction info may be specified only for reduction items.");
825 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
826 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000827 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000828 "Additional reduction info may be specified only once for reduction "
829 "items.");
830 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000831 Expr *&TaskgroupReductionRef =
832 Stack.back().first.back().TaskgroupReductionRef;
833 if (!TaskgroupReductionRef) {
834 auto *VD = buildVarDecl(SemaRef, SourceLocation(),
835 SemaRef.Context.VoidPtrTy, ".task_red.");
836 TaskgroupReductionRef = buildDeclRefExpr(
837 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation());
838 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000839}
840
Alexey Bataevf189cb72017-07-24 14:52:13 +0000841DSAStackTy::DSAVarData
842DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000843 BinaryOperatorKind &BOK,
844 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000845 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000846 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
847 if (Stack.back().first.empty())
848 return DSAVarData();
849 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000850 E = Stack.back().first.rend();
851 I != E; std::advance(I, 1)) {
852 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000853 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000854 continue;
855 auto &ReductionData = I->ReductionMap[D];
856 if (!ReductionData.ReductionOp ||
857 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000858 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000859 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000860 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000861 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
862 "expression for the descriptor is not "
863 "set.");
864 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000865 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
866 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000867 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000868 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000869}
870
Alexey Bataevf189cb72017-07-24 14:52:13 +0000871DSAStackTy::DSAVarData
872DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000873 const Expr *&ReductionRef,
874 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000875 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000876 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
877 if (Stack.back().first.empty())
878 return DSAVarData();
879 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000880 E = Stack.back().first.rend();
881 I != E; std::advance(I, 1)) {
882 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000883 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000884 continue;
885 auto &ReductionData = I->ReductionMap[D];
886 if (!ReductionData.ReductionOp ||
887 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000888 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000889 SR = ReductionData.ReductionRange;
890 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000891 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
892 "expression for the descriptor is not "
893 "set.");
894 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000895 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
896 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000897 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000898 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000899}
900
Alexey Bataeved09d242014-05-28 05:53:51 +0000901bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000902 D = D->getCanonicalDecl();
Alexey Bataev4b465392017-04-26 15:06:24 +0000903 if (!isStackEmpty() && Stack.back().first.size() > 1) {
904 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000905 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000906 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000907 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000908 if (I == E)
909 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000910 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000911 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000912 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000913 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000914 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000915 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000916 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000917}
918
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000919DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
920 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000921 DSAVarData DVar;
922
923 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
924 // in a Construct, C/C++, predetermined, p.1]
925 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000926 auto *VD = dyn_cast<VarDecl>(D);
927 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
928 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000929 SemaRef.getLangOpts().OpenMPUseTLS &&
930 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000931 (VD && VD->getStorageClass() == SC_Register &&
932 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
933 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000934 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000935 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000936 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000937 auto TI = Threadprivates.find(D);
938 if (TI != Threadprivates.end()) {
939 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000940 DVar.CKind = OMPC_threadprivate;
941 return DVar;
942 }
943
Alexey Bataev4b465392017-04-26 15:06:24 +0000944 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000945 // Not in OpenMP execution region and top scope was already checked.
946 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000947
Alexey Bataev758e55e2013-09-06 18:03:48 +0000948 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000949 // in a Construct, C/C++, predetermined, p.4]
950 // Static data members are shared.
951 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
952 // in a Construct, C/C++, predetermined, p.7]
953 // Variables with static storage duration that are declared in a scope
954 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000955 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000956 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000957 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000958 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000959 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000960
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000961 DVar.CKind = OMPC_shared;
962 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000963 }
964
965 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000966 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
967 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000968 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
969 // in a Construct, C/C++, predetermined, p.6]
970 // Variables with const qualified type having no mutable member are
971 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000972 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000973 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000974 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
975 if (auto *CTD = CTSD->getSpecializedTemplate())
976 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000977 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000978 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
979 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000980 // Variables with const-qualified type having no mutable member may be
981 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000982 DSAVarData DVarTemp = hasDSA(
983 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
984 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000985 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
986 return DVar;
987
Alexey Bataev758e55e2013-09-06 18:03:48 +0000988 DVar.CKind = OMPC_shared;
989 return DVar;
990 }
991
Alexey Bataev758e55e2013-09-06 18:03:48 +0000992 // Explicitly specified attributes and local variables with predetermined
993 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000994 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +0000995 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000996 if (FromParent && I != EndI)
997 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000998 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000999 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001000 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001001 DVar.CKind = I->SharingMap[D].Attributes;
1002 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001003 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001004 }
1005
1006 return DVar;
1007}
1008
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001009DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1010 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001011 if (isStackEmpty()) {
1012 StackTy::reverse_iterator I;
1013 return getDSA(I, D);
1014 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001016 auto StartI = Stack.back().first.rbegin();
1017 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001018 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001019 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001020 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001021}
1022
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001023DSAStackTy::DSAVarData
1024DSAStackTy::hasDSA(ValueDecl *D,
1025 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1026 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1027 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001028 if (isStackEmpty())
1029 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001030 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001031 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001032 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001033 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001034 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001035 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001036 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001037 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001038 auto NewI = I;
1039 DSAVarData DVar = getDSA(NewI, D);
1040 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001041 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001042 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001043 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001044}
1045
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001046DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1047 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1048 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1049 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001050 if (isStackEmpty())
1051 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001052 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001053 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001054 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001055 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001056 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001057 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001058 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001059 auto NewI = StartI;
1060 DSAVarData DVar = getDSA(NewI, D);
1061 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001062}
1063
Alexey Bataevaac108a2015-06-23 04:51:00 +00001064bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001065 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001066 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001067 if (CPred(ClauseKindMode))
1068 return true;
Alexey Bataev4b465392017-04-26 15:06:24 +00001069 if (isStackEmpty())
1070 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001071 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001072 auto StartI = Stack.back().first.begin();
1073 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001074 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001075 return false;
1076 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001077 return (StartI->SharingMap.count(D) > 0) &&
1078 StartI->SharingMap[D].RefExpr.getPointer() &&
1079 CPred(StartI->SharingMap[D].Attributes) &&
1080 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001081}
1082
Samuel Antao4be30e92015-10-02 17:14:03 +00001083bool DSAStackTy::hasExplicitDirective(
1084 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1085 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001086 if (isStackEmpty())
1087 return false;
1088 auto StartI = Stack.back().first.begin();
1089 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001090 if (std::distance(StartI, EndI) <= (int)Level)
1091 return false;
1092 std::advance(StartI, Level);
1093 return DPred(StartI->Directive);
1094}
1095
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001096bool DSAStackTy::hasDirective(
1097 const llvm::function_ref<bool(OpenMPDirectiveKind,
1098 const DeclarationNameInfo &, SourceLocation)>
1099 &DPred,
1100 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001101 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001102 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001103 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001104 auto StartI = std::next(Stack.back().first.rbegin());
1105 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001106 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001107 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001108 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1109 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1110 return true;
1111 }
1112 return false;
1113}
1114
Alexey Bataev758e55e2013-09-06 18:03:48 +00001115void Sema::InitDataSharingAttributesStack() {
1116 VarDataSharingAttributesStack = new DSAStackTy(*this);
1117}
1118
1119#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1120
Alexey Bataev4b465392017-04-26 15:06:24 +00001121void Sema::pushOpenMPFunctionRegion() {
1122 DSAStack->pushFunction();
1123}
1124
1125void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1126 DSAStack->popFunction(OldFSI);
1127}
1128
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001129bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001130 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1131
1132 auto &Ctx = getASTContext();
1133 bool IsByRef = true;
1134
1135 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001136 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001137
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001138 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001139 // This table summarizes how a given variable should be passed to the device
1140 // given its type and the clauses where it appears. This table is based on
1141 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1142 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1143 //
1144 // =========================================================================
1145 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1146 // | |(tofrom:scalar)| | pvt | | | |
1147 // =========================================================================
1148 // | scl | | | | - | | bycopy|
1149 // | scl | | - | x | - | - | bycopy|
1150 // | scl | | x | - | - | - | null |
1151 // | scl | x | | | - | | byref |
1152 // | scl | x | - | x | - | - | bycopy|
1153 // | scl | x | x | - | - | - | null |
1154 // | scl | | - | - | - | x | byref |
1155 // | scl | x | - | - | - | x | byref |
1156 //
1157 // | agg | n.a. | | | - | | byref |
1158 // | agg | n.a. | - | x | - | - | byref |
1159 // | agg | n.a. | x | - | - | - | null |
1160 // | agg | n.a. | - | - | - | x | byref |
1161 // | agg | n.a. | - | - | - | x[] | byref |
1162 //
1163 // | ptr | n.a. | | | - | | bycopy|
1164 // | ptr | n.a. | - | x | - | - | bycopy|
1165 // | ptr | n.a. | x | - | - | - | null |
1166 // | ptr | n.a. | - | - | - | x | byref |
1167 // | ptr | n.a. | - | - | - | x[] | bycopy|
1168 // | ptr | n.a. | - | - | x | | bycopy|
1169 // | ptr | n.a. | - | - | x | x | bycopy|
1170 // | ptr | n.a. | - | - | x | x[] | bycopy|
1171 // =========================================================================
1172 // Legend:
1173 // scl - scalar
1174 // ptr - pointer
1175 // agg - aggregate
1176 // x - applies
1177 // - - invalid in this combination
1178 // [] - mapped with an array section
1179 // byref - should be mapped by reference
1180 // byval - should be mapped by value
1181 // null - initialize a local variable to null on the device
1182 //
1183 // Observations:
1184 // - All scalar declarations that show up in a map clause have to be passed
1185 // by reference, because they may have been mapped in the enclosing data
1186 // environment.
1187 // - If the scalar value does not fit the size of uintptr, it has to be
1188 // passed by reference, regardless the result in the table above.
1189 // - For pointers mapped by value that have either an implicit map or an
1190 // array section, the runtime library may pass the NULL value to the
1191 // device instead of the value passed to it by the compiler.
1192
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001193 if (Ty->isReferenceType())
1194 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001195
1196 // Locate map clauses and see if the variable being captured is referred to
1197 // in any of those clauses. Here we only care about variables, not fields,
1198 // because fields are part of aggregates.
1199 bool IsVariableUsedInMapClause = false;
1200 bool IsVariableAssociatedWithSection = false;
1201
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001202 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1203 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001204 MapExprComponents,
1205 OpenMPClauseKind WhereFoundClauseKind) {
1206 // Only the map clause information influences how a variable is
1207 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001208 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001209 if (WhereFoundClauseKind != OMPC_map)
1210 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001211
1212 auto EI = MapExprComponents.rbegin();
1213 auto EE = MapExprComponents.rend();
1214
1215 assert(EI != EE && "Invalid map expression!");
1216
1217 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1218 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1219
1220 ++EI;
1221 if (EI == EE)
1222 return false;
1223
1224 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1225 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1226 isa<MemberExpr>(EI->getAssociatedExpression())) {
1227 IsVariableAssociatedWithSection = true;
1228 // There is nothing more we need to know about this variable.
1229 return true;
1230 }
1231
1232 // Keep looking for more map info.
1233 return false;
1234 });
1235
1236 if (IsVariableUsedInMapClause) {
1237 // If variable is identified in a map clause it is always captured by
1238 // reference except if it is a pointer that is dereferenced somehow.
1239 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1240 } else {
1241 // By default, all the data that has a scalar type is mapped by copy.
1242 IsByRef = !Ty->isScalarType();
1243 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001244 }
1245
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001246 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1247 IsByRef = !DSAStack->hasExplicitDSA(
1248 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1249 Level, /*NotLastprivate=*/true);
1250 }
1251
Samuel Antao86ace552016-04-27 22:40:57 +00001252 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001253 // and alignment, because the runtime library only deals with uintptr types.
1254 // If it does not fit the uintptr size, we need to pass the data by reference
1255 // instead.
1256 if (!IsByRef &&
1257 (Ctx.getTypeSizeInChars(Ty) >
1258 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001259 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001260 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001261 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001262
1263 return IsByRef;
1264}
1265
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001266unsigned Sema::getOpenMPNestingLevel() const {
1267 assert(getLangOpts().OpenMP);
1268 return DSAStack->getNestingLevel();
1269}
1270
Alexey Bataev90c228f2016-02-08 09:29:13 +00001271VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001272 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001273 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001274
1275 // If we are attempting to capture a global variable in a directive with
1276 // 'target' we return true so that this global is also mapped to the device.
1277 //
1278 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1279 // then it should not be captured. Therefore, an extra check has to be
1280 // inserted here once support for 'declare target' is added.
1281 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001282 auto *VD = dyn_cast<VarDecl>(D);
1283 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001284 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001285 !DSAStack->isClauseParsingMode())
1286 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001287 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001288 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1289 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001290 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001291 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001292 false))
1293 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001294 }
1295
Alexey Bataev48977c32015-08-04 08:10:48 +00001296 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1297 (!DSAStack->isClauseParsingMode() ||
1298 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001299 auto &&Info = DSAStack->isLoopControlVariable(D);
1300 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001301 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001302 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001303 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001304 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001305 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001306 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001307 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001308 DVarPrivate = DSAStack->hasDSA(
1309 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1310 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001311 if (DVarPrivate.CKind != OMPC_unknown)
1312 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001313 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001314 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001315}
1316
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001317bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001318 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1319 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001320 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1321 Level) ||
1322 // Consider taskgroup reduction descriptor variable a private to avoid
1323 // possible capture in the region.
1324 (DSAStack->hasExplicitDirective(
1325 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1326 Level) &&
1327 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001328}
1329
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001330bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001331 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1332 // Return true if the current level is no longer enclosed in a target region.
1333
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001334 auto *VD = dyn_cast<VarDecl>(D);
1335 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001336 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1337 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001338}
1339
Alexey Bataeved09d242014-05-28 05:53:51 +00001340void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001341
1342void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1343 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001344 Scope *CurScope, SourceLocation Loc) {
1345 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001346 PushExpressionEvaluationContext(
1347 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001348}
1349
Alexey Bataevaac108a2015-06-23 04:51:00 +00001350void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1351 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001352}
1353
Alexey Bataevaac108a2015-06-23 04:51:00 +00001354void Sema::EndOpenMPClause() {
1355 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001356}
1357
Alexey Bataev758e55e2013-09-06 18:03:48 +00001358void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001359 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1360 // A variable of class type (or array thereof) that appears in a lastprivate
1361 // clause requires an accessible, unambiguous default constructor for the
1362 // class type, unless the list item is also specified in a firstprivate
1363 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001364 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001365 for (auto *C : D->clauses()) {
1366 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1367 SmallVector<Expr *, 8> PrivateCopies;
1368 for (auto *DE : Clause->varlists()) {
1369 if (DE->isValueDependent() || DE->isTypeDependent()) {
1370 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001371 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001372 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001373 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001374 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1375 QualType Type = VD->getType().getNonReferenceType();
1376 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001377 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001378 // Generate helper private variable and initialize it with the
1379 // default value. The address of the original variable is replaced
1380 // by the address of the new private variable in CodeGen. This new
1381 // variable is not added to IdResolver, so the code in the OpenMP
1382 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001383 auto *VDPrivate = buildVarDecl(
1384 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001385 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001386 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001387 if (VDPrivate->isInvalidDecl())
1388 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001389 PrivateCopies.push_back(buildDeclRefExpr(
1390 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001391 } else {
1392 // The variable is also a firstprivate, so initialization sequence
1393 // for private copy is generated already.
1394 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001395 }
1396 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001397 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001398 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001399 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001400 }
1401 }
1402 }
1403
Alexey Bataev758e55e2013-09-06 18:03:48 +00001404 DSAStack->pop();
1405 DiscardCleanupsInEvaluationContext();
1406 PopExpressionEvaluationContext();
1407}
1408
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001409static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1410 Expr *NumIterations, Sema &SemaRef,
1411 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001412
Alexey Bataeva769e072013-03-22 06:34:35 +00001413namespace {
1414
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001415class VarDeclFilterCCC : public CorrectionCandidateCallback {
1416private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001417 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001418
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001419public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001420 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001421 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001422 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001423 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001424 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1426 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001427 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001428 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001429 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001430};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001431
1432class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1433private:
1434 Sema &SemaRef;
1435
1436public:
1437 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1438 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1439 NamedDecl *ND = Candidate.getCorrectionDecl();
1440 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1441 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1442 SemaRef.getCurScope());
1443 }
1444 return false;
1445 }
1446};
1447
Alexey Bataeved09d242014-05-28 05:53:51 +00001448} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001449
1450ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1451 CXXScopeSpec &ScopeSpec,
1452 const DeclarationNameInfo &Id) {
1453 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1454 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1455
1456 if (Lookup.isAmbiguous())
1457 return ExprError();
1458
1459 VarDecl *VD;
1460 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001461 if (TypoCorrection Corrected = CorrectTypo(
1462 Id, LookupOrdinaryName, CurScope, nullptr,
1463 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001464 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001465 PDiag(Lookup.empty()
1466 ? diag::err_undeclared_var_use_suggest
1467 : diag::err_omp_expected_var_arg_suggest)
1468 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001469 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001470 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001471 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1472 : diag::err_omp_expected_var_arg)
1473 << Id.getName();
1474 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001475 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001476 } else {
1477 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001478 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001479 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1480 return ExprError();
1481 }
1482 }
1483 Lookup.suppressDiagnostics();
1484
1485 // OpenMP [2.9.2, Syntax, C/C++]
1486 // Variables must be file-scope, namespace-scope, or static block-scope.
1487 if (!VD->hasGlobalStorage()) {
1488 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001489 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1490 bool IsDecl =
1491 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001492 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001493 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1494 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001495 return ExprError();
1496 }
1497
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001498 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1499 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001500 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1501 // A threadprivate directive for file-scope variables must appear outside
1502 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001503 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1504 !getCurLexicalContext()->isTranslationUnit()) {
1505 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001506 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1507 bool IsDecl =
1508 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1509 Diag(VD->getLocation(),
1510 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1511 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001512 return ExprError();
1513 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001514 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1515 // A threadprivate directive for static class member variables must appear
1516 // in the class definition, in the same scope in which the member
1517 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001518 if (CanonicalVD->isStaticDataMember() &&
1519 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1520 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001521 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1522 bool IsDecl =
1523 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1524 Diag(VD->getLocation(),
1525 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1526 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001527 return ExprError();
1528 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001529 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1530 // A threadprivate directive for namespace-scope variables must appear
1531 // outside any definition or declaration other than the namespace
1532 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001533 if (CanonicalVD->getDeclContext()->isNamespace() &&
1534 (!getCurLexicalContext()->isFileContext() ||
1535 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1536 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001537 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1538 bool IsDecl =
1539 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1540 Diag(VD->getLocation(),
1541 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1542 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001543 return ExprError();
1544 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001545 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1546 // A threadprivate directive for static block-scope variables must appear
1547 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001548 if (CanonicalVD->isStaticLocal() && CurScope &&
1549 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001550 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001551 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1552 bool IsDecl =
1553 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1554 Diag(VD->getLocation(),
1555 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1556 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001557 return ExprError();
1558 }
1559
1560 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1561 // A threadprivate directive must lexically precede all references to any
1562 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001563 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001564 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001565 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001566 return ExprError();
1567 }
1568
1569 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001570 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1571 SourceLocation(), VD,
1572 /*RefersToEnclosingVariableOrCapture=*/false,
1573 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001574}
1575
Alexey Bataeved09d242014-05-28 05:53:51 +00001576Sema::DeclGroupPtrTy
1577Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1578 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001579 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001580 CurContext->addDecl(D);
1581 return DeclGroupPtrTy::make(DeclGroupRef(D));
1582 }
David Blaikie0403cb12016-01-15 23:43:25 +00001583 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001584}
1585
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001586namespace {
1587class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1588 Sema &SemaRef;
1589
1590public:
1591 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001592 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001593 if (VD->hasLocalStorage()) {
1594 SemaRef.Diag(E->getLocStart(),
1595 diag::err_omp_local_var_in_threadprivate_init)
1596 << E->getSourceRange();
1597 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1598 << VD << VD->getSourceRange();
1599 return true;
1600 }
1601 }
1602 return false;
1603 }
1604 bool VisitStmt(const Stmt *S) {
1605 for (auto Child : S->children()) {
1606 if (Child && Visit(Child))
1607 return true;
1608 }
1609 return false;
1610 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001611 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001612};
1613} // namespace
1614
Alexey Bataeved09d242014-05-28 05:53:51 +00001615OMPThreadPrivateDecl *
1616Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001617 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001618 for (auto &RefExpr : VarList) {
1619 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001620 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1621 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001622
Alexey Bataev376b4a42016-02-09 09:41:09 +00001623 // Mark variable as used.
1624 VD->setReferenced();
1625 VD->markUsed(Context);
1626
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001627 QualType QType = VD->getType();
1628 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1629 // It will be analyzed later.
1630 Vars.push_back(DE);
1631 continue;
1632 }
1633
Alexey Bataeva769e072013-03-22 06:34:35 +00001634 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1635 // A threadprivate variable must not have an incomplete type.
1636 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001637 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001638 continue;
1639 }
1640
1641 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1642 // A threadprivate variable must not have a reference type.
1643 if (VD->getType()->isReferenceType()) {
1644 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001645 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1646 bool IsDecl =
1647 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1648 Diag(VD->getLocation(),
1649 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1650 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001651 continue;
1652 }
1653
Samuel Antaof8b50122015-07-13 22:54:53 +00001654 // Check if this is a TLS variable. If TLS is not being supported, produce
1655 // the corresponding diagnostic.
1656 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1657 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1658 getLangOpts().OpenMPUseTLS &&
1659 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001660 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1661 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001662 Diag(ILoc, diag::err_omp_var_thread_local)
1663 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001664 bool IsDecl =
1665 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1666 Diag(VD->getLocation(),
1667 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1668 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001669 continue;
1670 }
1671
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001672 // Check if initial value of threadprivate variable reference variable with
1673 // local storage (it is not supported by runtime).
1674 if (auto Init = VD->getAnyInitializer()) {
1675 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001676 if (Checker.Visit(Init))
1677 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001678 }
1679
Alexey Bataeved09d242014-05-28 05:53:51 +00001680 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001681 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001682 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1683 Context, SourceRange(Loc, Loc)));
1684 if (auto *ML = Context.getASTMutationListener())
1685 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001686 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001687 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001688 if (!Vars.empty()) {
1689 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1690 Vars);
1691 D->setAccess(AS_public);
1692 }
1693 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001694}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001695
Alexey Bataev7ff55242014-06-19 09:13:45 +00001696static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001697 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001698 bool IsLoopIterVar = false) {
1699 if (DVar.RefExpr) {
1700 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1701 << getOpenMPClauseName(DVar.CKind);
1702 return;
1703 }
1704 enum {
1705 PDSA_StaticMemberShared,
1706 PDSA_StaticLocalVarShared,
1707 PDSA_LoopIterVarPrivate,
1708 PDSA_LoopIterVarLinear,
1709 PDSA_LoopIterVarLastprivate,
1710 PDSA_ConstVarShared,
1711 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001712 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001713 PDSA_LocalVarPrivate,
1714 PDSA_Implicit
1715 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001716 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001717 auto ReportLoc = D->getLocation();
1718 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001719 if (IsLoopIterVar) {
1720 if (DVar.CKind == OMPC_private)
1721 Reason = PDSA_LoopIterVarPrivate;
1722 else if (DVar.CKind == OMPC_lastprivate)
1723 Reason = PDSA_LoopIterVarLastprivate;
1724 else
1725 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001726 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1727 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001728 Reason = PDSA_TaskVarFirstprivate;
1729 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001730 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001731 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001732 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001733 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001734 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001735 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001736 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001737 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001738 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001739 ReportHint = true;
1740 Reason = PDSA_LocalVarPrivate;
1741 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001742 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001743 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001744 << Reason << ReportHint
1745 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1746 } else if (DVar.ImplicitDSALoc.isValid()) {
1747 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1748 << getOpenMPClauseName(DVar.CKind);
1749 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001750}
1751
Alexey Bataev758e55e2013-09-06 18:03:48 +00001752namespace {
1753class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1754 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001755 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001756 bool ErrorFound;
1757 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001758 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001759 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001760
Alexey Bataev758e55e2013-09-06 18:03:48 +00001761public:
1762 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001763 if (E->isTypeDependent() || E->isValueDependent() ||
1764 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1765 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001766 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001767 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001768 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1769 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001770
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001771 auto DVar = Stack->getTopDSA(VD, false);
1772 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001773 if (DVar.RefExpr)
1774 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001775
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001776 auto ELoc = E->getExprLoc();
1777 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001778 // The default(none) clause requires that each variable that is referenced
1779 // in the construct, and does not have a predetermined data-sharing
1780 // attribute, must have its data-sharing attribute explicitly determined
1781 // by being listed in a data-sharing attribute clause.
1782 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001783 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001784 VarsWithInheritedDSA.count(VD) == 0) {
1785 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001786 return;
1787 }
1788
1789 // OpenMP [2.9.3.6, Restrictions, p.2]
1790 // A list item that appears in a reduction clause of the innermost
1791 // enclosing worksharing or parallel construct may not be accessed in an
1792 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001793 DVar = Stack->hasInnermostDSA(
1794 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1795 [](OpenMPDirectiveKind K) -> bool {
1796 return isOpenMPParallelDirective(K) ||
1797 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1798 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001799 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001800 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001801 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001802 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1803 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001804 return;
1805 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001806
1807 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001808 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001809 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1810 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001811 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001812 }
1813 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001814 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001815 if (E->isTypeDependent() || E->isValueDependent() ||
1816 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1817 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001818 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1819 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1820 auto DVar = Stack->getTopDSA(FD, false);
1821 // Check if the variable has explicit DSA set and stop analysis if it
1822 // so.
1823 if (DVar.RefExpr)
1824 return;
1825
1826 auto ELoc = E->getExprLoc();
1827 auto DKind = Stack->getCurrentDirective();
1828 // OpenMP [2.9.3.6, Restrictions, p.2]
1829 // A list item that appears in a reduction clause of the innermost
1830 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001831 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001832 DVar = Stack->hasInnermostDSA(
1833 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1834 [](OpenMPDirectiveKind K) -> bool {
1835 return isOpenMPParallelDirective(K) ||
1836 isOpenMPWorksharingDirective(K) ||
1837 isOpenMPTeamsDirective(K);
1838 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001839 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001840 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001841 ErrorFound = true;
1842 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1843 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1844 return;
1845 }
1846
1847 // Define implicit data-sharing attributes for task.
1848 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001849 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1850 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001851 ImplicitFirstprivate.push_back(E);
1852 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001853 } else
1854 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001855 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001856 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001857 for (auto *C : S->clauses()) {
1858 // Skip analysis of arguments of implicitly defined firstprivate clause
1859 // for task directives.
1860 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1861 for (auto *CC : C->children()) {
1862 if (CC)
1863 Visit(CC);
1864 }
1865 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001866 }
1867 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001868 for (auto *C : S->children()) {
1869 if (C && !isa<OMPExecutableDirective>(C))
1870 Visit(C);
1871 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001872 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001873
1874 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001875 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001876 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001877 return VarsWithInheritedDSA;
1878 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001879
Alexey Bataev7ff55242014-06-19 09:13:45 +00001880 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1881 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001882};
Alexey Bataeved09d242014-05-28 05:53:51 +00001883} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001884
Alexey Bataevbae9a792014-06-27 10:37:06 +00001885void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001886 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001887 case OMPD_parallel:
1888 case OMPD_parallel_for:
1889 case OMPD_parallel_for_simd:
1890 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001891 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001892 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001893 QualType KmpInt32PtrTy =
1894 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001895 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001896 std::make_pair(".global_tid.", KmpInt32PtrTy),
1897 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1898 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001899 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001900 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1901 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001902 break;
1903 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001904 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001905 case OMPD_target_parallel: {
1906 Sema::CapturedParamNameType ParamsTarget[] = {
1907 std::make_pair(StringRef(), QualType()) // __context with shared vars
1908 };
1909 // Start a captured region for 'target' with no implicit parameters.
1910 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1911 ParamsTarget);
1912 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1913 QualType KmpInt32PtrTy =
1914 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001915 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001916 std::make_pair(".global_tid.", KmpInt32PtrTy),
1917 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1918 std::make_pair(StringRef(), QualType()) // __context with shared vars
1919 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001920 // Start a captured region for 'teams' or 'parallel'. Both regions have
1921 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001922 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001923 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001924 break;
1925 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001926 case OMPD_simd:
1927 case OMPD_for:
1928 case OMPD_for_simd:
1929 case OMPD_sections:
1930 case OMPD_section:
1931 case OMPD_single:
1932 case OMPD_master:
1933 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001934 case OMPD_taskgroup:
1935 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001936 case OMPD_ordered:
1937 case OMPD_atomic:
1938 case OMPD_target_data:
1939 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001940 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001941 case OMPD_target_parallel_for_simd:
1942 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001943 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001944 std::make_pair(StringRef(), QualType()) // __context with shared vars
1945 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001946 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1947 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001948 break;
1949 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001950 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001951 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001952 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1953 FunctionProtoType::ExtProtoInfo EPI;
1954 EPI.Variadic = true;
1955 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001956 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001957 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001958 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1959 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1960 std::make_pair(".copy_fn.",
1961 Context.getPointerType(CopyFnType).withConst()),
1962 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001963 std::make_pair(StringRef(), QualType()) // __context with shared vars
1964 };
1965 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1966 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001967 // Mark this captured region as inlined, because we don't use outlined
1968 // function directly.
1969 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1970 AlwaysInlineAttr::CreateImplicit(
1971 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001972 break;
1973 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001974 case OMPD_taskloop:
1975 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001976 QualType KmpInt32Ty =
1977 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1978 QualType KmpUInt64Ty =
1979 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1980 QualType KmpInt64Ty =
1981 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1982 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1983 FunctionProtoType::ExtProtoInfo EPI;
1984 EPI.Variadic = true;
1985 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001986 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001987 std::make_pair(".global_tid.", KmpInt32Ty),
1988 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1989 std::make_pair(".privates.",
1990 Context.VoidPtrTy.withConst().withRestrict()),
1991 std::make_pair(
1992 ".copy_fn.",
1993 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1994 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1995 std::make_pair(".lb.", KmpUInt64Ty),
1996 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1997 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001998 std::make_pair(".reductions.",
1999 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002000 std::make_pair(StringRef(), QualType()) // __context with shared vars
2001 };
2002 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2003 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002004 // Mark this captured region as inlined, because we don't use outlined
2005 // function directly.
2006 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2007 AlwaysInlineAttr::CreateImplicit(
2008 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002009 break;
2010 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002011 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00002012 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00002013 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00002014 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00002015 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00002016 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00002017 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00002018 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00002019 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00002020 case OMPD_target_teams_distribute_parallel_for_simd:
2021 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002022 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2023 QualType KmpInt32PtrTy =
2024 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2025 Sema::CapturedParamNameType Params[] = {
2026 std::make_pair(".global_tid.", KmpInt32PtrTy),
2027 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2028 std::make_pair(".previous.lb.", Context.getSizeType()),
2029 std::make_pair(".previous.ub.", Context.getSizeType()),
2030 std::make_pair(StringRef(), QualType()) // __context with shared vars
2031 };
2032 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2033 Params);
2034 break;
2035 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002036 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002037 case OMPD_taskyield:
2038 case OMPD_barrier:
2039 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002040 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002041 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002042 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00002043 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00002044 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002045 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002046 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002047 case OMPD_declare_target:
2048 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00002049 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00002050 llvm_unreachable("OpenMP Directive is not allowed");
2051 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002052 llvm_unreachable("Unknown OpenMP directive");
2053 }
2054}
2055
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002056int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2057 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2058 getOpenMPCaptureRegions(CaptureRegions, DKind);
2059 return CaptureRegions.size();
2060}
2061
Alexey Bataev3392d762016-02-16 11:18:12 +00002062static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002063 Expr *CaptureExpr, bool WithInit,
2064 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002065 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002066 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002067 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002068 QualType Ty = Init->getType();
2069 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2070 if (S.getLangOpts().CPlusPlus)
2071 Ty = C.getLValueReferenceType(Ty);
2072 else {
2073 Ty = C.getPointerType(Ty);
2074 ExprResult Res =
2075 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2076 if (!Res.isUsable())
2077 return nullptr;
2078 Init = Res.get();
2079 }
Alexey Bataev61205072016-03-02 04:57:40 +00002080 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002081 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002082 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2083 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002084 if (!WithInit)
2085 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002086 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002087 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002088 return CED;
2089}
2090
Alexey Bataev61205072016-03-02 04:57:40 +00002091static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2092 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002093 OMPCapturedExprDecl *CD;
2094 if (auto *VD = S.IsOpenMPCapturedDecl(D))
2095 CD = cast<OMPCapturedExprDecl>(VD);
2096 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002097 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2098 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002099 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002100 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002101}
2102
Alexey Bataev5a3af132016-03-29 08:58:54 +00002103static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2104 if (!Ref) {
2105 auto *CD =
2106 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
2107 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
2108 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2109 CaptureExpr->getExprLoc());
2110 }
2111 ExprResult Res = Ref;
2112 if (!S.getLangOpts().CPlusPlus &&
2113 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2114 Ref->getType()->isPointerType())
2115 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2116 if (!Res.isUsable())
2117 return ExprError();
2118 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002119}
2120
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002121namespace {
2122// OpenMP directives parsed in this section are represented as a
2123// CapturedStatement with an associated statement. If a syntax error
2124// is detected during the parsing of the associated statement, the
2125// compiler must abort processing and close the CapturedStatement.
2126//
2127// Combined directives such as 'target parallel' have more than one
2128// nested CapturedStatements. This RAII ensures that we unwind out
2129// of all the nested CapturedStatements when an error is found.
2130class CaptureRegionUnwinderRAII {
2131private:
2132 Sema &S;
2133 bool &ErrorFound;
2134 OpenMPDirectiveKind DKind;
2135
2136public:
2137 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2138 OpenMPDirectiveKind DKind)
2139 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2140 ~CaptureRegionUnwinderRAII() {
2141 if (ErrorFound) {
2142 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2143 while (--ThisCaptureLevel >= 0)
2144 S.ActOnCapturedRegionError();
2145 }
2146 }
2147};
2148} // namespace
2149
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002150StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2151 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002152 bool ErrorFound = false;
2153 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2154 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002155 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002156 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002157 return StmtError();
2158 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002159
2160 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002161 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002162 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002163 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002164 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002165 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002166 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2167 Clause->getClauseKind() == OMPC_in_reduction) {
2168 // Capture taskgroup task_reduction descriptors inside the tasking regions
2169 // with the corresponding in_reduction items.
2170 auto *IRC = cast<OMPInReductionClause>(Clause);
2171 for (auto *E : IRC->taskgroup_descriptors())
2172 if (E)
2173 MarkDeclarationsReferencedInExpr(E);
2174 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002175 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002176 Clause->getClauseKind() == OMPC_copyprivate ||
2177 (getLangOpts().OpenMPUseTLS &&
2178 getASTContext().getTargetInfo().isTLSSupported() &&
2179 Clause->getClauseKind() == OMPC_copyin)) {
2180 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002181 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002182 for (auto *VarRef : Clause->children()) {
2183 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002184 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002185 }
2186 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002187 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002188 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002189 if (auto *C = OMPClauseWithPreInit::get(Clause))
2190 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002191 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2192 if (auto *E = C->getPostUpdateExpr())
2193 MarkDeclarationsReferencedInExpr(E);
2194 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002195 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002196 if (Clause->getClauseKind() == OMPC_schedule)
2197 SC = cast<OMPScheduleClause>(Clause);
2198 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002199 OC = cast<OMPOrderedClause>(Clause);
2200 else if (Clause->getClauseKind() == OMPC_linear)
2201 LCs.push_back(cast<OMPLinearClause>(Clause));
2202 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002203 // OpenMP, 2.7.1 Loop Construct, Restrictions
2204 // The nonmonotonic modifier cannot be specified if an ordered clause is
2205 // specified.
2206 if (SC &&
2207 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2208 SC->getSecondScheduleModifier() ==
2209 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2210 OC) {
2211 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2212 ? SC->getFirstScheduleModifierLoc()
2213 : SC->getSecondScheduleModifierLoc(),
2214 diag::err_omp_schedule_nonmonotonic_ordered)
2215 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2216 ErrorFound = true;
2217 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002218 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2219 for (auto *C : LCs) {
2220 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2221 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2222 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002223 ErrorFound = true;
2224 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002225 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2226 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2227 OC->getNumForLoops()) {
2228 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2229 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2230 ErrorFound = true;
2231 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002232 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002233 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002234 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002235 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002236 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2237 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2238 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
2239 // Mark all variables in private list clauses as used in inner region.
2240 // Required for proper codegen of combined directives.
2241 // TODO: add processing for other clauses.
2242 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
2243 for (auto *C : PICs) {
2244 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2245 // Find the particular capture region for the clause if the
2246 // directive is a combined one with multiple capture regions.
2247 // If the directive is not a combined one, the capture region
2248 // associated with the clause is OMPD_unknown and is generated
2249 // only once.
2250 if (CaptureRegion == ThisCaptureRegion ||
2251 CaptureRegion == OMPD_unknown) {
2252 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2253 for (auto *D : DS->decls())
2254 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2255 }
2256 }
2257 }
2258 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002259 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002260 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002261 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002262}
2263
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002264static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2265 OpenMPDirectiveKind CancelRegion,
2266 SourceLocation StartLoc) {
2267 // CancelRegion is only needed for cancel and cancellation_point.
2268 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2269 return false;
2270
2271 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2272 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2273 return false;
2274
2275 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2276 << getOpenMPDirectiveName(CancelRegion);
2277 return true;
2278}
2279
2280static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002281 OpenMPDirectiveKind CurrentRegion,
2282 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002283 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002284 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002285 if (Stack->getCurScope()) {
2286 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002287 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002288 bool NestingProhibited = false;
2289 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002290 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002291 enum {
2292 NoRecommend,
2293 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002294 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002295 ShouldBeInTargetRegion,
2296 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002297 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002298 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002299 // OpenMP [2.16, Nesting of Regions]
2300 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002301 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002302 // An ordered construct with the simd clause is the only OpenMP
2303 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002304 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002305 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2306 // message.
2307 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2308 ? diag::err_omp_prohibited_region_simd
2309 : diag::warn_omp_nesting_simd);
2310 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002311 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002312 if (ParentRegion == OMPD_atomic) {
2313 // OpenMP [2.16, Nesting of Regions]
2314 // OpenMP constructs may not be nested inside an atomic region.
2315 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2316 return true;
2317 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002318 if (CurrentRegion == OMPD_section) {
2319 // OpenMP [2.7.2, sections Construct, Restrictions]
2320 // Orphaned section directives are prohibited. That is, the section
2321 // directives must appear within the sections construct and must not be
2322 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002323 if (ParentRegion != OMPD_sections &&
2324 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002325 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2326 << (ParentRegion != OMPD_unknown)
2327 << getOpenMPDirectiveName(ParentRegion);
2328 return true;
2329 }
2330 return false;
2331 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002332 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002333 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002334 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002335 if (ParentRegion == OMPD_unknown &&
2336 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002337 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002338 if (CurrentRegion == OMPD_cancellation_point ||
2339 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002340 // OpenMP [2.16, Nesting of Regions]
2341 // A cancellation point construct for which construct-type-clause is
2342 // taskgroup must be nested inside a task construct. A cancellation
2343 // point construct for which construct-type-clause is not taskgroup must
2344 // be closely nested inside an OpenMP construct that matches the type
2345 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002346 // A cancel construct for which construct-type-clause is taskgroup must be
2347 // nested inside a task construct. A cancel construct for which
2348 // construct-type-clause is not taskgroup must be closely nested inside an
2349 // OpenMP construct that matches the type specified in
2350 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002351 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002352 !((CancelRegion == OMPD_parallel &&
2353 (ParentRegion == OMPD_parallel ||
2354 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002355 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002356 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2357 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002358 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2359 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002360 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2361 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002362 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002363 // OpenMP [2.16, Nesting of Regions]
2364 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002365 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002366 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002367 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002368 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2369 // OpenMP [2.16, Nesting of Regions]
2370 // A critical region may not be nested (closely or otherwise) inside a
2371 // critical region with the same name. Note that this restriction is not
2372 // sufficient to prevent deadlock.
2373 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002374 bool DeadLock = Stack->hasDirective(
2375 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2376 const DeclarationNameInfo &DNI,
2377 SourceLocation Loc) -> bool {
2378 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2379 PreviousCriticalLoc = Loc;
2380 return true;
2381 } else
2382 return false;
2383 },
2384 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002385 if (DeadLock) {
2386 SemaRef.Diag(StartLoc,
2387 diag::err_omp_prohibited_region_critical_same_name)
2388 << CurrentName.getName();
2389 if (PreviousCriticalLoc.isValid())
2390 SemaRef.Diag(PreviousCriticalLoc,
2391 diag::note_omp_previous_critical_region);
2392 return true;
2393 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002394 } else if (CurrentRegion == OMPD_barrier) {
2395 // OpenMP [2.16, Nesting of Regions]
2396 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002397 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002398 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2399 isOpenMPTaskingDirective(ParentRegion) ||
2400 ParentRegion == OMPD_master ||
2401 ParentRegion == OMPD_critical ||
2402 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002403 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002404 !isOpenMPParallelDirective(CurrentRegion) &&
2405 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002406 // OpenMP [2.16, Nesting of Regions]
2407 // A worksharing region may not be closely nested inside a worksharing,
2408 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002409 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2410 isOpenMPTaskingDirective(ParentRegion) ||
2411 ParentRegion == OMPD_master ||
2412 ParentRegion == OMPD_critical ||
2413 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002414 Recommend = ShouldBeInParallelRegion;
2415 } else if (CurrentRegion == OMPD_ordered) {
2416 // OpenMP [2.16, Nesting of Regions]
2417 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002418 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002419 // An ordered region must be closely nested inside a loop region (or
2420 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002421 // OpenMP [2.8.1,simd Construct, Restrictions]
2422 // An ordered construct with the simd clause is the only OpenMP construct
2423 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002424 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002425 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002426 !(isOpenMPSimdDirective(ParentRegion) ||
2427 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002428 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002429 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002430 // OpenMP [2.16, Nesting of Regions]
2431 // If specified, a teams construct must be contained within a target
2432 // construct.
2433 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002434 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002435 Recommend = ShouldBeInTargetRegion;
2436 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2437 }
Kelvin Libf594a52016-12-17 05:48:59 +00002438 if (!NestingProhibited &&
2439 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2440 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2441 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002442 // OpenMP [2.16, Nesting of Regions]
2443 // distribute, parallel, parallel sections, parallel workshare, and the
2444 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2445 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002446 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2447 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002448 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002449 }
David Majnemer9d168222016-08-05 17:44:54 +00002450 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002451 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002452 // OpenMP 4.5 [2.17 Nesting of Regions]
2453 // The region associated with the distribute construct must be strictly
2454 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002455 NestingProhibited =
2456 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002457 Recommend = ShouldBeInTeamsRegion;
2458 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002459 if (!NestingProhibited &&
2460 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2461 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2462 // OpenMP 4.5 [2.17 Nesting of Regions]
2463 // If a target, target update, target data, target enter data, or
2464 // target exit data construct is encountered during execution of a
2465 // target region, the behavior is unspecified.
2466 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002467 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2468 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002469 if (isOpenMPTargetExecutionDirective(K)) {
2470 OffendingRegion = K;
2471 return true;
2472 } else
2473 return false;
2474 },
2475 false /* don't skip top directive */);
2476 CloseNesting = false;
2477 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002478 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002479 if (OrphanSeen) {
2480 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2481 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2482 } else {
2483 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2484 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2485 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2486 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002487 return true;
2488 }
2489 }
2490 return false;
2491}
2492
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002493static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2494 ArrayRef<OMPClause *> Clauses,
2495 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2496 bool ErrorFound = false;
2497 unsigned NamedModifiersNumber = 0;
2498 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2499 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002500 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002501 for (const auto *C : Clauses) {
2502 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2503 // At most one if clause without a directive-name-modifier can appear on
2504 // the directive.
2505 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2506 if (FoundNameModifiers[CurNM]) {
2507 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2508 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2509 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2510 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002511 } else if (CurNM != OMPD_unknown) {
2512 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002513 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002514 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002515 FoundNameModifiers[CurNM] = IC;
2516 if (CurNM == OMPD_unknown)
2517 continue;
2518 // Check if the specified name modifier is allowed for the current
2519 // directive.
2520 // At most one if clause with the particular directive-name-modifier can
2521 // appear on the directive.
2522 bool MatchFound = false;
2523 for (auto NM : AllowedNameModifiers) {
2524 if (CurNM == NM) {
2525 MatchFound = true;
2526 break;
2527 }
2528 }
2529 if (!MatchFound) {
2530 S.Diag(IC->getNameModifierLoc(),
2531 diag::err_omp_wrong_if_directive_name_modifier)
2532 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2533 ErrorFound = true;
2534 }
2535 }
2536 }
2537 // If any if clause on the directive includes a directive-name-modifier then
2538 // all if clauses on the directive must include a directive-name-modifier.
2539 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2540 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2541 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2542 diag::err_omp_no_more_if_clause);
2543 } else {
2544 std::string Values;
2545 std::string Sep(", ");
2546 unsigned AllowedCnt = 0;
2547 unsigned TotalAllowedNum =
2548 AllowedNameModifiers.size() - NamedModifiersNumber;
2549 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2550 ++Cnt) {
2551 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2552 if (!FoundNameModifiers[NM]) {
2553 Values += "'";
2554 Values += getOpenMPDirectiveName(NM);
2555 Values += "'";
2556 if (AllowedCnt + 2 == TotalAllowedNum)
2557 Values += " or ";
2558 else if (AllowedCnt + 1 != TotalAllowedNum)
2559 Values += Sep;
2560 ++AllowedCnt;
2561 }
2562 }
2563 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2564 diag::err_omp_unnamed_if_clause)
2565 << (TotalAllowedNum > 1) << Values;
2566 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002567 for (auto Loc : NameModifierLoc) {
2568 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2569 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002570 ErrorFound = true;
2571 }
2572 return ErrorFound;
2573}
2574
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002575StmtResult Sema::ActOnOpenMPExecutableDirective(
2576 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2577 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2578 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002579 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002580 // First check CancelRegion which is then used in checkNestingOfRegions.
2581 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2582 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002583 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002584 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002585
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002586 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002587 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002588 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002589 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002590 if (AStmt) {
2591 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2592
2593 // Check default data sharing attributes for referenced variables.
2594 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002595 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2596 Stmt *S = AStmt;
2597 while (--ThisCaptureLevel >= 0)
2598 S = cast<CapturedStmt>(S)->getCapturedStmt();
2599 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002600 if (DSAChecker.isErrorFound())
2601 return StmtError();
2602 // Generate list of implicitly defined firstprivate variables.
2603 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002604
Alexey Bataev88202be2017-07-27 13:20:36 +00002605 SmallVector<Expr *, 4> ImplicitFirstprivates(
2606 DSAChecker.getImplicitFirstprivate().begin(),
2607 DSAChecker.getImplicitFirstprivate().end());
2608 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2609 for (auto *C : Clauses) {
2610 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2611 for (auto *E : IRC->taskgroup_descriptors())
2612 if (E)
2613 ImplicitFirstprivates.emplace_back(E);
2614 }
2615 }
2616 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002617 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002618 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2619 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002620 ClausesWithImplicit.push_back(Implicit);
2621 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002622 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002623 } else
2624 ErrorFound = true;
2625 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002626 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002627
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002628 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002629 switch (Kind) {
2630 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002631 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2632 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002633 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002634 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002635 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002636 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2637 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002638 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002639 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002640 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2641 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002642 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002643 case OMPD_for_simd:
2644 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2645 EndLoc, VarsWithInheritedDSA);
2646 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002647 case OMPD_sections:
2648 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2649 EndLoc);
2650 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002651 case OMPD_section:
2652 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002653 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002654 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2655 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002656 case OMPD_single:
2657 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2658 EndLoc);
2659 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002660 case OMPD_master:
2661 assert(ClausesWithImplicit.empty() &&
2662 "No clauses are allowed for 'omp master' directive");
2663 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2664 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002665 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002666 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2667 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002668 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002669 case OMPD_parallel_for:
2670 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2671 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002672 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002673 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002674 case OMPD_parallel_for_simd:
2675 Res = ActOnOpenMPParallelForSimdDirective(
2676 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002677 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002678 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002679 case OMPD_parallel_sections:
2680 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2681 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002682 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002683 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002684 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002685 Res =
2686 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002687 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002688 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002689 case OMPD_taskyield:
2690 assert(ClausesWithImplicit.empty() &&
2691 "No clauses are allowed for 'omp taskyield' directive");
2692 assert(AStmt == nullptr &&
2693 "No associated statement allowed for 'omp taskyield' directive");
2694 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2695 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002696 case OMPD_barrier:
2697 assert(ClausesWithImplicit.empty() &&
2698 "No clauses are allowed for 'omp barrier' directive");
2699 assert(AStmt == nullptr &&
2700 "No associated statement allowed for 'omp barrier' directive");
2701 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2702 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002703 case OMPD_taskwait:
2704 assert(ClausesWithImplicit.empty() &&
2705 "No clauses are allowed for 'omp taskwait' directive");
2706 assert(AStmt == nullptr &&
2707 "No associated statement allowed for 'omp taskwait' directive");
2708 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2709 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002710 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00002711 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
2712 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002713 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002714 case OMPD_flush:
2715 assert(AStmt == nullptr &&
2716 "No associated statement allowed for 'omp flush' directive");
2717 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2718 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002719 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002720 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2721 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002722 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002723 case OMPD_atomic:
2724 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2725 EndLoc);
2726 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002727 case OMPD_teams:
2728 Res =
2729 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2730 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002731 case OMPD_target:
2732 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2733 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002734 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002735 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002736 case OMPD_target_parallel:
2737 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2738 StartLoc, EndLoc);
2739 AllowedNameModifiers.push_back(OMPD_target);
2740 AllowedNameModifiers.push_back(OMPD_parallel);
2741 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002742 case OMPD_target_parallel_for:
2743 Res = ActOnOpenMPTargetParallelForDirective(
2744 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2745 AllowedNameModifiers.push_back(OMPD_target);
2746 AllowedNameModifiers.push_back(OMPD_parallel);
2747 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002748 case OMPD_cancellation_point:
2749 assert(ClausesWithImplicit.empty() &&
2750 "No clauses are allowed for 'omp cancellation point' directive");
2751 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2752 "cancellation point' directive");
2753 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2754 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002755 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002756 assert(AStmt == nullptr &&
2757 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002758 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2759 CancelRegion);
2760 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002761 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002762 case OMPD_target_data:
2763 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2764 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002765 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002766 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002767 case OMPD_target_enter_data:
2768 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2769 EndLoc);
2770 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2771 break;
Samuel Antao72590762016-01-19 20:04:50 +00002772 case OMPD_target_exit_data:
2773 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2774 EndLoc);
2775 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2776 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002777 case OMPD_taskloop:
2778 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2779 EndLoc, VarsWithInheritedDSA);
2780 AllowedNameModifiers.push_back(OMPD_taskloop);
2781 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002782 case OMPD_taskloop_simd:
2783 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2784 EndLoc, VarsWithInheritedDSA);
2785 AllowedNameModifiers.push_back(OMPD_taskloop);
2786 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002787 case OMPD_distribute:
2788 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2789 EndLoc, VarsWithInheritedDSA);
2790 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002791 case OMPD_target_update:
2792 assert(!AStmt && "Statement is not allowed for target update");
2793 Res =
2794 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2795 AllowedNameModifiers.push_back(OMPD_target_update);
2796 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002797 case OMPD_distribute_parallel_for:
2798 Res = ActOnOpenMPDistributeParallelForDirective(
2799 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2800 AllowedNameModifiers.push_back(OMPD_parallel);
2801 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002802 case OMPD_distribute_parallel_for_simd:
2803 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2804 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2805 AllowedNameModifiers.push_back(OMPD_parallel);
2806 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002807 case OMPD_distribute_simd:
2808 Res = ActOnOpenMPDistributeSimdDirective(
2809 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2810 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002811 case OMPD_target_parallel_for_simd:
2812 Res = ActOnOpenMPTargetParallelForSimdDirective(
2813 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2814 AllowedNameModifiers.push_back(OMPD_target);
2815 AllowedNameModifiers.push_back(OMPD_parallel);
2816 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002817 case OMPD_target_simd:
2818 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2819 EndLoc, VarsWithInheritedDSA);
2820 AllowedNameModifiers.push_back(OMPD_target);
2821 break;
Kelvin Li02532872016-08-05 14:37:37 +00002822 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002823 Res = ActOnOpenMPTeamsDistributeDirective(
2824 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002825 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002826 case OMPD_teams_distribute_simd:
2827 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2828 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2829 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002830 case OMPD_teams_distribute_parallel_for_simd:
2831 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2832 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2833 AllowedNameModifiers.push_back(OMPD_parallel);
2834 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002835 case OMPD_teams_distribute_parallel_for:
2836 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2837 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2838 AllowedNameModifiers.push_back(OMPD_parallel);
2839 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002840 case OMPD_target_teams:
2841 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2842 EndLoc);
2843 AllowedNameModifiers.push_back(OMPD_target);
2844 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002845 case OMPD_target_teams_distribute:
2846 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2847 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2848 AllowedNameModifiers.push_back(OMPD_target);
2849 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002850 case OMPD_target_teams_distribute_parallel_for:
2851 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2852 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2853 AllowedNameModifiers.push_back(OMPD_target);
2854 AllowedNameModifiers.push_back(OMPD_parallel);
2855 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002856 case OMPD_target_teams_distribute_parallel_for_simd:
2857 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2858 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2859 AllowedNameModifiers.push_back(OMPD_target);
2860 AllowedNameModifiers.push_back(OMPD_parallel);
2861 break;
Kelvin Lida681182017-01-10 18:08:18 +00002862 case OMPD_target_teams_distribute_simd:
2863 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2864 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2865 AllowedNameModifiers.push_back(OMPD_target);
2866 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002867 case OMPD_declare_target:
2868 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002869 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002870 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002871 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002872 llvm_unreachable("OpenMP Directive is not allowed");
2873 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002874 llvm_unreachable("Unknown OpenMP directive");
2875 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002876
Alexey Bataev4acb8592014-07-07 13:01:15 +00002877 for (auto P : VarsWithInheritedDSA) {
2878 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2879 << P.first << P.second->getSourceRange();
2880 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002881 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2882
2883 if (!AllowedNameModifiers.empty())
2884 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2885 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002886
Alexey Bataeved09d242014-05-28 05:53:51 +00002887 if (ErrorFound)
2888 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002889 return Res;
2890}
2891
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002892Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2893 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002894 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002895 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2896 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002897 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002898 assert(Linears.size() == LinModifiers.size());
2899 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002900 if (!DG || DG.get().isNull())
2901 return DeclGroupPtrTy();
2902
2903 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002904 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002905 return DG;
2906 }
2907 auto *ADecl = DG.get().getSingleDecl();
2908 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2909 ADecl = FTD->getTemplatedDecl();
2910
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002911 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2912 if (!FD) {
2913 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002914 return DeclGroupPtrTy();
2915 }
2916
Alexey Bataev2af33e32016-04-07 12:45:37 +00002917 // OpenMP [2.8.2, declare simd construct, Description]
2918 // The parameter of the simdlen clause must be a constant positive integer
2919 // expression.
2920 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002921 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002922 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002923 // OpenMP [2.8.2, declare simd construct, Description]
2924 // The special this pointer can be used as if was one of the arguments to the
2925 // function in any of the linear, aligned, or uniform clauses.
2926 // The uniform clause declares one or more arguments to have an invariant
2927 // value for all concurrent invocations of the function in the execution of a
2928 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002929 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2930 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002931 for (auto *E : Uniforms) {
2932 E = E->IgnoreParenImpCasts();
2933 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2934 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2935 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2936 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002937 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2938 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002939 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002940 }
2941 if (isa<CXXThisExpr>(E)) {
2942 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002943 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002944 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002945 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2946 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002947 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002948 // OpenMP [2.8.2, declare simd construct, Description]
2949 // The aligned clause declares that the object to which each list item points
2950 // is aligned to the number of bytes expressed in the optional parameter of
2951 // the aligned clause.
2952 // The special this pointer can be used as if was one of the arguments to the
2953 // function in any of the linear, aligned, or uniform clauses.
2954 // The type of list items appearing in the aligned clause must be array,
2955 // pointer, reference to array, or reference to pointer.
2956 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2957 Expr *AlignedThis = nullptr;
2958 for (auto *E : Aligneds) {
2959 E = E->IgnoreParenImpCasts();
2960 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2961 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2962 auto *CanonPVD = PVD->getCanonicalDecl();
2963 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2964 FD->getParamDecl(PVD->getFunctionScopeIndex())
2965 ->getCanonicalDecl() == CanonPVD) {
2966 // OpenMP [2.8.1, simd construct, Restrictions]
2967 // A list-item cannot appear in more than one aligned clause.
2968 if (AlignedArgs.count(CanonPVD) > 0) {
2969 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2970 << 1 << E->getSourceRange();
2971 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2972 diag::note_omp_explicit_dsa)
2973 << getOpenMPClauseName(OMPC_aligned);
2974 continue;
2975 }
2976 AlignedArgs[CanonPVD] = E;
2977 QualType QTy = PVD->getType()
2978 .getNonReferenceType()
2979 .getUnqualifiedType()
2980 .getCanonicalType();
2981 const Type *Ty = QTy.getTypePtrOrNull();
2982 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2983 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2984 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2985 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2986 }
2987 continue;
2988 }
2989 }
2990 if (isa<CXXThisExpr>(E)) {
2991 if (AlignedThis) {
2992 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2993 << 2 << E->getSourceRange();
2994 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2995 << getOpenMPClauseName(OMPC_aligned);
2996 }
2997 AlignedThis = E;
2998 continue;
2999 }
3000 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3001 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3002 }
3003 // The optional parameter of the aligned clause, alignment, must be a constant
3004 // positive integer expression. If no optional parameter is specified,
3005 // implementation-defined default alignments for SIMD instructions on the
3006 // target platforms are assumed.
3007 SmallVector<Expr *, 4> NewAligns;
3008 for (auto *E : Alignments) {
3009 ExprResult Align;
3010 if (E)
3011 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3012 NewAligns.push_back(Align.get());
3013 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003014 // OpenMP [2.8.2, declare simd construct, Description]
3015 // The linear clause declares one or more list items to be private to a SIMD
3016 // lane and to have a linear relationship with respect to the iteration space
3017 // of a loop.
3018 // The special this pointer can be used as if was one of the arguments to the
3019 // function in any of the linear, aligned, or uniform clauses.
3020 // When a linear-step expression is specified in a linear clause it must be
3021 // either a constant integer expression or an integer-typed parameter that is
3022 // specified in a uniform clause on the directive.
3023 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3024 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3025 auto MI = LinModifiers.begin();
3026 for (auto *E : Linears) {
3027 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3028 ++MI;
3029 E = E->IgnoreParenImpCasts();
3030 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3031 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3032 auto *CanonPVD = PVD->getCanonicalDecl();
3033 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3034 FD->getParamDecl(PVD->getFunctionScopeIndex())
3035 ->getCanonicalDecl() == CanonPVD) {
3036 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3037 // A list-item cannot appear in more than one linear clause.
3038 if (LinearArgs.count(CanonPVD) > 0) {
3039 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3040 << getOpenMPClauseName(OMPC_linear)
3041 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3042 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3043 diag::note_omp_explicit_dsa)
3044 << getOpenMPClauseName(OMPC_linear);
3045 continue;
3046 }
3047 // Each argument can appear in at most one uniform or linear clause.
3048 if (UniformedArgs.count(CanonPVD) > 0) {
3049 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3050 << getOpenMPClauseName(OMPC_linear)
3051 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3052 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3053 diag::note_omp_explicit_dsa)
3054 << getOpenMPClauseName(OMPC_uniform);
3055 continue;
3056 }
3057 LinearArgs[CanonPVD] = E;
3058 if (E->isValueDependent() || E->isTypeDependent() ||
3059 E->isInstantiationDependent() ||
3060 E->containsUnexpandedParameterPack())
3061 continue;
3062 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3063 PVD->getOriginalType());
3064 continue;
3065 }
3066 }
3067 if (isa<CXXThisExpr>(E)) {
3068 if (UniformedLinearThis) {
3069 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3070 << getOpenMPClauseName(OMPC_linear)
3071 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3072 << E->getSourceRange();
3073 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3074 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3075 : OMPC_linear);
3076 continue;
3077 }
3078 UniformedLinearThis = E;
3079 if (E->isValueDependent() || E->isTypeDependent() ||
3080 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3081 continue;
3082 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3083 E->getType());
3084 continue;
3085 }
3086 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3087 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3088 }
3089 Expr *Step = nullptr;
3090 Expr *NewStep = nullptr;
3091 SmallVector<Expr *, 4> NewSteps;
3092 for (auto *E : Steps) {
3093 // Skip the same step expression, it was checked already.
3094 if (Step == E || !E) {
3095 NewSteps.push_back(E ? NewStep : nullptr);
3096 continue;
3097 }
3098 Step = E;
3099 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3100 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3101 auto *CanonPVD = PVD->getCanonicalDecl();
3102 if (UniformedArgs.count(CanonPVD) == 0) {
3103 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3104 << Step->getSourceRange();
3105 } else if (E->isValueDependent() || E->isTypeDependent() ||
3106 E->isInstantiationDependent() ||
3107 E->containsUnexpandedParameterPack() ||
3108 CanonPVD->getType()->hasIntegerRepresentation())
3109 NewSteps.push_back(Step);
3110 else {
3111 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3112 << Step->getSourceRange();
3113 }
3114 continue;
3115 }
3116 NewStep = Step;
3117 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3118 !Step->isInstantiationDependent() &&
3119 !Step->containsUnexpandedParameterPack()) {
3120 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3121 .get();
3122 if (NewStep)
3123 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3124 }
3125 NewSteps.push_back(NewStep);
3126 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003127 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3128 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003129 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003130 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3131 const_cast<Expr **>(Linears.data()), Linears.size(),
3132 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3133 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003134 ADecl->addAttr(NewAttr);
3135 return ConvertDeclToDeclGroup(ADecl);
3136}
3137
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003138StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3139 Stmt *AStmt,
3140 SourceLocation StartLoc,
3141 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003142 if (!AStmt)
3143 return StmtError();
3144
Alexey Bataev9959db52014-05-06 10:08:46 +00003145 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3146 // 1.2.2 OpenMP Language Terminology
3147 // Structured block - An executable statement with a single entry at the
3148 // top and a single exit at the bottom.
3149 // The point of exit cannot be a branch out of the structured block.
3150 // longjmp() and throw() must not violate the entry/exit criteria.
3151 CS->getCapturedDecl()->setNothrow();
3152
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003153 getCurFunction()->setHasBranchProtectedScope();
3154
Alexey Bataev25e5b442015-09-15 12:52:43 +00003155 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3156 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003157}
3158
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003159namespace {
3160/// \brief Helper class for checking canonical form of the OpenMP loops and
3161/// extracting iteration space of each loop in the loop nest, that will be used
3162/// for IR generation.
3163class OpenMPIterationSpaceChecker {
3164 /// \brief Reference to Sema.
3165 Sema &SemaRef;
3166 /// \brief A location for diagnostics (when there is no some better location).
3167 SourceLocation DefaultLoc;
3168 /// \brief A location for diagnostics (when increment is not compatible).
3169 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003170 /// \brief A source location for referring to loop init later.
3171 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003172 /// \brief A source location for referring to condition later.
3173 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003174 /// \brief A source location for referring to increment later.
3175 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003176 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003177 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003178 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003179 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003180 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003181 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003182 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003183 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003184 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003185 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003186 /// \brief This flag is true when condition is one of:
3187 /// Var < UB
3188 /// Var <= UB
3189 /// UB > Var
3190 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003191 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003192 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003193 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003194 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003195 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003196
3197public:
3198 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003199 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003200 /// \brief Check init-expr for canonical loop form and save loop counter
3201 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003202 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003203 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3204 /// for less/greater and for strict/non-strict comparison.
3205 bool CheckCond(Expr *S);
3206 /// \brief Check incr-expr for canonical loop form and return true if it
3207 /// does not conform, otherwise save loop step (#Step).
3208 bool CheckInc(Expr *S);
3209 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003210 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003211 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003212 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003213 /// \brief Source range of the loop init.
3214 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3215 /// \brief Source range of the loop condition.
3216 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3217 /// \brief Source range of the loop increment.
3218 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3219 /// \brief True if the step should be subtracted.
3220 bool ShouldSubtractStep() const { return SubtractStep; }
3221 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003222 Expr *
3223 BuildNumIterations(Scope *S, const bool LimitedType,
3224 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003225 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003226 Expr *BuildPreCond(Scope *S, Expr *Cond,
3227 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003228 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003229 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3230 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003231 /// \brief Build reference expression to the private counter be used for
3232 /// codegen.
3233 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003234 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003235 Expr *BuildCounterInit() const;
3236 /// \brief Build step of the counter be used for codegen.
3237 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003238 /// \brief Return true if any expression is dependent.
3239 bool Dependent() const;
3240
3241private:
3242 /// \brief Check the right-hand side of an assignment in the increment
3243 /// expression.
3244 bool CheckIncRHS(Expr *RHS);
3245 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003246 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003247 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003248 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003249 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003250 /// \brief Helper to set loop increment.
3251 bool SetStep(Expr *NewStep, bool Subtract);
3252};
3253
3254bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003255 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003256 assert(!LB && !UB && !Step);
3257 return false;
3258 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003259 return LCDecl->getType()->isDependentType() ||
3260 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3261 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003262}
3263
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003264bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3265 Expr *NewLCRefExpr,
3266 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003267 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003268 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003269 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003270 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003271 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003272 LCDecl = getCanonicalDecl(NewLCDecl);
3273 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003274 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3275 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003276 if ((Ctor->isCopyOrMoveConstructor() ||
3277 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3278 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003279 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003280 LB = NewLB;
3281 return false;
3282}
3283
3284bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003285 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003286 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003287 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3288 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003289 if (!NewUB)
3290 return true;
3291 UB = NewUB;
3292 TestIsLessOp = LessOp;
3293 TestIsStrictOp = StrictOp;
3294 ConditionSrcRange = SR;
3295 ConditionLoc = SL;
3296 return false;
3297}
3298
3299bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3300 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003301 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003302 if (!NewStep)
3303 return true;
3304 if (!NewStep->isValueDependent()) {
3305 // Check that the step is integer expression.
3306 SourceLocation StepLoc = NewStep->getLocStart();
3307 ExprResult Val =
3308 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
3309 if (Val.isInvalid())
3310 return true;
3311 NewStep = Val.get();
3312
3313 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3314 // If test-expr is of form var relational-op b and relational-op is < or
3315 // <= then incr-expr must cause var to increase on each iteration of the
3316 // loop. If test-expr is of form var relational-op b and relational-op is
3317 // > or >= then incr-expr must cause var to decrease on each iteration of
3318 // the loop.
3319 // If test-expr is of form b relational-op var and relational-op is < or
3320 // <= then incr-expr must cause var to decrease on each iteration of the
3321 // loop. If test-expr is of form b relational-op var and relational-op is
3322 // > or >= then incr-expr must cause var to increase on each iteration of
3323 // the loop.
3324 llvm::APSInt Result;
3325 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3326 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3327 bool IsConstNeg =
3328 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003329 bool IsConstPos =
3330 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003331 bool IsConstZero = IsConstant && !Result.getBoolValue();
3332 if (UB && (IsConstZero ||
3333 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003334 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003335 SemaRef.Diag(NewStep->getExprLoc(),
3336 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003337 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003338 SemaRef.Diag(ConditionLoc,
3339 diag::note_omp_loop_cond_requres_compatible_incr)
3340 << TestIsLessOp << ConditionSrcRange;
3341 return true;
3342 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003343 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003344 NewStep =
3345 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3346 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003347 Subtract = !Subtract;
3348 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003349 }
3350
3351 Step = NewStep;
3352 SubtractStep = Subtract;
3353 return false;
3354}
3355
Alexey Bataev9c821032015-04-30 04:23:23 +00003356bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003357 // Check init-expr for canonical loop form and save loop counter
3358 // variable - #Var and its initialization value - #LB.
3359 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3360 // var = lb
3361 // integer-type var = lb
3362 // random-access-iterator-type var = lb
3363 // pointer-type var = lb
3364 //
3365 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003366 if (EmitDiags) {
3367 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3368 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003369 return true;
3370 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003371 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3372 if (!ExprTemp->cleanupsHaveSideEffects())
3373 S = ExprTemp->getSubExpr();
3374
Alexander Musmana5f070a2014-10-01 06:03:56 +00003375 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003376 if (Expr *E = dyn_cast<Expr>(S))
3377 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003378 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003379 if (BO->getOpcode() == BO_Assign) {
3380 auto *LHS = BO->getLHS()->IgnoreParens();
3381 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3382 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3383 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3384 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3385 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3386 }
3387 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3388 if (ME->isArrow() &&
3389 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3390 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3391 }
3392 }
David Majnemer9d168222016-08-05 17:44:54 +00003393 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003394 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003395 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003396 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003397 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003398 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003399 SemaRef.Diag(S->getLocStart(),
3400 diag::ext_omp_loop_not_canonical_init)
3401 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003402 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003403 }
3404 }
3405 }
David Majnemer9d168222016-08-05 17:44:54 +00003406 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003407 if (CE->getOperator() == OO_Equal) {
3408 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003409 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003410 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3411 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3412 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3413 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3414 }
3415 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3416 if (ME->isArrow() &&
3417 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3418 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3419 }
3420 }
3421 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003422
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003423 if (Dependent() || SemaRef.CurContext->isDependentContext())
3424 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003425 if (EmitDiags) {
3426 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3427 << S->getSourceRange();
3428 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003429 return true;
3430}
3431
Alexey Bataev23b69422014-06-18 07:08:49 +00003432/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003433/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003434static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003435 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003436 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003437 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003438 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3439 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003440 if ((Ctor->isCopyOrMoveConstructor() ||
3441 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3442 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003443 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003444 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003445 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003446 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003447 }
3448 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3449 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3450 return getCanonicalDecl(ME->getMemberDecl());
3451 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003452}
3453
3454bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3455 // Check test-expr for canonical form, save upper-bound UB, flags for
3456 // less/greater and for strict/non-strict comparison.
3457 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3458 // var relational-op b
3459 // b relational-op var
3460 //
3461 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003462 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003463 return true;
3464 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003465 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003466 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003467 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003468 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003469 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003470 return SetUB(BO->getRHS(),
3471 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3472 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3473 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003474 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003475 return SetUB(BO->getLHS(),
3476 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3477 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3478 BO->getSourceRange(), BO->getOperatorLoc());
3479 }
David Majnemer9d168222016-08-05 17:44:54 +00003480 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003481 if (CE->getNumArgs() == 2) {
3482 auto Op = CE->getOperator();
3483 switch (Op) {
3484 case OO_Greater:
3485 case OO_GreaterEqual:
3486 case OO_Less:
3487 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003488 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003489 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3490 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3491 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003492 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003493 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3494 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3495 CE->getOperatorLoc());
3496 break;
3497 default:
3498 break;
3499 }
3500 }
3501 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003502 if (Dependent() || SemaRef.CurContext->isDependentContext())
3503 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003504 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003505 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003506 return true;
3507}
3508
3509bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3510 // RHS of canonical loop form increment can be:
3511 // var + incr
3512 // incr + var
3513 // var - incr
3514 //
3515 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003516 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003517 if (BO->isAdditiveOp()) {
3518 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003519 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003520 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003521 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003522 return SetStep(BO->getLHS(), false);
3523 }
David Majnemer9d168222016-08-05 17:44:54 +00003524 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003525 bool IsAdd = CE->getOperator() == OO_Plus;
3526 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003527 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003528 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003529 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003530 return SetStep(CE->getArg(0), false);
3531 }
3532 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003533 if (Dependent() || SemaRef.CurContext->isDependentContext())
3534 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003535 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003536 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003537 return true;
3538}
3539
3540bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3541 // Check incr-expr for canonical loop form and return true if it
3542 // does not conform.
3543 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3544 // ++var
3545 // var++
3546 // --var
3547 // var--
3548 // var += incr
3549 // var -= incr
3550 // var = var + incr
3551 // var = incr + var
3552 // var = var - incr
3553 //
3554 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003555 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003556 return true;
3557 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003558 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3559 if (!ExprTemp->cleanupsHaveSideEffects())
3560 S = ExprTemp->getSubExpr();
3561
Alexander Musmana5f070a2014-10-01 06:03:56 +00003562 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003563 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003564 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003565 if (UO->isIncrementDecrementOp() &&
3566 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003567 return SetStep(SemaRef
3568 .ActOnIntegerConstant(UO->getLocStart(),
3569 (UO->isDecrementOp() ? -1 : 1))
3570 .get(),
3571 false);
3572 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003573 switch (BO->getOpcode()) {
3574 case BO_AddAssign:
3575 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003576 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003577 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3578 break;
3579 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003580 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003581 return CheckIncRHS(BO->getRHS());
3582 break;
3583 default:
3584 break;
3585 }
David Majnemer9d168222016-08-05 17:44:54 +00003586 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003587 switch (CE->getOperator()) {
3588 case OO_PlusPlus:
3589 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003590 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003591 return SetStep(SemaRef
3592 .ActOnIntegerConstant(
3593 CE->getLocStart(),
3594 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3595 .get(),
3596 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003597 break;
3598 case OO_PlusEqual:
3599 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003600 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003601 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3602 break;
3603 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003604 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003605 return CheckIncRHS(CE->getArg(1));
3606 break;
3607 default:
3608 break;
3609 }
3610 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003611 if (Dependent() || SemaRef.CurContext->isDependentContext())
3612 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003613 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003614 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003615 return true;
3616}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003617
Alexey Bataev5a3af132016-03-29 08:58:54 +00003618static ExprResult
3619tryBuildCapture(Sema &SemaRef, Expr *Capture,
3620 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003621 if (SemaRef.CurContext->isDependentContext())
3622 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003623 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3624 return SemaRef.PerformImplicitConversion(
3625 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3626 /*AllowExplicit=*/true);
3627 auto I = Captures.find(Capture);
3628 if (I != Captures.end())
3629 return buildCapture(SemaRef, Capture, I->second);
3630 DeclRefExpr *Ref = nullptr;
3631 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3632 Captures[Capture] = Ref;
3633 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003634}
3635
Alexander Musmana5f070a2014-10-01 06:03:56 +00003636/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003637Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3638 Scope *S, const bool LimitedType,
3639 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003640 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003641 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003642 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003643 SemaRef.getLangOpts().CPlusPlus) {
3644 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003645 auto *UBExpr = TestIsLessOp ? UB : LB;
3646 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003647 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3648 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003649 if (!Upper || !Lower)
3650 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003651
3652 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3653
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003654 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003655 // BuildBinOp already emitted error, this one is to point user to upper
3656 // and lower bound, and to tell what is passed to 'operator-'.
3657 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3658 << Upper->getSourceRange() << Lower->getSourceRange();
3659 return nullptr;
3660 }
3661 }
3662
3663 if (!Diff.isUsable())
3664 return nullptr;
3665
3666 // Upper - Lower [- 1]
3667 if (TestIsStrictOp)
3668 Diff = SemaRef.BuildBinOp(
3669 S, DefaultLoc, BO_Sub, Diff.get(),
3670 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3671 if (!Diff.isUsable())
3672 return nullptr;
3673
3674 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003675 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3676 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003677 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003678 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003679 if (!Diff.isUsable())
3680 return nullptr;
3681
3682 // Parentheses (for dumping/debugging purposes only).
3683 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3684 if (!Diff.isUsable())
3685 return nullptr;
3686
3687 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003688 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003689 if (!Diff.isUsable())
3690 return nullptr;
3691
Alexander Musman174b3ca2014-10-06 11:16:29 +00003692 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003693 QualType Type = Diff.get()->getType();
3694 auto &C = SemaRef.Context;
3695 bool UseVarType = VarType->hasIntegerRepresentation() &&
3696 C.getTypeSize(Type) > C.getTypeSize(VarType);
3697 if (!Type->isIntegerType() || UseVarType) {
3698 unsigned NewSize =
3699 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3700 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3701 : Type->hasSignedIntegerRepresentation();
3702 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003703 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3704 Diff = SemaRef.PerformImplicitConversion(
3705 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3706 if (!Diff.isUsable())
3707 return nullptr;
3708 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003709 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003710 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003711 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3712 if (NewSize != C.getTypeSize(Type)) {
3713 if (NewSize < C.getTypeSize(Type)) {
3714 assert(NewSize == 64 && "incorrect loop var size");
3715 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3716 << InitSrcRange << ConditionSrcRange;
3717 }
3718 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003719 NewSize, Type->hasSignedIntegerRepresentation() ||
3720 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003721 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3722 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3723 Sema::AA_Converting, true);
3724 if (!Diff.isUsable())
3725 return nullptr;
3726 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003727 }
3728 }
3729
Alexander Musmana5f070a2014-10-01 06:03:56 +00003730 return Diff.get();
3731}
3732
Alexey Bataev5a3af132016-03-29 08:58:54 +00003733Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3734 Scope *S, Expr *Cond,
3735 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003736 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3737 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3738 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003739
Alexey Bataev5a3af132016-03-29 08:58:54 +00003740 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3741 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3742 if (!NewLB.isUsable() || !NewUB.isUsable())
3743 return nullptr;
3744
Alexey Bataev62dbb972015-04-22 11:59:37 +00003745 auto CondExpr = SemaRef.BuildBinOp(
3746 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3747 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003748 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003749 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003750 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3751 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003752 CondExpr = SemaRef.PerformImplicitConversion(
3753 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3754 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003755 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003756 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3757 // Otherwise use original loop conditon and evaluate it in runtime.
3758 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3759}
3760
Alexander Musmana5f070a2014-10-01 06:03:56 +00003761/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003762DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003763 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003764 auto *VD = dyn_cast<VarDecl>(LCDecl);
3765 if (!VD) {
3766 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3767 auto *Ref = buildDeclRefExpr(
3768 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003769 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3770 // If the loop control decl is explicitly marked as private, do not mark it
3771 // as captured again.
3772 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3773 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003774 return Ref;
3775 }
3776 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003777 DefaultLoc);
3778}
3779
3780Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003781 if (LCDecl && !LCDecl->isInvalidDecl()) {
3782 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003783 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003784 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3785 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003786 if (PrivateVar->isInvalidDecl())
3787 return nullptr;
3788 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3789 }
3790 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003791}
3792
Samuel Antao4c8035b2016-12-12 18:00:20 +00003793/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003794Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3795
3796/// \brief Build step of the counter be used for codegen.
3797Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3798
3799/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003800struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003801 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003802 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003803 /// \brief This expression calculates the number of iterations in the loop.
3804 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003805 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003806 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003807 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003808 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003809 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003810 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003811 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003812 /// \brief This is step for the #CounterVar used to generate its update:
3813 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003814 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003815 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003816 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003817 /// \brief Source range of the loop init.
3818 SourceRange InitSrcRange;
3819 /// \brief Source range of the loop condition.
3820 SourceRange CondSrcRange;
3821 /// \brief Source range of the loop increment.
3822 SourceRange IncSrcRange;
3823};
3824
Alexey Bataev23b69422014-06-18 07:08:49 +00003825} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003826
Alexey Bataev9c821032015-04-30 04:23:23 +00003827void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3828 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3829 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003830 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3831 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003832 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3833 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003834 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3835 if (auto *D = ISC.GetLoopDecl()) {
3836 auto *VD = dyn_cast<VarDecl>(D);
3837 if (!VD) {
3838 if (auto *Private = IsOpenMPCapturedDecl(D))
3839 VD = Private;
3840 else {
3841 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3842 /*WithInit=*/false);
3843 VD = cast<VarDecl>(Ref->getDecl());
3844 }
3845 }
3846 DSAStack->addLoopControlVariable(D, VD);
3847 }
3848 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003849 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003850 }
3851}
3852
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003853/// \brief Called on a for stmt to check and extract its iteration space
3854/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003855static bool CheckOpenMPIterationSpace(
3856 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3857 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003858 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003859 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003860 LoopIterationSpace &ResultIterSpace,
3861 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003862 // OpenMP [2.6, Canonical Loop Form]
3863 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003864 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003865 if (!For) {
3866 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003867 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3868 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3869 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3870 if (NestedLoopCount > 1) {
3871 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3872 SemaRef.Diag(DSA.getConstructLoc(),
3873 diag::note_omp_collapse_ordered_expr)
3874 << 2 << CollapseLoopCountExpr->getSourceRange()
3875 << OrderedLoopCountExpr->getSourceRange();
3876 else if (CollapseLoopCountExpr)
3877 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3878 diag::note_omp_collapse_ordered_expr)
3879 << 0 << CollapseLoopCountExpr->getSourceRange();
3880 else
3881 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3882 diag::note_omp_collapse_ordered_expr)
3883 << 1 << OrderedLoopCountExpr->getSourceRange();
3884 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003885 return true;
3886 }
3887 assert(For->getBody());
3888
3889 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3890
3891 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003892 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003893 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003894 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003895
3896 bool HasErrors = false;
3897
3898 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003899 if (auto *LCDecl = ISC.GetLoopDecl()) {
3900 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003901
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003902 // OpenMP [2.6, Canonical Loop Form]
3903 // Var is one of the following:
3904 // A variable of signed or unsigned integer type.
3905 // For C++, a variable of a random access iterator type.
3906 // For C, a variable of a pointer type.
3907 auto VarType = LCDecl->getType().getNonReferenceType();
3908 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3909 !VarType->isPointerType() &&
3910 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3911 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3912 << SemaRef.getLangOpts().CPlusPlus;
3913 HasErrors = true;
3914 }
3915
3916 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3917 // a Construct
3918 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3919 // parallel for construct is (are) private.
3920 // The loop iteration variable in the associated for-loop of a simd
3921 // construct with just one associated for-loop is linear with a
3922 // constant-linear-step that is the increment of the associated for-loop.
3923 // Exclude loop var from the list of variables with implicitly defined data
3924 // sharing attributes.
3925 VarsWithImplicitDSA.erase(LCDecl);
3926
3927 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3928 // in a Construct, C/C++].
3929 // The loop iteration variable in the associated for-loop of a simd
3930 // construct with just one associated for-loop may be listed in a linear
3931 // clause with a constant-linear-step that is the increment of the
3932 // associated for-loop.
3933 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3934 // parallel for construct may be listed in a private or lastprivate clause.
3935 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3936 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3937 // declared in the loop and it is predetermined as a private.
3938 auto PredeterminedCKind =
3939 isOpenMPSimdDirective(DKind)
3940 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3941 : OMPC_private;
3942 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3943 DVar.CKind != PredeterminedCKind) ||
3944 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3945 isOpenMPDistributeDirective(DKind)) &&
3946 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3947 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3948 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3949 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3950 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3951 << getOpenMPClauseName(PredeterminedCKind);
3952 if (DVar.RefExpr == nullptr)
3953 DVar.CKind = PredeterminedCKind;
3954 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3955 HasErrors = true;
3956 } else if (LoopDeclRefExpr != nullptr) {
3957 // Make the loop iteration variable private (for worksharing constructs),
3958 // linear (for simd directives with the only one associated loop) or
3959 // lastprivate (for simd directives with several collapsed or ordered
3960 // loops).
3961 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003962 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3963 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003964 /*FromParent=*/false);
3965 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3966 }
3967
3968 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3969
3970 // Check test-expr.
3971 HasErrors |= ISC.CheckCond(For->getCond());
3972
3973 // Check incr-expr.
3974 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003975 }
3976
Alexander Musmana5f070a2014-10-01 06:03:56 +00003977 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003978 return HasErrors;
3979
Alexander Musmana5f070a2014-10-01 06:03:56 +00003980 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003981 ResultIterSpace.PreCond =
3982 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003983 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003984 DSA.getCurScope(),
3985 (isOpenMPWorksharingDirective(DKind) ||
3986 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3987 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003988 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003989 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003990 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3991 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3992 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3993 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3994 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3995 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3996
Alexey Bataev62dbb972015-04-22 11:59:37 +00003997 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3998 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003999 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004000 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004001 ResultIterSpace.CounterInit == nullptr ||
4002 ResultIterSpace.CounterStep == nullptr);
4003
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004004 return HasErrors;
4005}
4006
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004007/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004008static ExprResult
4009BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4010 ExprResult Start,
4011 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004012 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004013 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4014 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004015 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004016 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004017 VarRef.get()->getType())) {
4018 NewStart = SemaRef.PerformImplicitConversion(
4019 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4020 /*AllowExplicit=*/true);
4021 if (!NewStart.isUsable())
4022 return ExprError();
4023 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004024
4025 auto Init =
4026 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4027 return Init;
4028}
4029
Alexander Musmana5f070a2014-10-01 06:03:56 +00004030/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004031static ExprResult
4032BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4033 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4034 ExprResult Step, bool Subtract,
4035 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004036 // Add parentheses (for debugging purposes only).
4037 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4038 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4039 !Step.isUsable())
4040 return ExprError();
4041
Alexey Bataev5a3af132016-03-29 08:58:54 +00004042 ExprResult NewStep = Step;
4043 if (Captures)
4044 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004045 if (NewStep.isInvalid())
4046 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004047 ExprResult Update =
4048 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004049 if (!Update.isUsable())
4050 return ExprError();
4051
Alexey Bataevc0214e02016-02-16 12:13:49 +00004052 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4053 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004054 ExprResult NewStart = Start;
4055 if (Captures)
4056 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004057 if (NewStart.isInvalid())
4058 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004059
Alexey Bataevc0214e02016-02-16 12:13:49 +00004060 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4061 ExprResult SavedUpdate = Update;
4062 ExprResult UpdateVal;
4063 if (VarRef.get()->getType()->isOverloadableType() ||
4064 NewStart.get()->getType()->isOverloadableType() ||
4065 Update.get()->getType()->isOverloadableType()) {
4066 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4067 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4068 Update =
4069 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4070 if (Update.isUsable()) {
4071 UpdateVal =
4072 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4073 VarRef.get(), SavedUpdate.get());
4074 if (UpdateVal.isUsable()) {
4075 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4076 UpdateVal.get());
4077 }
4078 }
4079 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4080 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004081
Alexey Bataevc0214e02016-02-16 12:13:49 +00004082 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4083 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4084 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4085 NewStart.get(), SavedUpdate.get());
4086 if (!Update.isUsable())
4087 return ExprError();
4088
Alexey Bataev11481f52016-02-17 10:29:05 +00004089 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4090 VarRef.get()->getType())) {
4091 Update = SemaRef.PerformImplicitConversion(
4092 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4093 if (!Update.isUsable())
4094 return ExprError();
4095 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004096
4097 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4098 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004099 return Update;
4100}
4101
4102/// \brief Convert integer expression \a E to make it have at least \a Bits
4103/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004104static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004105 if (E == nullptr)
4106 return ExprError();
4107 auto &C = SemaRef.Context;
4108 QualType OldType = E->getType();
4109 unsigned HasBits = C.getTypeSize(OldType);
4110 if (HasBits >= Bits)
4111 return ExprResult(E);
4112 // OK to convert to signed, because new type has more bits than old.
4113 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4114 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4115 true);
4116}
4117
4118/// \brief Check if the given expression \a E is a constant integer that fits
4119/// into \a Bits bits.
4120static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4121 if (E == nullptr)
4122 return false;
4123 llvm::APSInt Result;
4124 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4125 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4126 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004127}
4128
Alexey Bataev5a3af132016-03-29 08:58:54 +00004129/// Build preinits statement for the given declarations.
4130static Stmt *buildPreInits(ASTContext &Context,
4131 SmallVectorImpl<Decl *> &PreInits) {
4132 if (!PreInits.empty()) {
4133 return new (Context) DeclStmt(
4134 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4135 SourceLocation(), SourceLocation());
4136 }
4137 return nullptr;
4138}
4139
4140/// Build preinits statement for the given declarations.
4141static Stmt *buildPreInits(ASTContext &Context,
4142 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
4143 if (!Captures.empty()) {
4144 SmallVector<Decl *, 16> PreInits;
4145 for (auto &Pair : Captures)
4146 PreInits.push_back(Pair.second->getDecl());
4147 return buildPreInits(Context, PreInits);
4148 }
4149 return nullptr;
4150}
4151
4152/// Build postupdate expression for the given list of postupdates expressions.
4153static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4154 Expr *PostUpdate = nullptr;
4155 if (!PostUpdates.empty()) {
4156 for (auto *E : PostUpdates) {
4157 Expr *ConvE = S.BuildCStyleCastExpr(
4158 E->getExprLoc(),
4159 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4160 E->getExprLoc(), E)
4161 .get();
4162 PostUpdate = PostUpdate
4163 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4164 PostUpdate, ConvE)
4165 .get()
4166 : ConvE;
4167 }
4168 }
4169 return PostUpdate;
4170}
4171
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004172/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004173/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4174/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004175static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004176CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4177 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4178 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004179 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004180 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004181 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004182 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004183 // Found 'collapse' clause - calculate collapse number.
4184 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004185 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004186 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004187 }
4188 if (OrderedLoopCountExpr) {
4189 // Found 'ordered' clause - calculate collapse number.
4190 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004191 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4192 if (Result.getLimitedValue() < NestedLoopCount) {
4193 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4194 diag::err_omp_wrong_ordered_loop_count)
4195 << OrderedLoopCountExpr->getSourceRange();
4196 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4197 diag::note_collapse_loop_count)
4198 << CollapseLoopCountExpr->getSourceRange();
4199 }
4200 NestedLoopCount = Result.getLimitedValue();
4201 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004202 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004203 // This is helper routine for loop directives (e.g., 'for', 'simd',
4204 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004205 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004206 SmallVector<LoopIterationSpace, 4> IterSpaces;
4207 IterSpaces.resize(NestedLoopCount);
4208 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004209 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004210 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004211 NestedLoopCount, CollapseLoopCountExpr,
4212 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004213 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004214 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004215 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004216 // OpenMP [2.8.1, simd construct, Restrictions]
4217 // All loops associated with the construct must be perfectly nested; that
4218 // is, there must be no intervening code nor any OpenMP directive between
4219 // any two loops.
4220 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004221 }
4222
Alexander Musmana5f070a2014-10-01 06:03:56 +00004223 Built.clear(/* size */ NestedLoopCount);
4224
4225 if (SemaRef.CurContext->isDependentContext())
4226 return NestedLoopCount;
4227
4228 // An example of what is generated for the following code:
4229 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004230 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004231 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004232 // for (k = 0; k < NK; ++k)
4233 // for (j = J0; j < NJ; j+=2) {
4234 // <loop body>
4235 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004236 //
4237 // We generate the code below.
4238 // Note: the loop body may be outlined in CodeGen.
4239 // Note: some counters may be C++ classes, operator- is used to find number of
4240 // iterations and operator+= to calculate counter value.
4241 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4242 // or i64 is currently supported).
4243 //
4244 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4245 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4246 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4247 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4248 // // similar updates for vars in clauses (e.g. 'linear')
4249 // <loop body (using local i and j)>
4250 // }
4251 // i = NI; // assign final values of counters
4252 // j = NJ;
4253 //
4254
4255 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4256 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004257 // Precondition tests if there is at least one iteration (all conditions are
4258 // true).
4259 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004260 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004261 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004262 32 /* Bits */, SemaRef
4263 .PerformImplicitConversion(
4264 N0->IgnoreImpCasts(), N0->getType(),
4265 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004266 .get(),
4267 SemaRef);
4268 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004269 64 /* Bits */, SemaRef
4270 .PerformImplicitConversion(
4271 N0->IgnoreImpCasts(), N0->getType(),
4272 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004273 .get(),
4274 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004275
4276 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4277 return NestedLoopCount;
4278
4279 auto &C = SemaRef.Context;
4280 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4281
4282 Scope *CurScope = DSA.getCurScope();
4283 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004284 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004285 PreCond =
4286 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4287 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004288 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004289 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004290 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004291 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4292 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004293 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004294 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004295 SemaRef
4296 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4297 Sema::AA_Converting,
4298 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004299 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004300 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004301 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004302 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004303 SemaRef
4304 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4305 Sema::AA_Converting,
4306 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004307 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004308 }
4309
4310 // Choose either the 32-bit or 64-bit version.
4311 ExprResult LastIteration = LastIteration64;
4312 if (LastIteration32.isUsable() &&
4313 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4314 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4315 FitsInto(
4316 32 /* Bits */,
4317 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4318 LastIteration64.get(), SemaRef)))
4319 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004320 QualType VType = LastIteration.get()->getType();
4321 QualType RealVType = VType;
4322 QualType StrideVType = VType;
4323 if (isOpenMPTaskLoopDirective(DKind)) {
4324 VType =
4325 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4326 StrideVType =
4327 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4328 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004329
4330 if (!LastIteration.isUsable())
4331 return 0;
4332
4333 // Save the number of iterations.
4334 ExprResult NumIterations = LastIteration;
4335 {
4336 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004337 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4338 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004339 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4340 if (!LastIteration.isUsable())
4341 return 0;
4342 }
4343
4344 // Calculate the last iteration number beforehand instead of doing this on
4345 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4346 llvm::APSInt Result;
4347 bool IsConstant =
4348 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4349 ExprResult CalcLastIteration;
4350 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004351 ExprResult SaveRef =
4352 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004353 LastIteration = SaveRef;
4354
4355 // Prepare SaveRef + 1.
4356 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004357 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004358 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4359 if (!NumIterations.isUsable())
4360 return 0;
4361 }
4362
4363 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4364
David Majnemer9d168222016-08-05 17:44:54 +00004365 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004366 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004367 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4368 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004369 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004370 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4371 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004372 SemaRef.AddInitializerToDecl(LBDecl,
4373 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4374 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004375
4376 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004377 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4378 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004379 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004380 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004381
4382 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4383 // This will be used to implement clause 'lastprivate'.
4384 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004385 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4386 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004387 SemaRef.AddInitializerToDecl(ILDecl,
4388 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4389 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004390
4391 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004392 VarDecl *STDecl =
4393 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4394 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004395 SemaRef.AddInitializerToDecl(STDecl,
4396 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4397 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004398
4399 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004400 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004401 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4402 UB.get(), LastIteration.get());
4403 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4404 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4405 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4406 CondOp.get());
4407 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004408
4409 // If we have a combined directive that combines 'distribute', 'for' or
4410 // 'simd' we need to be able to access the bounds of the schedule of the
4411 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4412 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4413 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004414
Carlo Bertolliffafe102017-04-20 00:39:39 +00004415 // Lower bound variable, initialized with zero.
4416 VarDecl *CombLBDecl =
4417 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4418 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4419 SemaRef.AddInitializerToDecl(
4420 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4421 /*DirectInit*/ false);
4422
4423 // Upper bound variable, initialized with last iteration number.
4424 VarDecl *CombUBDecl =
4425 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4426 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4427 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4428 /*DirectInit*/ false);
4429
4430 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4431 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4432 ExprResult CombCondOp =
4433 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4434 LastIteration.get(), CombUB.get());
4435 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4436 CombCondOp.get());
4437 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4438
4439 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004440 // We expect to have at least 2 more parameters than the 'parallel'
4441 // directive does - the lower and upper bounds of the previous schedule.
4442 assert(CD->getNumParams() >= 4 &&
4443 "Unexpected number of parameters in loop combined directive");
4444
4445 // Set the proper type for the bounds given what we learned from the
4446 // enclosed loops.
4447 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4448 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4449
4450 // Previous lower and upper bounds are obtained from the region
4451 // parameters.
4452 PrevLB =
4453 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4454 PrevUB =
4455 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4456 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004457 }
4458
4459 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004460 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004461 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004462 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004463 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4464 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004465 Expr *RHS =
4466 (isOpenMPWorksharingDirective(DKind) ||
4467 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4468 ? LB.get()
4469 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004470 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4471 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004472
4473 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4474 Expr *CombRHS =
4475 (isOpenMPWorksharingDirective(DKind) ||
4476 isOpenMPTaskLoopDirective(DKind) ||
4477 isOpenMPDistributeDirective(DKind))
4478 ? CombLB.get()
4479 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4480 CombInit =
4481 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4482 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4483 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004484 }
4485
Alexander Musmanc6388682014-12-15 07:07:06 +00004486 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004487 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004488 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004489 (isOpenMPWorksharingDirective(DKind) ||
4490 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004491 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4492 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4493 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004494 ExprResult CombCond;
4495 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4496 CombCond =
4497 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4498 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004499 // Loop increment (IV = IV + 1)
4500 SourceLocation IncLoc;
4501 ExprResult Inc =
4502 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4503 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4504 if (!Inc.isUsable())
4505 return 0;
4506 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004507 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4508 if (!Inc.isUsable())
4509 return 0;
4510
4511 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4512 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004513 // In combined construct, add combined version that use CombLB and CombUB
4514 // base variables for the update
4515 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004516 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4517 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004518 // LB + ST
4519 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4520 if (!NextLB.isUsable())
4521 return 0;
4522 // LB = LB + ST
4523 NextLB =
4524 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4525 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4526 if (!NextLB.isUsable())
4527 return 0;
4528 // UB + ST
4529 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4530 if (!NextUB.isUsable())
4531 return 0;
4532 // UB = UB + ST
4533 NextUB =
4534 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4535 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4536 if (!NextUB.isUsable())
4537 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004538 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4539 CombNextLB =
4540 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4541 if (!NextLB.isUsable())
4542 return 0;
4543 // LB = LB + ST
4544 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4545 CombNextLB.get());
4546 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4547 if (!CombNextLB.isUsable())
4548 return 0;
4549 // UB + ST
4550 CombNextUB =
4551 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4552 if (!CombNextUB.isUsable())
4553 return 0;
4554 // UB = UB + ST
4555 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4556 CombNextUB.get());
4557 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4558 if (!CombNextUB.isUsable())
4559 return 0;
4560 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004561 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004562
Carlo Bertolliffafe102017-04-20 00:39:39 +00004563 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004564 // directive with for as IV = IV + ST; ensure upper bound expression based
4565 // on PrevUB instead of NumIterations - used to implement 'for' when found
4566 // in combination with 'distribute', like in 'distribute parallel for'
4567 SourceLocation DistIncLoc;
4568 ExprResult DistCond, DistInc, PrevEUB;
4569 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4570 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4571 assert(DistCond.isUsable() && "distribute cond expr was not built");
4572
4573 DistInc =
4574 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4575 assert(DistInc.isUsable() && "distribute inc expr was not built");
4576 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4577 DistInc.get());
4578 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4579 assert(DistInc.isUsable() && "distribute inc expr was not built");
4580
4581 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4582 // construct
4583 SourceLocation DistEUBLoc;
4584 ExprResult IsUBGreater =
4585 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4586 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4587 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4588 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4589 CondOp.get());
4590 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4591 }
4592
Alexander Musmana5f070a2014-10-01 06:03:56 +00004593 // Build updates and final values of the loop counters.
4594 bool HasErrors = false;
4595 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004596 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004597 Built.Updates.resize(NestedLoopCount);
4598 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004599 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004600 {
4601 ExprResult Div;
4602 // Go from inner nested loop to outer.
4603 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4604 LoopIterationSpace &IS = IterSpaces[Cnt];
4605 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4606 // Build: Iter = (IV / Div) % IS.NumIters
4607 // where Div is product of previous iterations' IS.NumIters.
4608 ExprResult Iter;
4609 if (Div.isUsable()) {
4610 Iter =
4611 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4612 } else {
4613 Iter = IV;
4614 assert((Cnt == (int)NestedLoopCount - 1) &&
4615 "unusable div expected on first iteration only");
4616 }
4617
4618 if (Cnt != 0 && Iter.isUsable())
4619 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4620 IS.NumIterations);
4621 if (!Iter.isUsable()) {
4622 HasErrors = true;
4623 break;
4624 }
4625
Alexey Bataev39f915b82015-05-08 10:41:21 +00004626 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004627 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4628 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4629 IS.CounterVar->getExprLoc(),
4630 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004631 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004632 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004633 if (!Init.isUsable()) {
4634 HasErrors = true;
4635 break;
4636 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004637 ExprResult Update = BuildCounterUpdate(
4638 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4639 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004640 if (!Update.isUsable()) {
4641 HasErrors = true;
4642 break;
4643 }
4644
4645 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4646 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004647 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004648 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004649 if (!Final.isUsable()) {
4650 HasErrors = true;
4651 break;
4652 }
4653
4654 // Build Div for the next iteration: Div <- Div * IS.NumIters
4655 if (Cnt != 0) {
4656 if (Div.isUnset())
4657 Div = IS.NumIterations;
4658 else
4659 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4660 IS.NumIterations);
4661
4662 // Add parentheses (for debugging purposes only).
4663 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004664 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004665 if (!Div.isUsable()) {
4666 HasErrors = true;
4667 break;
4668 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004669 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004670 }
4671 if (!Update.isUsable() || !Final.isUsable()) {
4672 HasErrors = true;
4673 break;
4674 }
4675 // Save results
4676 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004677 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004678 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004679 Built.Updates[Cnt] = Update.get();
4680 Built.Finals[Cnt] = Final.get();
4681 }
4682 }
4683
4684 if (HasErrors)
4685 return 0;
4686
4687 // Save results
4688 Built.IterationVarRef = IV.get();
4689 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004690 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004691 Built.CalcLastIteration =
4692 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004693 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004694 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004695 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004696 Built.Init = Init.get();
4697 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004698 Built.LB = LB.get();
4699 Built.UB = UB.get();
4700 Built.IL = IL.get();
4701 Built.ST = ST.get();
4702 Built.EUB = EUB.get();
4703 Built.NLB = NextLB.get();
4704 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004705 Built.PrevLB = PrevLB.get();
4706 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004707 Built.DistInc = DistInc.get();
4708 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00004709 Built.DistCombinedFields.LB = CombLB.get();
4710 Built.DistCombinedFields.UB = CombUB.get();
4711 Built.DistCombinedFields.EUB = CombEUB.get();
4712 Built.DistCombinedFields.Init = CombInit.get();
4713 Built.DistCombinedFields.Cond = CombCond.get();
4714 Built.DistCombinedFields.NLB = CombNextLB.get();
4715 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004716
Alexey Bataev8b427062016-05-25 12:36:08 +00004717 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4718 // Fill data for doacross depend clauses.
4719 for (auto Pair : DSA.getDoacrossDependClauses()) {
4720 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4721 Pair.first->setCounterValue(CounterVal);
4722 else {
4723 if (NestedLoopCount != Pair.second.size() ||
4724 NestedLoopCount != LoopMultipliers.size() + 1) {
4725 // Erroneous case - clause has some problems.
4726 Pair.first->setCounterValue(CounterVal);
4727 continue;
4728 }
4729 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4730 auto I = Pair.second.rbegin();
4731 auto IS = IterSpaces.rbegin();
4732 auto ILM = LoopMultipliers.rbegin();
4733 Expr *UpCounterVal = CounterVal;
4734 Expr *Multiplier = nullptr;
4735 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4736 if (I->first) {
4737 assert(IS->CounterStep);
4738 Expr *NormalizedOffset =
4739 SemaRef
4740 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4741 I->first, IS->CounterStep)
4742 .get();
4743 if (Multiplier) {
4744 NormalizedOffset =
4745 SemaRef
4746 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4747 NormalizedOffset, Multiplier)
4748 .get();
4749 }
4750 assert(I->second == OO_Plus || I->second == OO_Minus);
4751 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004752 UpCounterVal = SemaRef
4753 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4754 UpCounterVal, NormalizedOffset)
4755 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004756 }
4757 Multiplier = *ILM;
4758 ++I;
4759 ++IS;
4760 ++ILM;
4761 }
4762 Pair.first->setCounterValue(UpCounterVal);
4763 }
4764 }
4765
Alexey Bataevabfc0692014-06-25 06:52:00 +00004766 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004767}
4768
Alexey Bataev10e775f2015-07-30 11:36:16 +00004769static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004770 auto CollapseClauses =
4771 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4772 if (CollapseClauses.begin() != CollapseClauses.end())
4773 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004774 return nullptr;
4775}
4776
Alexey Bataev10e775f2015-07-30 11:36:16 +00004777static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004778 auto OrderedClauses =
4779 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4780 if (OrderedClauses.begin() != OrderedClauses.end())
4781 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004782 return nullptr;
4783}
4784
Kelvin Lic5609492016-07-15 04:39:07 +00004785static bool checkSimdlenSafelenSpecified(Sema &S,
4786 const ArrayRef<OMPClause *> Clauses) {
4787 OMPSafelenClause *Safelen = nullptr;
4788 OMPSimdlenClause *Simdlen = nullptr;
4789
4790 for (auto *Clause : Clauses) {
4791 if (Clause->getClauseKind() == OMPC_safelen)
4792 Safelen = cast<OMPSafelenClause>(Clause);
4793 else if (Clause->getClauseKind() == OMPC_simdlen)
4794 Simdlen = cast<OMPSimdlenClause>(Clause);
4795 if (Safelen && Simdlen)
4796 break;
4797 }
4798
4799 if (Simdlen && Safelen) {
4800 llvm::APSInt SimdlenRes, SafelenRes;
4801 auto SimdlenLength = Simdlen->getSimdlen();
4802 auto SafelenLength = Safelen->getSafelen();
4803 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4804 SimdlenLength->isInstantiationDependent() ||
4805 SimdlenLength->containsUnexpandedParameterPack())
4806 return false;
4807 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4808 SafelenLength->isInstantiationDependent() ||
4809 SafelenLength->containsUnexpandedParameterPack())
4810 return false;
4811 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4812 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4813 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4814 // If both simdlen and safelen clauses are specified, the value of the
4815 // simdlen parameter must be less than or equal to the value of the safelen
4816 // parameter.
4817 if (SimdlenRes > SafelenRes) {
4818 S.Diag(SimdlenLength->getExprLoc(),
4819 diag::err_omp_wrong_simdlen_safelen_values)
4820 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4821 return true;
4822 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004823 }
4824 return false;
4825}
4826
Alexey Bataev4acb8592014-07-07 13:01:15 +00004827StmtResult Sema::ActOnOpenMPSimdDirective(
4828 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4829 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004830 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004831 if (!AStmt)
4832 return StmtError();
4833
4834 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004835 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004836 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4837 // define the nested loops number.
4838 unsigned NestedLoopCount = CheckOpenMPLoop(
4839 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4840 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004841 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004842 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004843
Alexander Musmana5f070a2014-10-01 06:03:56 +00004844 assert((CurContext->isDependentContext() || B.builtAll()) &&
4845 "omp simd loop exprs were not built");
4846
Alexander Musman3276a272015-03-21 10:12:56 +00004847 if (!CurContext->isDependentContext()) {
4848 // Finalize the clauses that need pre-built expressions for CodeGen.
4849 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004850 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004851 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004852 B.NumIterations, *this, CurScope,
4853 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004854 return StmtError();
4855 }
4856 }
4857
Kelvin Lic5609492016-07-15 04:39:07 +00004858 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004859 return StmtError();
4860
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004861 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004862 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4863 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004864}
4865
Alexey Bataev4acb8592014-07-07 13:01:15 +00004866StmtResult Sema::ActOnOpenMPForDirective(
4867 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4868 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004869 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004870 if (!AStmt)
4871 return StmtError();
4872
4873 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004874 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004875 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4876 // define the nested loops number.
4877 unsigned NestedLoopCount = CheckOpenMPLoop(
4878 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4879 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004880 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004881 return StmtError();
4882
Alexander Musmana5f070a2014-10-01 06:03:56 +00004883 assert((CurContext->isDependentContext() || B.builtAll()) &&
4884 "omp for loop exprs were not built");
4885
Alexey Bataev54acd402015-08-04 11:18:19 +00004886 if (!CurContext->isDependentContext()) {
4887 // Finalize the clauses that need pre-built expressions for CodeGen.
4888 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004889 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004890 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004891 B.NumIterations, *this, CurScope,
4892 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004893 return StmtError();
4894 }
4895 }
4896
Alexey Bataevf29276e2014-06-18 04:14:57 +00004897 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004898 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004899 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004900}
4901
Alexander Musmanf82886e2014-09-18 05:12:34 +00004902StmtResult Sema::ActOnOpenMPForSimdDirective(
4903 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4904 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004905 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004906 if (!AStmt)
4907 return StmtError();
4908
4909 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004910 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004911 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4912 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004913 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004914 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4915 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4916 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004917 if (NestedLoopCount == 0)
4918 return StmtError();
4919
Alexander Musmanc6388682014-12-15 07:07:06 +00004920 assert((CurContext->isDependentContext() || B.builtAll()) &&
4921 "omp for simd loop exprs were not built");
4922
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004923 if (!CurContext->isDependentContext()) {
4924 // Finalize the clauses that need pre-built expressions for CodeGen.
4925 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004926 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004927 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004928 B.NumIterations, *this, CurScope,
4929 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004930 return StmtError();
4931 }
4932 }
4933
Kelvin Lic5609492016-07-15 04:39:07 +00004934 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004935 return StmtError();
4936
Alexander Musmanf82886e2014-09-18 05:12:34 +00004937 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004938 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4939 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004940}
4941
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004942StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4943 Stmt *AStmt,
4944 SourceLocation StartLoc,
4945 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004946 if (!AStmt)
4947 return StmtError();
4948
4949 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004950 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004951 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004952 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004953 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004954 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004955 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004956 return StmtError();
4957 // All associated statements must be '#pragma omp section' except for
4958 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004959 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004960 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4961 if (SectionStmt)
4962 Diag(SectionStmt->getLocStart(),
4963 diag::err_omp_sections_substmt_not_section);
4964 return StmtError();
4965 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004966 cast<OMPSectionDirective>(SectionStmt)
4967 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004968 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004969 } else {
4970 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4971 return StmtError();
4972 }
4973
4974 getCurFunction()->setHasBranchProtectedScope();
4975
Alexey Bataev25e5b442015-09-15 12:52:43 +00004976 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4977 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004978}
4979
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004980StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4981 SourceLocation StartLoc,
4982 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004983 if (!AStmt)
4984 return StmtError();
4985
4986 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004987
4988 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004989 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004990
Alexey Bataev25e5b442015-09-15 12:52:43 +00004991 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4992 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004993}
4994
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004995StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4996 Stmt *AStmt,
4997 SourceLocation StartLoc,
4998 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004999 if (!AStmt)
5000 return StmtError();
5001
5002 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005003
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005004 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005005
Alexey Bataev3255bf32015-01-19 05:20:46 +00005006 // OpenMP [2.7.3, single Construct, Restrictions]
5007 // The copyprivate clause must not be used with the nowait clause.
5008 OMPClause *Nowait = nullptr;
5009 OMPClause *Copyprivate = nullptr;
5010 for (auto *Clause : Clauses) {
5011 if (Clause->getClauseKind() == OMPC_nowait)
5012 Nowait = Clause;
5013 else if (Clause->getClauseKind() == OMPC_copyprivate)
5014 Copyprivate = Clause;
5015 if (Copyprivate && Nowait) {
5016 Diag(Copyprivate->getLocStart(),
5017 diag::err_omp_single_copyprivate_with_nowait);
5018 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5019 return StmtError();
5020 }
5021 }
5022
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005023 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5024}
5025
Alexander Musman80c22892014-07-17 08:54:58 +00005026StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5027 SourceLocation StartLoc,
5028 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005029 if (!AStmt)
5030 return StmtError();
5031
5032 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005033
5034 getCurFunction()->setHasBranchProtectedScope();
5035
5036 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5037}
5038
Alexey Bataev28c75412015-12-15 08:19:24 +00005039StmtResult Sema::ActOnOpenMPCriticalDirective(
5040 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5041 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005042 if (!AStmt)
5043 return StmtError();
5044
5045 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005046
Alexey Bataev28c75412015-12-15 08:19:24 +00005047 bool ErrorFound = false;
5048 llvm::APSInt Hint;
5049 SourceLocation HintLoc;
5050 bool DependentHint = false;
5051 for (auto *C : Clauses) {
5052 if (C->getClauseKind() == OMPC_hint) {
5053 if (!DirName.getName()) {
5054 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5055 ErrorFound = true;
5056 }
5057 Expr *E = cast<OMPHintClause>(C)->getHint();
5058 if (E->isTypeDependent() || E->isValueDependent() ||
5059 E->isInstantiationDependent())
5060 DependentHint = true;
5061 else {
5062 Hint = E->EvaluateKnownConstInt(Context);
5063 HintLoc = C->getLocStart();
5064 }
5065 }
5066 }
5067 if (ErrorFound)
5068 return StmtError();
5069 auto Pair = DSAStack->getCriticalWithHint(DirName);
5070 if (Pair.first && DirName.getName() && !DependentHint) {
5071 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5072 Diag(StartLoc, diag::err_omp_critical_with_hint);
5073 if (HintLoc.isValid()) {
5074 Diag(HintLoc, diag::note_omp_critical_hint_here)
5075 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5076 } else
5077 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5078 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5079 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5080 << 1
5081 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5082 /*Radix=*/10, /*Signed=*/false);
5083 } else
5084 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5085 }
5086 }
5087
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005088 getCurFunction()->setHasBranchProtectedScope();
5089
Alexey Bataev28c75412015-12-15 08:19:24 +00005090 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5091 Clauses, AStmt);
5092 if (!Pair.first && DirName.getName() && !DependentHint)
5093 DSAStack->addCriticalWithHint(Dir, Hint);
5094 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005095}
5096
Alexey Bataev4acb8592014-07-07 13:01:15 +00005097StmtResult Sema::ActOnOpenMPParallelForDirective(
5098 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5099 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005100 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005101 if (!AStmt)
5102 return StmtError();
5103
Alexey Bataev4acb8592014-07-07 13:01:15 +00005104 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5105 // 1.2.2 OpenMP Language Terminology
5106 // Structured block - An executable statement with a single entry at the
5107 // top and a single exit at the bottom.
5108 // The point of exit cannot be a branch out of the structured block.
5109 // longjmp() and throw() must not violate the entry/exit criteria.
5110 CS->getCapturedDecl()->setNothrow();
5111
Alexander Musmanc6388682014-12-15 07:07:06 +00005112 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005113 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5114 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005115 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005116 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5117 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5118 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005119 if (NestedLoopCount == 0)
5120 return StmtError();
5121
Alexander Musmana5f070a2014-10-01 06:03:56 +00005122 assert((CurContext->isDependentContext() || B.builtAll()) &&
5123 "omp parallel for loop exprs were not built");
5124
Alexey Bataev54acd402015-08-04 11:18:19 +00005125 if (!CurContext->isDependentContext()) {
5126 // Finalize the clauses that need pre-built expressions for CodeGen.
5127 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005128 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005129 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005130 B.NumIterations, *this, CurScope,
5131 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005132 return StmtError();
5133 }
5134 }
5135
Alexey Bataev4acb8592014-07-07 13:01:15 +00005136 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005137 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005138 NestedLoopCount, Clauses, AStmt, B,
5139 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005140}
5141
Alexander Musmane4e893b2014-09-23 09:33:00 +00005142StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5143 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5144 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005145 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005146 if (!AStmt)
5147 return StmtError();
5148
Alexander Musmane4e893b2014-09-23 09:33:00 +00005149 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5150 // 1.2.2 OpenMP Language Terminology
5151 // Structured block - An executable statement with a single entry at the
5152 // top and a single exit at the bottom.
5153 // The point of exit cannot be a branch out of the structured block.
5154 // longjmp() and throw() must not violate the entry/exit criteria.
5155 CS->getCapturedDecl()->setNothrow();
5156
Alexander Musmanc6388682014-12-15 07:07:06 +00005157 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005158 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5159 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005160 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005161 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5162 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5163 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005164 if (NestedLoopCount == 0)
5165 return StmtError();
5166
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005167 if (!CurContext->isDependentContext()) {
5168 // Finalize the clauses that need pre-built expressions for CodeGen.
5169 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005170 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005171 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005172 B.NumIterations, *this, CurScope,
5173 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005174 return StmtError();
5175 }
5176 }
5177
Kelvin Lic5609492016-07-15 04:39:07 +00005178 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005179 return StmtError();
5180
Alexander Musmane4e893b2014-09-23 09:33:00 +00005181 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005182 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005183 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005184}
5185
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005186StmtResult
5187Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5188 Stmt *AStmt, SourceLocation StartLoc,
5189 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005190 if (!AStmt)
5191 return StmtError();
5192
5193 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005194 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005195 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005196 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005197 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005198 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005199 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005200 return StmtError();
5201 // All associated statements must be '#pragma omp section' except for
5202 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005203 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005204 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5205 if (SectionStmt)
5206 Diag(SectionStmt->getLocStart(),
5207 diag::err_omp_parallel_sections_substmt_not_section);
5208 return StmtError();
5209 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005210 cast<OMPSectionDirective>(SectionStmt)
5211 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005212 }
5213 } else {
5214 Diag(AStmt->getLocStart(),
5215 diag::err_omp_parallel_sections_not_compound_stmt);
5216 return StmtError();
5217 }
5218
5219 getCurFunction()->setHasBranchProtectedScope();
5220
Alexey Bataev25e5b442015-09-15 12:52:43 +00005221 return OMPParallelSectionsDirective::Create(
5222 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005223}
5224
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005225StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5226 Stmt *AStmt, SourceLocation StartLoc,
5227 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005228 if (!AStmt)
5229 return StmtError();
5230
David Majnemer9d168222016-08-05 17:44:54 +00005231 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005232 // 1.2.2 OpenMP Language Terminology
5233 // Structured block - An executable statement with a single entry at the
5234 // top and a single exit at the bottom.
5235 // The point of exit cannot be a branch out of the structured block.
5236 // longjmp() and throw() must not violate the entry/exit criteria.
5237 CS->getCapturedDecl()->setNothrow();
5238
5239 getCurFunction()->setHasBranchProtectedScope();
5240
Alexey Bataev25e5b442015-09-15 12:52:43 +00005241 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5242 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005243}
5244
Alexey Bataev68446b72014-07-18 07:47:19 +00005245StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5246 SourceLocation EndLoc) {
5247 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5248}
5249
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005250StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5251 SourceLocation EndLoc) {
5252 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5253}
5254
Alexey Bataev2df347a2014-07-18 10:17:07 +00005255StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5256 SourceLocation EndLoc) {
5257 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5258}
5259
Alexey Bataev169d96a2017-07-18 20:17:46 +00005260StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5261 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005262 SourceLocation StartLoc,
5263 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005264 if (!AStmt)
5265 return StmtError();
5266
5267 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005268
5269 getCurFunction()->setHasBranchProtectedScope();
5270
Alexey Bataev169d96a2017-07-18 20:17:46 +00005271 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005272 AStmt,
5273 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005274}
5275
Alexey Bataev6125da92014-07-21 11:26:11 +00005276StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5277 SourceLocation StartLoc,
5278 SourceLocation EndLoc) {
5279 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5280 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5281}
5282
Alexey Bataev346265e2015-09-25 10:37:12 +00005283StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5284 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005285 SourceLocation StartLoc,
5286 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005287 OMPClause *DependFound = nullptr;
5288 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005289 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005290 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005291 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005292 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005293 for (auto *C : Clauses) {
5294 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5295 DependFound = C;
5296 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5297 if (DependSourceClause) {
5298 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5299 << getOpenMPDirectiveName(OMPD_ordered)
5300 << getOpenMPClauseName(OMPC_depend) << 2;
5301 ErrorFound = true;
5302 } else
5303 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005304 if (DependSinkClause) {
5305 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5306 << 0;
5307 ErrorFound = true;
5308 }
5309 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5310 if (DependSourceClause) {
5311 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5312 << 1;
5313 ErrorFound = true;
5314 }
5315 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005316 }
5317 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005318 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005319 else if (C->getClauseKind() == OMPC_simd)
5320 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005321 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005322 if (!ErrorFound && !SC &&
5323 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005324 // OpenMP [2.8.1,simd Construct, Restrictions]
5325 // An ordered construct with the simd clause is the only OpenMP construct
5326 // that can appear in the simd region.
5327 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005328 ErrorFound = true;
5329 } else if (DependFound && (TC || SC)) {
5330 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5331 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5332 ErrorFound = true;
5333 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5334 Diag(DependFound->getLocStart(),
5335 diag::err_omp_ordered_directive_without_param);
5336 ErrorFound = true;
5337 } else if (TC || Clauses.empty()) {
5338 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5339 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5340 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5341 << (TC != nullptr);
5342 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5343 ErrorFound = true;
5344 }
5345 }
5346 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005347 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005348
5349 if (AStmt) {
5350 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5351
5352 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005353 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005354
5355 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005356}
5357
Alexey Bataev1d160b12015-03-13 12:27:31 +00005358namespace {
5359/// \brief Helper class for checking expression in 'omp atomic [update]'
5360/// construct.
5361class OpenMPAtomicUpdateChecker {
5362 /// \brief Error results for atomic update expressions.
5363 enum ExprAnalysisErrorCode {
5364 /// \brief A statement is not an expression statement.
5365 NotAnExpression,
5366 /// \brief Expression is not builtin binary or unary operation.
5367 NotABinaryOrUnaryExpression,
5368 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5369 NotAnUnaryIncDecExpression,
5370 /// \brief An expression is not of scalar type.
5371 NotAScalarType,
5372 /// \brief A binary operation is not an assignment operation.
5373 NotAnAssignmentOp,
5374 /// \brief RHS part of the binary operation is not a binary expression.
5375 NotABinaryExpression,
5376 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5377 /// expression.
5378 NotABinaryOperator,
5379 /// \brief RHS binary operation does not have reference to the updated LHS
5380 /// part.
5381 NotAnUpdateExpression,
5382 /// \brief No errors is found.
5383 NoError
5384 };
5385 /// \brief Reference to Sema.
5386 Sema &SemaRef;
5387 /// \brief A location for note diagnostics (when error is found).
5388 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005389 /// \brief 'x' lvalue part of the source atomic expression.
5390 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005391 /// \brief 'expr' rvalue part of the source atomic expression.
5392 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005393 /// \brief Helper expression of the form
5394 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5395 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5396 Expr *UpdateExpr;
5397 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5398 /// important for non-associative operations.
5399 bool IsXLHSInRHSPart;
5400 BinaryOperatorKind Op;
5401 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005402 /// \brief true if the source expression is a postfix unary operation, false
5403 /// if it is a prefix unary operation.
5404 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005405
5406public:
5407 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005408 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005409 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005410 /// \brief Check specified statement that it is suitable for 'atomic update'
5411 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005412 /// expression. If DiagId and NoteId == 0, then only check is performed
5413 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005414 /// \param DiagId Diagnostic which should be emitted if error is found.
5415 /// \param NoteId Diagnostic note for the main error message.
5416 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005417 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005418 /// \brief Return the 'x' lvalue part of the source atomic expression.
5419 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005420 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5421 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005422 /// \brief Return the update expression used in calculation of the updated
5423 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5424 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5425 Expr *getUpdateExpr() const { return UpdateExpr; }
5426 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5427 /// false otherwise.
5428 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5429
Alexey Bataevb78ca832015-04-01 03:33:17 +00005430 /// \brief true if the source expression is a postfix unary operation, false
5431 /// if it is a prefix unary operation.
5432 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5433
Alexey Bataev1d160b12015-03-13 12:27:31 +00005434private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005435 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5436 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005437};
5438} // namespace
5439
5440bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5441 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5442 ExprAnalysisErrorCode ErrorFound = NoError;
5443 SourceLocation ErrorLoc, NoteLoc;
5444 SourceRange ErrorRange, NoteRange;
5445 // Allowed constructs are:
5446 // x = x binop expr;
5447 // x = expr binop x;
5448 if (AtomicBinOp->getOpcode() == BO_Assign) {
5449 X = AtomicBinOp->getLHS();
5450 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5451 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5452 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5453 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5454 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005455 Op = AtomicInnerBinOp->getOpcode();
5456 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005457 auto *LHS = AtomicInnerBinOp->getLHS();
5458 auto *RHS = AtomicInnerBinOp->getRHS();
5459 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5460 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5461 /*Canonical=*/true);
5462 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5463 /*Canonical=*/true);
5464 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5465 /*Canonical=*/true);
5466 if (XId == LHSId) {
5467 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005468 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005469 } else if (XId == RHSId) {
5470 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005471 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005472 } else {
5473 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5474 ErrorRange = AtomicInnerBinOp->getSourceRange();
5475 NoteLoc = X->getExprLoc();
5476 NoteRange = X->getSourceRange();
5477 ErrorFound = NotAnUpdateExpression;
5478 }
5479 } else {
5480 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5481 ErrorRange = AtomicInnerBinOp->getSourceRange();
5482 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5483 NoteRange = SourceRange(NoteLoc, NoteLoc);
5484 ErrorFound = NotABinaryOperator;
5485 }
5486 } else {
5487 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5488 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5489 ErrorFound = NotABinaryExpression;
5490 }
5491 } else {
5492 ErrorLoc = AtomicBinOp->getExprLoc();
5493 ErrorRange = AtomicBinOp->getSourceRange();
5494 NoteLoc = AtomicBinOp->getOperatorLoc();
5495 NoteRange = SourceRange(NoteLoc, NoteLoc);
5496 ErrorFound = NotAnAssignmentOp;
5497 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005498 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005499 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5500 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5501 return true;
5502 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005503 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005504 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005505}
5506
5507bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5508 unsigned NoteId) {
5509 ExprAnalysisErrorCode ErrorFound = NoError;
5510 SourceLocation ErrorLoc, NoteLoc;
5511 SourceRange ErrorRange, NoteRange;
5512 // Allowed constructs are:
5513 // x++;
5514 // x--;
5515 // ++x;
5516 // --x;
5517 // x binop= expr;
5518 // x = x binop expr;
5519 // x = expr binop x;
5520 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5521 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5522 if (AtomicBody->getType()->isScalarType() ||
5523 AtomicBody->isInstantiationDependent()) {
5524 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5525 AtomicBody->IgnoreParenImpCasts())) {
5526 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005527 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005528 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005529 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005530 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005531 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005532 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005533 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5534 AtomicBody->IgnoreParenImpCasts())) {
5535 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005536 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005537 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005538 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5539 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005540 // Check for Unary Operation
5541 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005542 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005543 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5544 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005545 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005546 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5547 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005548 } else {
5549 ErrorFound = NotAnUnaryIncDecExpression;
5550 ErrorLoc = AtomicUnaryOp->getExprLoc();
5551 ErrorRange = AtomicUnaryOp->getSourceRange();
5552 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5553 NoteRange = SourceRange(NoteLoc, NoteLoc);
5554 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005555 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005556 ErrorFound = NotABinaryOrUnaryExpression;
5557 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5558 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5559 }
5560 } else {
5561 ErrorFound = NotAScalarType;
5562 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5563 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5564 }
5565 } else {
5566 ErrorFound = NotAnExpression;
5567 NoteLoc = ErrorLoc = S->getLocStart();
5568 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5569 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005570 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005571 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5572 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5573 return true;
5574 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005575 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005576 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005577 // Build an update expression of form 'OpaqueValueExpr(x) binop
5578 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5579 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5580 auto *OVEX = new (SemaRef.getASTContext())
5581 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5582 auto *OVEExpr = new (SemaRef.getASTContext())
5583 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5584 auto Update =
5585 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5586 IsXLHSInRHSPart ? OVEExpr : OVEX);
5587 if (Update.isInvalid())
5588 return true;
5589 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5590 Sema::AA_Casting);
5591 if (Update.isInvalid())
5592 return true;
5593 UpdateExpr = Update.get();
5594 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005595 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005596}
5597
Alexey Bataev0162e452014-07-22 10:10:35 +00005598StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5599 Stmt *AStmt,
5600 SourceLocation StartLoc,
5601 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005602 if (!AStmt)
5603 return StmtError();
5604
David Majnemer9d168222016-08-05 17:44:54 +00005605 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005606 // 1.2.2 OpenMP Language Terminology
5607 // Structured block - An executable statement with a single entry at the
5608 // top and a single exit at the bottom.
5609 // The point of exit cannot be a branch out of the structured block.
5610 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005611 OpenMPClauseKind AtomicKind = OMPC_unknown;
5612 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005613 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005614 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005615 C->getClauseKind() == OMPC_update ||
5616 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005617 if (AtomicKind != OMPC_unknown) {
5618 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5619 << SourceRange(C->getLocStart(), C->getLocEnd());
5620 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5621 << getOpenMPClauseName(AtomicKind);
5622 } else {
5623 AtomicKind = C->getClauseKind();
5624 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005625 }
5626 }
5627 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005628
Alexey Bataev459dec02014-07-24 06:46:57 +00005629 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005630 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5631 Body = EWC->getSubExpr();
5632
Alexey Bataev62cec442014-11-18 10:14:22 +00005633 Expr *X = nullptr;
5634 Expr *V = nullptr;
5635 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005636 Expr *UE = nullptr;
5637 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005638 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005639 // OpenMP [2.12.6, atomic Construct]
5640 // In the next expressions:
5641 // * x and v (as applicable) are both l-value expressions with scalar type.
5642 // * During the execution of an atomic region, multiple syntactic
5643 // occurrences of x must designate the same storage location.
5644 // * Neither of v and expr (as applicable) may access the storage location
5645 // designated by x.
5646 // * Neither of x and expr (as applicable) may access the storage location
5647 // designated by v.
5648 // * expr is an expression with scalar type.
5649 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5650 // * binop, binop=, ++, and -- are not overloaded operators.
5651 // * The expression x binop expr must be numerically equivalent to x binop
5652 // (expr). This requirement is satisfied if the operators in expr have
5653 // precedence greater than binop, or by using parentheses around expr or
5654 // subexpressions of expr.
5655 // * The expression expr binop x must be numerically equivalent to (expr)
5656 // binop x. This requirement is satisfied if the operators in expr have
5657 // precedence equal to or greater than binop, or by using parentheses around
5658 // expr or subexpressions of expr.
5659 // * For forms that allow multiple occurrences of x, the number of times
5660 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005661 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005662 enum {
5663 NotAnExpression,
5664 NotAnAssignmentOp,
5665 NotAScalarType,
5666 NotAnLValue,
5667 NoError
5668 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005669 SourceLocation ErrorLoc, NoteLoc;
5670 SourceRange ErrorRange, NoteRange;
5671 // If clause is read:
5672 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005673 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5674 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005675 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5676 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5677 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5678 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5679 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5680 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5681 if (!X->isLValue() || !V->isLValue()) {
5682 auto NotLValueExpr = X->isLValue() ? V : X;
5683 ErrorFound = NotAnLValue;
5684 ErrorLoc = AtomicBinOp->getExprLoc();
5685 ErrorRange = AtomicBinOp->getSourceRange();
5686 NoteLoc = NotLValueExpr->getExprLoc();
5687 NoteRange = NotLValueExpr->getSourceRange();
5688 }
5689 } else if (!X->isInstantiationDependent() ||
5690 !V->isInstantiationDependent()) {
5691 auto NotScalarExpr =
5692 (X->isInstantiationDependent() || X->getType()->isScalarType())
5693 ? V
5694 : X;
5695 ErrorFound = NotAScalarType;
5696 ErrorLoc = AtomicBinOp->getExprLoc();
5697 ErrorRange = AtomicBinOp->getSourceRange();
5698 NoteLoc = NotScalarExpr->getExprLoc();
5699 NoteRange = NotScalarExpr->getSourceRange();
5700 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005701 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005702 ErrorFound = NotAnAssignmentOp;
5703 ErrorLoc = AtomicBody->getExprLoc();
5704 ErrorRange = AtomicBody->getSourceRange();
5705 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5706 : AtomicBody->getExprLoc();
5707 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5708 : AtomicBody->getSourceRange();
5709 }
5710 } else {
5711 ErrorFound = NotAnExpression;
5712 NoteLoc = ErrorLoc = Body->getLocStart();
5713 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005714 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005715 if (ErrorFound != NoError) {
5716 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5717 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005718 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5719 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005720 return StmtError();
5721 } else if (CurContext->isDependentContext())
5722 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005723 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005724 enum {
5725 NotAnExpression,
5726 NotAnAssignmentOp,
5727 NotAScalarType,
5728 NotAnLValue,
5729 NoError
5730 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005731 SourceLocation ErrorLoc, NoteLoc;
5732 SourceRange ErrorRange, NoteRange;
5733 // If clause is write:
5734 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005735 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5736 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005737 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5738 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005739 X = AtomicBinOp->getLHS();
5740 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005741 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5742 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5743 if (!X->isLValue()) {
5744 ErrorFound = NotAnLValue;
5745 ErrorLoc = AtomicBinOp->getExprLoc();
5746 ErrorRange = AtomicBinOp->getSourceRange();
5747 NoteLoc = X->getExprLoc();
5748 NoteRange = X->getSourceRange();
5749 }
5750 } else if (!X->isInstantiationDependent() ||
5751 !E->isInstantiationDependent()) {
5752 auto NotScalarExpr =
5753 (X->isInstantiationDependent() || X->getType()->isScalarType())
5754 ? E
5755 : X;
5756 ErrorFound = NotAScalarType;
5757 ErrorLoc = AtomicBinOp->getExprLoc();
5758 ErrorRange = AtomicBinOp->getSourceRange();
5759 NoteLoc = NotScalarExpr->getExprLoc();
5760 NoteRange = NotScalarExpr->getSourceRange();
5761 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005762 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005763 ErrorFound = NotAnAssignmentOp;
5764 ErrorLoc = AtomicBody->getExprLoc();
5765 ErrorRange = AtomicBody->getSourceRange();
5766 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5767 : AtomicBody->getExprLoc();
5768 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5769 : AtomicBody->getSourceRange();
5770 }
5771 } else {
5772 ErrorFound = NotAnExpression;
5773 NoteLoc = ErrorLoc = Body->getLocStart();
5774 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005775 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005776 if (ErrorFound != NoError) {
5777 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5778 << ErrorRange;
5779 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5780 << NoteRange;
5781 return StmtError();
5782 } else if (CurContext->isDependentContext())
5783 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005784 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005785 // If clause is update:
5786 // x++;
5787 // x--;
5788 // ++x;
5789 // --x;
5790 // x binop= expr;
5791 // x = x binop expr;
5792 // x = expr binop x;
5793 OpenMPAtomicUpdateChecker Checker(*this);
5794 if (Checker.checkStatement(
5795 Body, (AtomicKind == OMPC_update)
5796 ? diag::err_omp_atomic_update_not_expression_statement
5797 : diag::err_omp_atomic_not_expression_statement,
5798 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005799 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005800 if (!CurContext->isDependentContext()) {
5801 E = Checker.getExpr();
5802 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005803 UE = Checker.getUpdateExpr();
5804 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005805 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005806 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005807 enum {
5808 NotAnAssignmentOp,
5809 NotACompoundStatement,
5810 NotTwoSubstatements,
5811 NotASpecificExpression,
5812 NoError
5813 } ErrorFound = NoError;
5814 SourceLocation ErrorLoc, NoteLoc;
5815 SourceRange ErrorRange, NoteRange;
5816 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5817 // If clause is a capture:
5818 // v = x++;
5819 // v = x--;
5820 // v = ++x;
5821 // v = --x;
5822 // v = x binop= expr;
5823 // v = x = x binop expr;
5824 // v = x = expr binop x;
5825 auto *AtomicBinOp =
5826 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5827 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5828 V = AtomicBinOp->getLHS();
5829 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5830 OpenMPAtomicUpdateChecker Checker(*this);
5831 if (Checker.checkStatement(
5832 Body, diag::err_omp_atomic_capture_not_expression_statement,
5833 diag::note_omp_atomic_update))
5834 return StmtError();
5835 E = Checker.getExpr();
5836 X = Checker.getX();
5837 UE = Checker.getUpdateExpr();
5838 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5839 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005840 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005841 ErrorLoc = AtomicBody->getExprLoc();
5842 ErrorRange = AtomicBody->getSourceRange();
5843 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5844 : AtomicBody->getExprLoc();
5845 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5846 : AtomicBody->getSourceRange();
5847 ErrorFound = NotAnAssignmentOp;
5848 }
5849 if (ErrorFound != NoError) {
5850 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5851 << ErrorRange;
5852 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5853 return StmtError();
5854 } else if (CurContext->isDependentContext()) {
5855 UE = V = E = X = nullptr;
5856 }
5857 } else {
5858 // If clause is a capture:
5859 // { v = x; x = expr; }
5860 // { v = x; x++; }
5861 // { v = x; x--; }
5862 // { v = x; ++x; }
5863 // { v = x; --x; }
5864 // { v = x; x binop= expr; }
5865 // { v = x; x = x binop expr; }
5866 // { v = x; x = expr binop x; }
5867 // { x++; v = x; }
5868 // { x--; v = x; }
5869 // { ++x; v = x; }
5870 // { --x; v = x; }
5871 // { x binop= expr; v = x; }
5872 // { x = x binop expr; v = x; }
5873 // { x = expr binop x; v = x; }
5874 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5875 // Check that this is { expr1; expr2; }
5876 if (CS->size() == 2) {
5877 auto *First = CS->body_front();
5878 auto *Second = CS->body_back();
5879 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5880 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5881 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5882 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5883 // Need to find what subexpression is 'v' and what is 'x'.
5884 OpenMPAtomicUpdateChecker Checker(*this);
5885 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5886 BinaryOperator *BinOp = nullptr;
5887 if (IsUpdateExprFound) {
5888 BinOp = dyn_cast<BinaryOperator>(First);
5889 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5890 }
5891 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5892 // { v = x; x++; }
5893 // { v = x; x--; }
5894 // { v = x; ++x; }
5895 // { v = x; --x; }
5896 // { v = x; x binop= expr; }
5897 // { v = x; x = x binop expr; }
5898 // { v = x; x = expr binop x; }
5899 // Check that the first expression has form v = x.
5900 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5901 llvm::FoldingSetNodeID XId, PossibleXId;
5902 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5903 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5904 IsUpdateExprFound = XId == PossibleXId;
5905 if (IsUpdateExprFound) {
5906 V = BinOp->getLHS();
5907 X = Checker.getX();
5908 E = Checker.getExpr();
5909 UE = Checker.getUpdateExpr();
5910 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005911 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005912 }
5913 }
5914 if (!IsUpdateExprFound) {
5915 IsUpdateExprFound = !Checker.checkStatement(First);
5916 BinOp = nullptr;
5917 if (IsUpdateExprFound) {
5918 BinOp = dyn_cast<BinaryOperator>(Second);
5919 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5920 }
5921 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5922 // { x++; v = x; }
5923 // { x--; v = x; }
5924 // { ++x; v = x; }
5925 // { --x; v = x; }
5926 // { x binop= expr; v = x; }
5927 // { x = x binop expr; v = x; }
5928 // { x = expr binop x; v = x; }
5929 // Check that the second expression has form v = x.
5930 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5931 llvm::FoldingSetNodeID XId, PossibleXId;
5932 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5933 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5934 IsUpdateExprFound = XId == PossibleXId;
5935 if (IsUpdateExprFound) {
5936 V = BinOp->getLHS();
5937 X = Checker.getX();
5938 E = Checker.getExpr();
5939 UE = Checker.getUpdateExpr();
5940 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005941 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005942 }
5943 }
5944 }
5945 if (!IsUpdateExprFound) {
5946 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005947 auto *FirstExpr = dyn_cast<Expr>(First);
5948 auto *SecondExpr = dyn_cast<Expr>(Second);
5949 if (!FirstExpr || !SecondExpr ||
5950 !(FirstExpr->isInstantiationDependent() ||
5951 SecondExpr->isInstantiationDependent())) {
5952 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5953 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005954 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005955 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5956 : First->getLocStart();
5957 NoteRange = ErrorRange = FirstBinOp
5958 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005959 : SourceRange(ErrorLoc, ErrorLoc);
5960 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005961 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5962 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5963 ErrorFound = NotAnAssignmentOp;
5964 NoteLoc = ErrorLoc = SecondBinOp
5965 ? SecondBinOp->getOperatorLoc()
5966 : Second->getLocStart();
5967 NoteRange = ErrorRange =
5968 SecondBinOp ? SecondBinOp->getSourceRange()
5969 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005970 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005971 auto *PossibleXRHSInFirst =
5972 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5973 auto *PossibleXLHSInSecond =
5974 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5975 llvm::FoldingSetNodeID X1Id, X2Id;
5976 PossibleXRHSInFirst->Profile(X1Id, Context,
5977 /*Canonical=*/true);
5978 PossibleXLHSInSecond->Profile(X2Id, Context,
5979 /*Canonical=*/true);
5980 IsUpdateExprFound = X1Id == X2Id;
5981 if (IsUpdateExprFound) {
5982 V = FirstBinOp->getLHS();
5983 X = SecondBinOp->getLHS();
5984 E = SecondBinOp->getRHS();
5985 UE = nullptr;
5986 IsXLHSInRHSPart = false;
5987 IsPostfixUpdate = true;
5988 } else {
5989 ErrorFound = NotASpecificExpression;
5990 ErrorLoc = FirstBinOp->getExprLoc();
5991 ErrorRange = FirstBinOp->getSourceRange();
5992 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5993 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5994 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005995 }
5996 }
5997 }
5998 }
5999 } else {
6000 NoteLoc = ErrorLoc = Body->getLocStart();
6001 NoteRange = ErrorRange =
6002 SourceRange(Body->getLocStart(), Body->getLocStart());
6003 ErrorFound = NotTwoSubstatements;
6004 }
6005 } else {
6006 NoteLoc = ErrorLoc = Body->getLocStart();
6007 NoteRange = ErrorRange =
6008 SourceRange(Body->getLocStart(), Body->getLocStart());
6009 ErrorFound = NotACompoundStatement;
6010 }
6011 if (ErrorFound != NoError) {
6012 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6013 << ErrorRange;
6014 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6015 return StmtError();
6016 } else if (CurContext->isDependentContext()) {
6017 UE = V = E = X = nullptr;
6018 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006019 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006020 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006021
6022 getCurFunction()->setHasBranchProtectedScope();
6023
Alexey Bataev62cec442014-11-18 10:14:22 +00006024 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006025 X, V, E, UE, IsXLHSInRHSPart,
6026 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006027}
6028
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006029StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6030 Stmt *AStmt,
6031 SourceLocation StartLoc,
6032 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006033 if (!AStmt)
6034 return StmtError();
6035
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006036 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6037 // 1.2.2 OpenMP Language Terminology
6038 // Structured block - An executable statement with a single entry at the
6039 // top and a single exit at the bottom.
6040 // The point of exit cannot be a branch out of the structured block.
6041 // longjmp() and throw() must not violate the entry/exit criteria.
6042 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006043
Alexey Bataev13314bf2014-10-09 04:18:56 +00006044 // OpenMP [2.16, Nesting of Regions]
6045 // If specified, a teams construct must be contained within a target
6046 // construct. That target construct must contain no statements or directives
6047 // outside of the teams construct.
6048 if (DSAStack->hasInnerTeamsRegion()) {
6049 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
6050 bool OMPTeamsFound = true;
6051 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6052 auto I = CS->body_begin();
6053 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006054 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006055 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6056 OMPTeamsFound = false;
6057 break;
6058 }
6059 ++I;
6060 }
6061 assert(I != CS->body_end() && "Not found statement");
6062 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006063 } else {
6064 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6065 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006066 }
6067 if (!OMPTeamsFound) {
6068 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6069 Diag(DSAStack->getInnerTeamsRegionLoc(),
6070 diag::note_omp_nested_teams_construct_here);
6071 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6072 << isa<OMPExecutableDirective>(S);
6073 return StmtError();
6074 }
6075 }
6076
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006077 getCurFunction()->setHasBranchProtectedScope();
6078
6079 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6080}
6081
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006082StmtResult
6083Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6084 Stmt *AStmt, SourceLocation StartLoc,
6085 SourceLocation EndLoc) {
6086 if (!AStmt)
6087 return StmtError();
6088
6089 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6090 // 1.2.2 OpenMP Language Terminology
6091 // Structured block - An executable statement with a single entry at the
6092 // top and a single exit at the bottom.
6093 // The point of exit cannot be a branch out of the structured block.
6094 // longjmp() and throw() must not violate the entry/exit criteria.
6095 CS->getCapturedDecl()->setNothrow();
6096
6097 getCurFunction()->setHasBranchProtectedScope();
6098
6099 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6100 AStmt);
6101}
6102
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006103StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6104 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6105 SourceLocation EndLoc,
6106 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6107 if (!AStmt)
6108 return StmtError();
6109
6110 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6111 // 1.2.2 OpenMP Language Terminology
6112 // Structured block - An executable statement with a single entry at the
6113 // top and a single exit at the bottom.
6114 // The point of exit cannot be a branch out of the structured block.
6115 // longjmp() and throw() must not violate the entry/exit criteria.
6116 CS->getCapturedDecl()->setNothrow();
6117
6118 OMPLoopDirective::HelperExprs B;
6119 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6120 // define the nested loops number.
6121 unsigned NestedLoopCount =
6122 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
6123 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6124 VarsWithImplicitDSA, B);
6125 if (NestedLoopCount == 0)
6126 return StmtError();
6127
6128 assert((CurContext->isDependentContext() || B.builtAll()) &&
6129 "omp target parallel for loop exprs were not built");
6130
6131 if (!CurContext->isDependentContext()) {
6132 // Finalize the clauses that need pre-built expressions for CodeGen.
6133 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006134 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006135 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006136 B.NumIterations, *this, CurScope,
6137 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006138 return StmtError();
6139 }
6140 }
6141
6142 getCurFunction()->setHasBranchProtectedScope();
6143 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6144 NestedLoopCount, Clauses, AStmt,
6145 B, DSAStack->isCancelRegion());
6146}
6147
Alexey Bataev95b64a92017-05-30 16:00:04 +00006148/// Check for existence of a map clause in the list of clauses.
6149static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6150 const OpenMPClauseKind K) {
6151 return llvm::any_of(
6152 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6153}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006154
Alexey Bataev95b64a92017-05-30 16:00:04 +00006155template <typename... Params>
6156static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6157 const Params... ClauseTypes) {
6158 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006159}
6160
Michael Wong65f367f2015-07-21 13:44:28 +00006161StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6162 Stmt *AStmt,
6163 SourceLocation StartLoc,
6164 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006165 if (!AStmt)
6166 return StmtError();
6167
6168 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6169
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006170 // OpenMP [2.10.1, Restrictions, p. 97]
6171 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006172 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6173 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6174 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006175 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006176 return StmtError();
6177 }
6178
Michael Wong65f367f2015-07-21 13:44:28 +00006179 getCurFunction()->setHasBranchProtectedScope();
6180
6181 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6182 AStmt);
6183}
6184
Samuel Antaodf67fc42016-01-19 19:15:56 +00006185StmtResult
6186Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6187 SourceLocation StartLoc,
6188 SourceLocation EndLoc) {
6189 // OpenMP [2.10.2, Restrictions, p. 99]
6190 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006191 if (!hasClauses(Clauses, OMPC_map)) {
6192 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6193 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006194 return StmtError();
6195 }
6196
6197 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
6198 Clauses);
6199}
6200
Samuel Antao72590762016-01-19 20:04:50 +00006201StmtResult
6202Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6203 SourceLocation StartLoc,
6204 SourceLocation EndLoc) {
6205 // OpenMP [2.10.3, Restrictions, p. 102]
6206 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006207 if (!hasClauses(Clauses, OMPC_map)) {
6208 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6209 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006210 return StmtError();
6211 }
6212
6213 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
6214}
6215
Samuel Antao686c70c2016-05-26 17:30:50 +00006216StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6217 SourceLocation StartLoc,
6218 SourceLocation EndLoc) {
Alexey Bataev95b64a92017-05-30 16:00:04 +00006219 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006220 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6221 return StmtError();
6222 }
6223 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
6224}
6225
Alexey Bataev13314bf2014-10-09 04:18:56 +00006226StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6227 Stmt *AStmt, SourceLocation StartLoc,
6228 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006229 if (!AStmt)
6230 return StmtError();
6231
Alexey Bataev13314bf2014-10-09 04:18:56 +00006232 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6233 // 1.2.2 OpenMP Language Terminology
6234 // Structured block - An executable statement with a single entry at the
6235 // top and a single exit at the bottom.
6236 // The point of exit cannot be a branch out of the structured block.
6237 // longjmp() and throw() must not violate the entry/exit criteria.
6238 CS->getCapturedDecl()->setNothrow();
6239
6240 getCurFunction()->setHasBranchProtectedScope();
6241
6242 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6243}
6244
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006245StmtResult
6246Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6247 SourceLocation EndLoc,
6248 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006249 if (DSAStack->isParentNowaitRegion()) {
6250 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6251 return StmtError();
6252 }
6253 if (DSAStack->isParentOrderedRegion()) {
6254 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6255 return StmtError();
6256 }
6257 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6258 CancelRegion);
6259}
6260
Alexey Bataev87933c72015-09-18 08:07:34 +00006261StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6262 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006263 SourceLocation EndLoc,
6264 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006265 if (DSAStack->isParentNowaitRegion()) {
6266 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6267 return StmtError();
6268 }
6269 if (DSAStack->isParentOrderedRegion()) {
6270 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6271 return StmtError();
6272 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006273 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006274 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6275 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006276}
6277
Alexey Bataev382967a2015-12-08 12:06:20 +00006278static bool checkGrainsizeNumTasksClauses(Sema &S,
6279 ArrayRef<OMPClause *> Clauses) {
6280 OMPClause *PrevClause = nullptr;
6281 bool ErrorFound = false;
6282 for (auto *C : Clauses) {
6283 if (C->getClauseKind() == OMPC_grainsize ||
6284 C->getClauseKind() == OMPC_num_tasks) {
6285 if (!PrevClause)
6286 PrevClause = C;
6287 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6288 S.Diag(C->getLocStart(),
6289 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6290 << getOpenMPClauseName(C->getClauseKind())
6291 << getOpenMPClauseName(PrevClause->getClauseKind());
6292 S.Diag(PrevClause->getLocStart(),
6293 diag::note_omp_previous_grainsize_num_tasks)
6294 << getOpenMPClauseName(PrevClause->getClauseKind());
6295 ErrorFound = true;
6296 }
6297 }
6298 }
6299 return ErrorFound;
6300}
6301
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006302static bool checkReductionClauseWithNogroup(Sema &S,
6303 ArrayRef<OMPClause *> Clauses) {
6304 OMPClause *ReductionClause = nullptr;
6305 OMPClause *NogroupClause = nullptr;
6306 for (auto *C : Clauses) {
6307 if (C->getClauseKind() == OMPC_reduction) {
6308 ReductionClause = C;
6309 if (NogroupClause)
6310 break;
6311 continue;
6312 }
6313 if (C->getClauseKind() == OMPC_nogroup) {
6314 NogroupClause = C;
6315 if (ReductionClause)
6316 break;
6317 continue;
6318 }
6319 }
6320 if (ReductionClause && NogroupClause) {
6321 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6322 << SourceRange(NogroupClause->getLocStart(),
6323 NogroupClause->getLocEnd());
6324 return true;
6325 }
6326 return false;
6327}
6328
Alexey Bataev49f6e782015-12-01 04:18:41 +00006329StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6330 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6331 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006332 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006333 if (!AStmt)
6334 return StmtError();
6335
6336 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6337 OMPLoopDirective::HelperExprs B;
6338 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6339 // define the nested loops number.
6340 unsigned NestedLoopCount =
6341 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006342 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006343 VarsWithImplicitDSA, B);
6344 if (NestedLoopCount == 0)
6345 return StmtError();
6346
6347 assert((CurContext->isDependentContext() || B.builtAll()) &&
6348 "omp for loop exprs were not built");
6349
Alexey Bataev382967a2015-12-08 12:06:20 +00006350 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6351 // The grainsize clause and num_tasks clause are mutually exclusive and may
6352 // not appear on the same taskloop directive.
6353 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6354 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006355 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6356 // If a reduction clause is present on the taskloop directive, the nogroup
6357 // clause must not be specified.
6358 if (checkReductionClauseWithNogroup(*this, Clauses))
6359 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006360
Alexey Bataev49f6e782015-12-01 04:18:41 +00006361 getCurFunction()->setHasBranchProtectedScope();
6362 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6363 NestedLoopCount, Clauses, AStmt, B);
6364}
6365
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006366StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6367 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6368 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006369 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006370 if (!AStmt)
6371 return StmtError();
6372
6373 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6374 OMPLoopDirective::HelperExprs B;
6375 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6376 // define the nested loops number.
6377 unsigned NestedLoopCount =
6378 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6379 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6380 VarsWithImplicitDSA, B);
6381 if (NestedLoopCount == 0)
6382 return StmtError();
6383
6384 assert((CurContext->isDependentContext() || B.builtAll()) &&
6385 "omp for loop exprs were not built");
6386
Alexey Bataev5a3af132016-03-29 08:58:54 +00006387 if (!CurContext->isDependentContext()) {
6388 // Finalize the clauses that need pre-built expressions for CodeGen.
6389 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006390 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006391 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006392 B.NumIterations, *this, CurScope,
6393 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006394 return StmtError();
6395 }
6396 }
6397
Alexey Bataev382967a2015-12-08 12:06:20 +00006398 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6399 // The grainsize clause and num_tasks clause are mutually exclusive and may
6400 // not appear on the same taskloop directive.
6401 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6402 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006403 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6404 // If a reduction clause is present on the taskloop directive, the nogroup
6405 // clause must not be specified.
6406 if (checkReductionClauseWithNogroup(*this, Clauses))
6407 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006408
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006409 getCurFunction()->setHasBranchProtectedScope();
6410 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6411 NestedLoopCount, Clauses, AStmt, B);
6412}
6413
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006414StmtResult Sema::ActOnOpenMPDistributeDirective(
6415 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6416 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006417 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006418 if (!AStmt)
6419 return StmtError();
6420
6421 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6422 OMPLoopDirective::HelperExprs B;
6423 // In presence of clause 'collapse' with number of loops, it will
6424 // define the nested loops number.
6425 unsigned NestedLoopCount =
6426 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6427 nullptr /*ordered not a clause on distribute*/, AStmt,
6428 *this, *DSAStack, VarsWithImplicitDSA, B);
6429 if (NestedLoopCount == 0)
6430 return StmtError();
6431
6432 assert((CurContext->isDependentContext() || B.builtAll()) &&
6433 "omp for loop exprs were not built");
6434
6435 getCurFunction()->setHasBranchProtectedScope();
6436 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6437 NestedLoopCount, Clauses, AStmt, B);
6438}
6439
Carlo Bertolli9925f152016-06-27 14:55:37 +00006440StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6441 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6442 SourceLocation EndLoc,
6443 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6444 if (!AStmt)
6445 return StmtError();
6446
6447 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6448 // 1.2.2 OpenMP Language Terminology
6449 // Structured block - An executable statement with a single entry at the
6450 // top and a single exit at the bottom.
6451 // The point of exit cannot be a branch out of the structured block.
6452 // longjmp() and throw() must not violate the entry/exit criteria.
6453 CS->getCapturedDecl()->setNothrow();
6454
6455 OMPLoopDirective::HelperExprs B;
6456 // In presence of clause 'collapse' with number of loops, it will
6457 // define the nested loops number.
6458 unsigned NestedLoopCount = CheckOpenMPLoop(
6459 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6460 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6461 VarsWithImplicitDSA, B);
6462 if (NestedLoopCount == 0)
6463 return StmtError();
6464
6465 assert((CurContext->isDependentContext() || B.builtAll()) &&
6466 "omp for loop exprs were not built");
6467
6468 getCurFunction()->setHasBranchProtectedScope();
6469 return OMPDistributeParallelForDirective::Create(
6470 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6471}
6472
Kelvin Li4a39add2016-07-05 05:00:15 +00006473StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6474 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6475 SourceLocation EndLoc,
6476 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6477 if (!AStmt)
6478 return StmtError();
6479
6480 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6481 // 1.2.2 OpenMP Language Terminology
6482 // Structured block - An executable statement with a single entry at the
6483 // top and a single exit at the bottom.
6484 // The point of exit cannot be a branch out of the structured block.
6485 // longjmp() and throw() must not violate the entry/exit criteria.
6486 CS->getCapturedDecl()->setNothrow();
6487
6488 OMPLoopDirective::HelperExprs B;
6489 // In presence of clause 'collapse' with number of loops, it will
6490 // define the nested loops number.
6491 unsigned NestedLoopCount = CheckOpenMPLoop(
6492 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6493 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6494 VarsWithImplicitDSA, B);
6495 if (NestedLoopCount == 0)
6496 return StmtError();
6497
6498 assert((CurContext->isDependentContext() || B.builtAll()) &&
6499 "omp for loop exprs were not built");
6500
Kelvin Lic5609492016-07-15 04:39:07 +00006501 if (checkSimdlenSafelenSpecified(*this, Clauses))
6502 return StmtError();
6503
Kelvin Li4a39add2016-07-05 05:00:15 +00006504 getCurFunction()->setHasBranchProtectedScope();
6505 return OMPDistributeParallelForSimdDirective::Create(
6506 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6507}
6508
Kelvin Li787f3fc2016-07-06 04:45:38 +00006509StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6510 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6511 SourceLocation EndLoc,
6512 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6513 if (!AStmt)
6514 return StmtError();
6515
6516 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6517 // 1.2.2 OpenMP Language Terminology
6518 // Structured block - An executable statement with a single entry at the
6519 // top and a single exit at the bottom.
6520 // The point of exit cannot be a branch out of the structured block.
6521 // longjmp() and throw() must not violate the entry/exit criteria.
6522 CS->getCapturedDecl()->setNothrow();
6523
6524 OMPLoopDirective::HelperExprs B;
6525 // In presence of clause 'collapse' with number of loops, it will
6526 // define the nested loops number.
6527 unsigned NestedLoopCount =
6528 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6529 nullptr /*ordered not a clause on distribute*/, AStmt,
6530 *this, *DSAStack, VarsWithImplicitDSA, B);
6531 if (NestedLoopCount == 0)
6532 return StmtError();
6533
6534 assert((CurContext->isDependentContext() || B.builtAll()) &&
6535 "omp for loop exprs were not built");
6536
Kelvin Lic5609492016-07-15 04:39:07 +00006537 if (checkSimdlenSafelenSpecified(*this, Clauses))
6538 return StmtError();
6539
Kelvin Li787f3fc2016-07-06 04:45:38 +00006540 getCurFunction()->setHasBranchProtectedScope();
6541 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6542 NestedLoopCount, Clauses, AStmt, B);
6543}
6544
Kelvin Lia579b912016-07-14 02:54:56 +00006545StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6546 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6547 SourceLocation EndLoc,
6548 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6549 if (!AStmt)
6550 return StmtError();
6551
6552 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6553 // 1.2.2 OpenMP Language Terminology
6554 // Structured block - An executable statement with a single entry at the
6555 // top and a single exit at the bottom.
6556 // The point of exit cannot be a branch out of the structured block.
6557 // longjmp() and throw() must not violate the entry/exit criteria.
6558 CS->getCapturedDecl()->setNothrow();
6559
6560 OMPLoopDirective::HelperExprs B;
6561 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6562 // define the nested loops number.
6563 unsigned NestedLoopCount = CheckOpenMPLoop(
6564 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6565 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6566 VarsWithImplicitDSA, B);
6567 if (NestedLoopCount == 0)
6568 return StmtError();
6569
6570 assert((CurContext->isDependentContext() || B.builtAll()) &&
6571 "omp target parallel for simd loop exprs were not built");
6572
6573 if (!CurContext->isDependentContext()) {
6574 // Finalize the clauses that need pre-built expressions for CodeGen.
6575 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006576 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006577 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6578 B.NumIterations, *this, CurScope,
6579 DSAStack))
6580 return StmtError();
6581 }
6582 }
Kelvin Lic5609492016-07-15 04:39:07 +00006583 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006584 return StmtError();
6585
6586 getCurFunction()->setHasBranchProtectedScope();
6587 return OMPTargetParallelForSimdDirective::Create(
6588 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6589}
6590
Kelvin Li986330c2016-07-20 22:57:10 +00006591StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6592 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6593 SourceLocation EndLoc,
6594 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6595 if (!AStmt)
6596 return StmtError();
6597
6598 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6599 // 1.2.2 OpenMP Language Terminology
6600 // Structured block - An executable statement with a single entry at the
6601 // top and a single exit at the bottom.
6602 // The point of exit cannot be a branch out of the structured block.
6603 // longjmp() and throw() must not violate the entry/exit criteria.
6604 CS->getCapturedDecl()->setNothrow();
6605
6606 OMPLoopDirective::HelperExprs B;
6607 // In presence of clause 'collapse' with number of loops, it will define the
6608 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006609 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006610 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6611 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6612 VarsWithImplicitDSA, B);
6613 if (NestedLoopCount == 0)
6614 return StmtError();
6615
6616 assert((CurContext->isDependentContext() || B.builtAll()) &&
6617 "omp target simd loop exprs were not built");
6618
6619 if (!CurContext->isDependentContext()) {
6620 // Finalize the clauses that need pre-built expressions for CodeGen.
6621 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006622 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006623 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6624 B.NumIterations, *this, CurScope,
6625 DSAStack))
6626 return StmtError();
6627 }
6628 }
6629
6630 if (checkSimdlenSafelenSpecified(*this, Clauses))
6631 return StmtError();
6632
6633 getCurFunction()->setHasBranchProtectedScope();
6634 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6635 NestedLoopCount, Clauses, AStmt, B);
6636}
6637
Kelvin Li02532872016-08-05 14:37:37 +00006638StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6640 SourceLocation EndLoc,
6641 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6642 if (!AStmt)
6643 return StmtError();
6644
6645 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6646 // 1.2.2 OpenMP Language Terminology
6647 // Structured block - An executable statement with a single entry at the
6648 // top and a single exit at the bottom.
6649 // The point of exit cannot be a branch out of the structured block.
6650 // longjmp() and throw() must not violate the entry/exit criteria.
6651 CS->getCapturedDecl()->setNothrow();
6652
6653 OMPLoopDirective::HelperExprs B;
6654 // In presence of clause 'collapse' with number of loops, it will
6655 // define the nested loops number.
6656 unsigned NestedLoopCount =
6657 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6658 nullptr /*ordered not a clause on distribute*/, AStmt,
6659 *this, *DSAStack, VarsWithImplicitDSA, B);
6660 if (NestedLoopCount == 0)
6661 return StmtError();
6662
6663 assert((CurContext->isDependentContext() || B.builtAll()) &&
6664 "omp teams distribute loop exprs were not built");
6665
6666 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006667 return OMPTeamsDistributeDirective::Create(
6668 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006669}
6670
Kelvin Li4e325f72016-10-25 12:50:55 +00006671StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6672 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6673 SourceLocation EndLoc,
6674 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6675 if (!AStmt)
6676 return StmtError();
6677
6678 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6679 // 1.2.2 OpenMP Language Terminology
6680 // Structured block - An executable statement with a single entry at the
6681 // top and a single exit at the bottom.
6682 // The point of exit cannot be a branch out of the structured block.
6683 // longjmp() and throw() must not violate the entry/exit criteria.
6684 CS->getCapturedDecl()->setNothrow();
6685
6686 OMPLoopDirective::HelperExprs B;
6687 // In presence of clause 'collapse' with number of loops, it will
6688 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006689 unsigned NestedLoopCount = CheckOpenMPLoop(
6690 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6691 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6692 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006693
6694 if (NestedLoopCount == 0)
6695 return StmtError();
6696
6697 assert((CurContext->isDependentContext() || B.builtAll()) &&
6698 "omp teams distribute simd loop exprs were not built");
6699
6700 if (!CurContext->isDependentContext()) {
6701 // Finalize the clauses that need pre-built expressions for CodeGen.
6702 for (auto C : Clauses) {
6703 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6704 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6705 B.NumIterations, *this, CurScope,
6706 DSAStack))
6707 return StmtError();
6708 }
6709 }
6710
6711 if (checkSimdlenSafelenSpecified(*this, Clauses))
6712 return StmtError();
6713
6714 getCurFunction()->setHasBranchProtectedScope();
6715 return OMPTeamsDistributeSimdDirective::Create(
6716 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6717}
6718
Kelvin Li579e41c2016-11-30 23:51:03 +00006719StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6720 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6721 SourceLocation EndLoc,
6722 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6723 if (!AStmt)
6724 return StmtError();
6725
6726 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6727 // 1.2.2 OpenMP Language Terminology
6728 // Structured block - An executable statement with a single entry at the
6729 // top and a single exit at the bottom.
6730 // The point of exit cannot be a branch out of the structured block.
6731 // longjmp() and throw() must not violate the entry/exit criteria.
6732 CS->getCapturedDecl()->setNothrow();
6733
6734 OMPLoopDirective::HelperExprs B;
6735 // In presence of clause 'collapse' with number of loops, it will
6736 // define the nested loops number.
6737 auto NestedLoopCount = CheckOpenMPLoop(
6738 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6739 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6740 VarsWithImplicitDSA, B);
6741
6742 if (NestedLoopCount == 0)
6743 return StmtError();
6744
6745 assert((CurContext->isDependentContext() || B.builtAll()) &&
6746 "omp for loop exprs were not built");
6747
6748 if (!CurContext->isDependentContext()) {
6749 // Finalize the clauses that need pre-built expressions for CodeGen.
6750 for (auto C : Clauses) {
6751 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6752 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6753 B.NumIterations, *this, CurScope,
6754 DSAStack))
6755 return StmtError();
6756 }
6757 }
6758
6759 if (checkSimdlenSafelenSpecified(*this, Clauses))
6760 return StmtError();
6761
6762 getCurFunction()->setHasBranchProtectedScope();
6763 return OMPTeamsDistributeParallelForSimdDirective::Create(
6764 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6765}
6766
Kelvin Li7ade93f2016-12-09 03:24:30 +00006767StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6768 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6769 SourceLocation EndLoc,
6770 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6771 if (!AStmt)
6772 return StmtError();
6773
6774 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6775 // 1.2.2 OpenMP Language Terminology
6776 // Structured block - An executable statement with a single entry at the
6777 // top and a single exit at the bottom.
6778 // The point of exit cannot be a branch out of the structured block.
6779 // longjmp() and throw() must not violate the entry/exit criteria.
6780 CS->getCapturedDecl()->setNothrow();
6781
6782 OMPLoopDirective::HelperExprs B;
6783 // In presence of clause 'collapse' with number of loops, it will
6784 // define the nested loops number.
6785 unsigned NestedLoopCount = CheckOpenMPLoop(
6786 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6787 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6788 VarsWithImplicitDSA, B);
6789
6790 if (NestedLoopCount == 0)
6791 return StmtError();
6792
6793 assert((CurContext->isDependentContext() || B.builtAll()) &&
6794 "omp for loop exprs were not built");
6795
6796 if (!CurContext->isDependentContext()) {
6797 // Finalize the clauses that need pre-built expressions for CodeGen.
6798 for (auto C : Clauses) {
6799 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6800 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6801 B.NumIterations, *this, CurScope,
6802 DSAStack))
6803 return StmtError();
6804 }
6805 }
6806
6807 getCurFunction()->setHasBranchProtectedScope();
6808 return OMPTeamsDistributeParallelForDirective::Create(
6809 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6810}
6811
Kelvin Libf594a52016-12-17 05:48:59 +00006812StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6813 Stmt *AStmt,
6814 SourceLocation StartLoc,
6815 SourceLocation EndLoc) {
6816 if (!AStmt)
6817 return StmtError();
6818
6819 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6820 // 1.2.2 OpenMP Language Terminology
6821 // Structured block - An executable statement with a single entry at the
6822 // top and a single exit at the bottom.
6823 // The point of exit cannot be a branch out of the structured block.
6824 // longjmp() and throw() must not violate the entry/exit criteria.
6825 CS->getCapturedDecl()->setNothrow();
6826
6827 getCurFunction()->setHasBranchProtectedScope();
6828
6829 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6830 AStmt);
6831}
6832
Kelvin Li83c451e2016-12-25 04:52:54 +00006833StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6834 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6835 SourceLocation EndLoc,
6836 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6837 if (!AStmt)
6838 return StmtError();
6839
6840 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6841 // 1.2.2 OpenMP Language Terminology
6842 // Structured block - An executable statement with a single entry at the
6843 // top and a single exit at the bottom.
6844 // The point of exit cannot be a branch out of the structured block.
6845 // longjmp() and throw() must not violate the entry/exit criteria.
6846 CS->getCapturedDecl()->setNothrow();
6847
6848 OMPLoopDirective::HelperExprs B;
6849 // In presence of clause 'collapse' with number of loops, it will
6850 // define the nested loops number.
6851 auto NestedLoopCount = CheckOpenMPLoop(
6852 OMPD_target_teams_distribute,
6853 getCollapseNumberExpr(Clauses),
6854 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6855 VarsWithImplicitDSA, B);
6856 if (NestedLoopCount == 0)
6857 return StmtError();
6858
6859 assert((CurContext->isDependentContext() || B.builtAll()) &&
6860 "omp target teams distribute loop exprs were not built");
6861
6862 getCurFunction()->setHasBranchProtectedScope();
6863 return OMPTargetTeamsDistributeDirective::Create(
6864 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6865}
6866
Kelvin Li80e8f562016-12-29 22:16:30 +00006867StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6868 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6869 SourceLocation EndLoc,
6870 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6871 if (!AStmt)
6872 return StmtError();
6873
6874 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6875 // 1.2.2 OpenMP Language Terminology
6876 // Structured block - An executable statement with a single entry at the
6877 // top and a single exit at the bottom.
6878 // The point of exit cannot be a branch out of the structured block.
6879 // longjmp() and throw() must not violate the entry/exit criteria.
6880 CS->getCapturedDecl()->setNothrow();
6881
6882 OMPLoopDirective::HelperExprs B;
6883 // In presence of clause 'collapse' with number of loops, it will
6884 // define the nested loops number.
6885 auto NestedLoopCount = CheckOpenMPLoop(
6886 OMPD_target_teams_distribute_parallel_for,
6887 getCollapseNumberExpr(Clauses),
6888 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6889 VarsWithImplicitDSA, B);
6890 if (NestedLoopCount == 0)
6891 return StmtError();
6892
6893 assert((CurContext->isDependentContext() || B.builtAll()) &&
6894 "omp target teams distribute parallel for loop exprs were not built");
6895
6896 if (!CurContext->isDependentContext()) {
6897 // Finalize the clauses that need pre-built expressions for CodeGen.
6898 for (auto C : Clauses) {
6899 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6900 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6901 B.NumIterations, *this, CurScope,
6902 DSAStack))
6903 return StmtError();
6904 }
6905 }
6906
6907 getCurFunction()->setHasBranchProtectedScope();
6908 return OMPTargetTeamsDistributeParallelForDirective::Create(
6909 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6910}
6911
Kelvin Li1851df52017-01-03 05:23:48 +00006912StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6913 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6914 SourceLocation EndLoc,
6915 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6916 if (!AStmt)
6917 return StmtError();
6918
6919 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6920 // 1.2.2 OpenMP Language Terminology
6921 // Structured block - An executable statement with a single entry at the
6922 // top and a single exit at the bottom.
6923 // The point of exit cannot be a branch out of the structured block.
6924 // longjmp() and throw() must not violate the entry/exit criteria.
6925 CS->getCapturedDecl()->setNothrow();
6926
6927 OMPLoopDirective::HelperExprs B;
6928 // In presence of clause 'collapse' with number of loops, it will
6929 // define the nested loops number.
6930 auto NestedLoopCount = CheckOpenMPLoop(
6931 OMPD_target_teams_distribute_parallel_for_simd,
6932 getCollapseNumberExpr(Clauses),
6933 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6934 VarsWithImplicitDSA, B);
6935 if (NestedLoopCount == 0)
6936 return StmtError();
6937
6938 assert((CurContext->isDependentContext() || B.builtAll()) &&
6939 "omp target teams distribute parallel for simd loop exprs were not "
6940 "built");
6941
6942 if (!CurContext->isDependentContext()) {
6943 // Finalize the clauses that need pre-built expressions for CodeGen.
6944 for (auto C : Clauses) {
6945 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6946 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6947 B.NumIterations, *this, CurScope,
6948 DSAStack))
6949 return StmtError();
6950 }
6951 }
6952
6953 getCurFunction()->setHasBranchProtectedScope();
6954 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6955 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6956}
6957
Kelvin Lida681182017-01-10 18:08:18 +00006958StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6959 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6960 SourceLocation EndLoc,
6961 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6962 if (!AStmt)
6963 return StmtError();
6964
6965 auto *CS = cast<CapturedStmt>(AStmt);
6966 // 1.2.2 OpenMP Language Terminology
6967 // Structured block - An executable statement with a single entry at the
6968 // top and a single exit at the bottom.
6969 // The point of exit cannot be a branch out of the structured block.
6970 // longjmp() and throw() must not violate the entry/exit criteria.
6971 CS->getCapturedDecl()->setNothrow();
6972
6973 OMPLoopDirective::HelperExprs B;
6974 // In presence of clause 'collapse' with number of loops, it will
6975 // define the nested loops number.
6976 auto NestedLoopCount = CheckOpenMPLoop(
6977 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6978 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6979 VarsWithImplicitDSA, B);
6980 if (NestedLoopCount == 0)
6981 return StmtError();
6982
6983 assert((CurContext->isDependentContext() || B.builtAll()) &&
6984 "omp target teams distribute simd loop exprs were not built");
6985
6986 getCurFunction()->setHasBranchProtectedScope();
6987 return OMPTargetTeamsDistributeSimdDirective::Create(
6988 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6989}
6990
Alexey Bataeved09d242014-05-28 05:53:51 +00006991OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006992 SourceLocation StartLoc,
6993 SourceLocation LParenLoc,
6994 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006995 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006996 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006997 case OMPC_final:
6998 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6999 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007000 case OMPC_num_threads:
7001 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7002 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007003 case OMPC_safelen:
7004 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7005 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007006 case OMPC_simdlen:
7007 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7008 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007009 case OMPC_collapse:
7010 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7011 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007012 case OMPC_ordered:
7013 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7014 break;
Michael Wonge710d542015-08-07 16:16:36 +00007015 case OMPC_device:
7016 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7017 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007018 case OMPC_num_teams:
7019 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7020 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007021 case OMPC_thread_limit:
7022 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7023 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007024 case OMPC_priority:
7025 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7026 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007027 case OMPC_grainsize:
7028 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7029 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007030 case OMPC_num_tasks:
7031 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7032 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007033 case OMPC_hint:
7034 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7035 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007036 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007037 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007038 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007039 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007040 case OMPC_private:
7041 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007042 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007043 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007044 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007045 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007046 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007047 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007048 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007049 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007050 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007051 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007052 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007053 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007054 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007055 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007056 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007057 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007058 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007059 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007060 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007061 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007062 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007063 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007064 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007065 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007066 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007067 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007068 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007069 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007070 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007071 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007072 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007073 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007074 llvm_unreachable("Clause is not allowed.");
7075 }
7076 return Res;
7077}
7078
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007079// An OpenMP directive such as 'target parallel' has two captured regions:
7080// for the 'target' and 'parallel' respectively. This function returns
7081// the region in which to capture expressions associated with a clause.
7082// A return value of OMPD_unknown signifies that the expression should not
7083// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007084static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7085 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7086 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007087 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
7088
7089 switch (CKind) {
7090 case OMPC_if:
7091 switch (DKind) {
7092 case OMPD_target_parallel:
7093 // If this clause applies to the nested 'parallel' region, capture within
7094 // the 'target' region, otherwise do not capture.
7095 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7096 CaptureRegion = OMPD_target;
7097 break;
7098 case OMPD_cancel:
7099 case OMPD_parallel:
7100 case OMPD_parallel_sections:
7101 case OMPD_parallel_for:
7102 case OMPD_parallel_for_simd:
7103 case OMPD_target:
7104 case OMPD_target_simd:
7105 case OMPD_target_parallel_for:
7106 case OMPD_target_parallel_for_simd:
7107 case OMPD_target_teams:
7108 case OMPD_target_teams_distribute:
7109 case OMPD_target_teams_distribute_simd:
7110 case OMPD_target_teams_distribute_parallel_for:
7111 case OMPD_target_teams_distribute_parallel_for_simd:
7112 case OMPD_teams_distribute_parallel_for:
7113 case OMPD_teams_distribute_parallel_for_simd:
7114 case OMPD_distribute_parallel_for:
7115 case OMPD_distribute_parallel_for_simd:
7116 case OMPD_task:
7117 case OMPD_taskloop:
7118 case OMPD_taskloop_simd:
7119 case OMPD_target_data:
7120 case OMPD_target_enter_data:
7121 case OMPD_target_exit_data:
7122 case OMPD_target_update:
7123 // Do not capture if-clause expressions.
7124 break;
7125 case OMPD_threadprivate:
7126 case OMPD_taskyield:
7127 case OMPD_barrier:
7128 case OMPD_taskwait:
7129 case OMPD_cancellation_point:
7130 case OMPD_flush:
7131 case OMPD_declare_reduction:
7132 case OMPD_declare_simd:
7133 case OMPD_declare_target:
7134 case OMPD_end_declare_target:
7135 case OMPD_teams:
7136 case OMPD_simd:
7137 case OMPD_for:
7138 case OMPD_for_simd:
7139 case OMPD_sections:
7140 case OMPD_section:
7141 case OMPD_single:
7142 case OMPD_master:
7143 case OMPD_critical:
7144 case OMPD_taskgroup:
7145 case OMPD_distribute:
7146 case OMPD_ordered:
7147 case OMPD_atomic:
7148 case OMPD_distribute_simd:
7149 case OMPD_teams_distribute:
7150 case OMPD_teams_distribute_simd:
7151 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7152 case OMPD_unknown:
7153 llvm_unreachable("Unknown OpenMP directive");
7154 }
7155 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007156 case OMPC_num_threads:
7157 switch (DKind) {
7158 case OMPD_target_parallel:
7159 CaptureRegion = OMPD_target;
7160 break;
7161 case OMPD_cancel:
7162 case OMPD_parallel:
7163 case OMPD_parallel_sections:
7164 case OMPD_parallel_for:
7165 case OMPD_parallel_for_simd:
7166 case OMPD_target:
7167 case OMPD_target_simd:
7168 case OMPD_target_parallel_for:
7169 case OMPD_target_parallel_for_simd:
7170 case OMPD_target_teams:
7171 case OMPD_target_teams_distribute:
7172 case OMPD_target_teams_distribute_simd:
7173 case OMPD_target_teams_distribute_parallel_for:
7174 case OMPD_target_teams_distribute_parallel_for_simd:
7175 case OMPD_teams_distribute_parallel_for:
7176 case OMPD_teams_distribute_parallel_for_simd:
7177 case OMPD_distribute_parallel_for:
7178 case OMPD_distribute_parallel_for_simd:
7179 case OMPD_task:
7180 case OMPD_taskloop:
7181 case OMPD_taskloop_simd:
7182 case OMPD_target_data:
7183 case OMPD_target_enter_data:
7184 case OMPD_target_exit_data:
7185 case OMPD_target_update:
7186 // Do not capture num_threads-clause expressions.
7187 break;
7188 case OMPD_threadprivate:
7189 case OMPD_taskyield:
7190 case OMPD_barrier:
7191 case OMPD_taskwait:
7192 case OMPD_cancellation_point:
7193 case OMPD_flush:
7194 case OMPD_declare_reduction:
7195 case OMPD_declare_simd:
7196 case OMPD_declare_target:
7197 case OMPD_end_declare_target:
7198 case OMPD_teams:
7199 case OMPD_simd:
7200 case OMPD_for:
7201 case OMPD_for_simd:
7202 case OMPD_sections:
7203 case OMPD_section:
7204 case OMPD_single:
7205 case OMPD_master:
7206 case OMPD_critical:
7207 case OMPD_taskgroup:
7208 case OMPD_distribute:
7209 case OMPD_ordered:
7210 case OMPD_atomic:
7211 case OMPD_distribute_simd:
7212 case OMPD_teams_distribute:
7213 case OMPD_teams_distribute_simd:
7214 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7215 case OMPD_unknown:
7216 llvm_unreachable("Unknown OpenMP directive");
7217 }
7218 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007219 case OMPC_num_teams:
7220 switch (DKind) {
7221 case OMPD_target_teams:
7222 CaptureRegion = OMPD_target;
7223 break;
7224 case OMPD_cancel:
7225 case OMPD_parallel:
7226 case OMPD_parallel_sections:
7227 case OMPD_parallel_for:
7228 case OMPD_parallel_for_simd:
7229 case OMPD_target:
7230 case OMPD_target_simd:
7231 case OMPD_target_parallel:
7232 case OMPD_target_parallel_for:
7233 case OMPD_target_parallel_for_simd:
7234 case OMPD_target_teams_distribute:
7235 case OMPD_target_teams_distribute_simd:
7236 case OMPD_target_teams_distribute_parallel_for:
7237 case OMPD_target_teams_distribute_parallel_for_simd:
7238 case OMPD_teams_distribute_parallel_for:
7239 case OMPD_teams_distribute_parallel_for_simd:
7240 case OMPD_distribute_parallel_for:
7241 case OMPD_distribute_parallel_for_simd:
7242 case OMPD_task:
7243 case OMPD_taskloop:
7244 case OMPD_taskloop_simd:
7245 case OMPD_target_data:
7246 case OMPD_target_enter_data:
7247 case OMPD_target_exit_data:
7248 case OMPD_target_update:
7249 case OMPD_teams:
7250 case OMPD_teams_distribute:
7251 case OMPD_teams_distribute_simd:
7252 // Do not capture num_teams-clause expressions.
7253 break;
7254 case OMPD_threadprivate:
7255 case OMPD_taskyield:
7256 case OMPD_barrier:
7257 case OMPD_taskwait:
7258 case OMPD_cancellation_point:
7259 case OMPD_flush:
7260 case OMPD_declare_reduction:
7261 case OMPD_declare_simd:
7262 case OMPD_declare_target:
7263 case OMPD_end_declare_target:
7264 case OMPD_simd:
7265 case OMPD_for:
7266 case OMPD_for_simd:
7267 case OMPD_sections:
7268 case OMPD_section:
7269 case OMPD_single:
7270 case OMPD_master:
7271 case OMPD_critical:
7272 case OMPD_taskgroup:
7273 case OMPD_distribute:
7274 case OMPD_ordered:
7275 case OMPD_atomic:
7276 case OMPD_distribute_simd:
7277 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7278 case OMPD_unknown:
7279 llvm_unreachable("Unknown OpenMP directive");
7280 }
7281 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007282 case OMPC_thread_limit:
7283 switch (DKind) {
7284 case OMPD_target_teams:
7285 CaptureRegion = OMPD_target;
7286 break;
7287 case OMPD_cancel:
7288 case OMPD_parallel:
7289 case OMPD_parallel_sections:
7290 case OMPD_parallel_for:
7291 case OMPD_parallel_for_simd:
7292 case OMPD_target:
7293 case OMPD_target_simd:
7294 case OMPD_target_parallel:
7295 case OMPD_target_parallel_for:
7296 case OMPD_target_parallel_for_simd:
7297 case OMPD_target_teams_distribute:
7298 case OMPD_target_teams_distribute_simd:
7299 case OMPD_target_teams_distribute_parallel_for:
7300 case OMPD_target_teams_distribute_parallel_for_simd:
7301 case OMPD_teams_distribute_parallel_for:
7302 case OMPD_teams_distribute_parallel_for_simd:
7303 case OMPD_distribute_parallel_for:
7304 case OMPD_distribute_parallel_for_simd:
7305 case OMPD_task:
7306 case OMPD_taskloop:
7307 case OMPD_taskloop_simd:
7308 case OMPD_target_data:
7309 case OMPD_target_enter_data:
7310 case OMPD_target_exit_data:
7311 case OMPD_target_update:
7312 case OMPD_teams:
7313 case OMPD_teams_distribute:
7314 case OMPD_teams_distribute_simd:
7315 // Do not capture thread_limit-clause expressions.
7316 break;
7317 case OMPD_threadprivate:
7318 case OMPD_taskyield:
7319 case OMPD_barrier:
7320 case OMPD_taskwait:
7321 case OMPD_cancellation_point:
7322 case OMPD_flush:
7323 case OMPD_declare_reduction:
7324 case OMPD_declare_simd:
7325 case OMPD_declare_target:
7326 case OMPD_end_declare_target:
7327 case OMPD_simd:
7328 case OMPD_for:
7329 case OMPD_for_simd:
7330 case OMPD_sections:
7331 case OMPD_section:
7332 case OMPD_single:
7333 case OMPD_master:
7334 case OMPD_critical:
7335 case OMPD_taskgroup:
7336 case OMPD_distribute:
7337 case OMPD_ordered:
7338 case OMPD_atomic:
7339 case OMPD_distribute_simd:
7340 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
7341 case OMPD_unknown:
7342 llvm_unreachable("Unknown OpenMP directive");
7343 }
7344 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007345 case OMPC_schedule:
7346 case OMPC_dist_schedule:
7347 case OMPC_firstprivate:
7348 case OMPC_lastprivate:
7349 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007350 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007351 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007352 case OMPC_linear:
7353 case OMPC_default:
7354 case OMPC_proc_bind:
7355 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007356 case OMPC_safelen:
7357 case OMPC_simdlen:
7358 case OMPC_collapse:
7359 case OMPC_private:
7360 case OMPC_shared:
7361 case OMPC_aligned:
7362 case OMPC_copyin:
7363 case OMPC_copyprivate:
7364 case OMPC_ordered:
7365 case OMPC_nowait:
7366 case OMPC_untied:
7367 case OMPC_mergeable:
7368 case OMPC_threadprivate:
7369 case OMPC_flush:
7370 case OMPC_read:
7371 case OMPC_write:
7372 case OMPC_update:
7373 case OMPC_capture:
7374 case OMPC_seq_cst:
7375 case OMPC_depend:
7376 case OMPC_device:
7377 case OMPC_threads:
7378 case OMPC_simd:
7379 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007380 case OMPC_priority:
7381 case OMPC_grainsize:
7382 case OMPC_nogroup:
7383 case OMPC_num_tasks:
7384 case OMPC_hint:
7385 case OMPC_defaultmap:
7386 case OMPC_unknown:
7387 case OMPC_uniform:
7388 case OMPC_to:
7389 case OMPC_from:
7390 case OMPC_use_device_ptr:
7391 case OMPC_is_device_ptr:
7392 llvm_unreachable("Unexpected OpenMP clause.");
7393 }
7394 return CaptureRegion;
7395}
7396
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007397OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
7398 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007399 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007400 SourceLocation NameModifierLoc,
7401 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007402 SourceLocation EndLoc) {
7403 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007404 Stmt *HelperValStmt = nullptr;
7405 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007406 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7407 !Condition->isInstantiationDependent() &&
7408 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007409 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007410 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007411 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007412
Richard Smith03a4aa32016-06-23 19:02:52 +00007413 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007414
7415 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7416 CaptureRegion =
7417 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
7418 if (CaptureRegion != OMPD_unknown) {
7419 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7420 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7421 HelperValStmt = buildPreInits(Context, Captures);
7422 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007423 }
7424
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007425 return new (Context)
7426 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
7427 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007428}
7429
Alexey Bataev3778b602014-07-17 07:32:53 +00007430OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
7431 SourceLocation StartLoc,
7432 SourceLocation LParenLoc,
7433 SourceLocation EndLoc) {
7434 Expr *ValExpr = Condition;
7435 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
7436 !Condition->isInstantiationDependent() &&
7437 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00007438 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00007439 if (Val.isInvalid())
7440 return nullptr;
7441
Richard Smith03a4aa32016-06-23 19:02:52 +00007442 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00007443 }
7444
7445 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
7446}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007447ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
7448 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00007449 if (!Op)
7450 return ExprError();
7451
7452 class IntConvertDiagnoser : public ICEConvertDiagnoser {
7453 public:
7454 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00007455 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00007456 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
7457 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007458 return S.Diag(Loc, diag::err_omp_not_integral) << T;
7459 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007460 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
7461 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007462 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
7463 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007464 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
7465 QualType T,
7466 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007467 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
7468 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007469 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
7470 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007471 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007472 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007473 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007474 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
7475 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007476 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
7477 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007478 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
7479 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007480 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00007481 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00007482 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007483 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
7484 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00007485 llvm_unreachable("conversion functions are permitted");
7486 }
7487 } ConvertDiagnoser;
7488 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
7489}
7490
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007491static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00007492 OpenMPClauseKind CKind,
7493 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007494 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
7495 !ValExpr->isInstantiationDependent()) {
7496 SourceLocation Loc = ValExpr->getExprLoc();
7497 ExprResult Value =
7498 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
7499 if (Value.isInvalid())
7500 return false;
7501
7502 ValExpr = Value.get();
7503 // The expression must evaluate to a non-negative integer value.
7504 llvm::APSInt Result;
7505 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00007506 Result.isSigned() &&
7507 !((!StrictlyPositive && Result.isNonNegative()) ||
7508 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007509 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007510 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7511 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007512 return false;
7513 }
7514 }
7515 return true;
7516}
7517
Alexey Bataev568a8332014-03-06 06:15:19 +00007518OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7519 SourceLocation StartLoc,
7520 SourceLocation LParenLoc,
7521 SourceLocation EndLoc) {
7522 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007523 Stmt *HelperValStmt = nullptr;
7524 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007525
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007526 // OpenMP [2.5, Restrictions]
7527 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007528 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7529 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007530 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007531
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007532 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7533 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7534 if (CaptureRegion != OMPD_unknown) {
7535 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7536 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7537 HelperValStmt = buildPreInits(Context, Captures);
7538 }
7539
7540 return new (Context) OMPNumThreadsClause(
7541 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007542}
7543
Alexey Bataev62c87d22014-03-21 04:51:18 +00007544ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007545 OpenMPClauseKind CKind,
7546 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007547 if (!E)
7548 return ExprError();
7549 if (E->isValueDependent() || E->isTypeDependent() ||
7550 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007551 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007552 llvm::APSInt Result;
7553 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7554 if (ICE.isInvalid())
7555 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007556 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7557 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007558 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007559 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7560 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007561 return ExprError();
7562 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007563 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7564 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7565 << E->getSourceRange();
7566 return ExprError();
7567 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007568 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7569 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007570 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007571 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007572 return ICE;
7573}
7574
7575OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7576 SourceLocation LParenLoc,
7577 SourceLocation EndLoc) {
7578 // OpenMP [2.8.1, simd construct, Description]
7579 // The parameter of the safelen clause must be a constant
7580 // positive integer expression.
7581 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7582 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007583 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007584 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007585 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007586}
7587
Alexey Bataev66b15b52015-08-21 11:14:16 +00007588OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7589 SourceLocation LParenLoc,
7590 SourceLocation EndLoc) {
7591 // OpenMP [2.8.1, simd construct, Description]
7592 // The parameter of the simdlen clause must be a constant
7593 // positive integer expression.
7594 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7595 if (Simdlen.isInvalid())
7596 return nullptr;
7597 return new (Context)
7598 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7599}
7600
Alexander Musman64d33f12014-06-04 07:53:32 +00007601OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7602 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007603 SourceLocation LParenLoc,
7604 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007605 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007606 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007607 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007608 // The parameter of the collapse clause must be a constant
7609 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007610 ExprResult NumForLoopsResult =
7611 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7612 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007613 return nullptr;
7614 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007615 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007616}
7617
Alexey Bataev10e775f2015-07-30 11:36:16 +00007618OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7619 SourceLocation EndLoc,
7620 SourceLocation LParenLoc,
7621 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007622 // OpenMP [2.7.1, loop construct, Description]
7623 // OpenMP [2.8.1, simd construct, Description]
7624 // OpenMP [2.9.6, distribute construct, Description]
7625 // The parameter of the ordered clause must be a constant
7626 // positive integer expression if any.
7627 if (NumForLoops && LParenLoc.isValid()) {
7628 ExprResult NumForLoopsResult =
7629 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7630 if (NumForLoopsResult.isInvalid())
7631 return nullptr;
7632 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007633 } else
7634 NumForLoops = nullptr;
7635 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007636 return new (Context)
7637 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7638}
7639
Alexey Bataeved09d242014-05-28 05:53:51 +00007640OMPClause *Sema::ActOnOpenMPSimpleClause(
7641 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7642 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007643 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007644 switch (Kind) {
7645 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007646 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007647 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7648 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007649 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007650 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007651 Res = ActOnOpenMPProcBindClause(
7652 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7653 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007654 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007655 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007656 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007657 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007658 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007659 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007660 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007661 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007662 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007663 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007664 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007665 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007666 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007667 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007668 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007669 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007670 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007671 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007672 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007673 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007674 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007675 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007676 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007677 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007678 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007679 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007680 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007681 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007682 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007683 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007684 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007685 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007686 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007687 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007688 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007689 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007690 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007691 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007692 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007693 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007694 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007695 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007696 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007697 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007698 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007699 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007700 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007701 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007702 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007703 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007704 llvm_unreachable("Clause is not allowed.");
7705 }
7706 return Res;
7707}
7708
Alexey Bataev6402bca2015-12-28 07:25:51 +00007709static std::string
7710getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7711 ArrayRef<unsigned> Exclude = llvm::None) {
7712 std::string Values;
7713 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7714 unsigned Skipped = Exclude.size();
7715 auto S = Exclude.begin(), E = Exclude.end();
7716 for (unsigned i = First; i < Last; ++i) {
7717 if (std::find(S, E, i) != E) {
7718 --Skipped;
7719 continue;
7720 }
7721 Values += "'";
7722 Values += getOpenMPSimpleClauseTypeName(K, i);
7723 Values += "'";
7724 if (i == Bound - Skipped)
7725 Values += " or ";
7726 else if (i != Bound + 1 - Skipped)
7727 Values += ", ";
7728 }
7729 return Values;
7730}
7731
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007732OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7733 SourceLocation KindKwLoc,
7734 SourceLocation StartLoc,
7735 SourceLocation LParenLoc,
7736 SourceLocation EndLoc) {
7737 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007738 static_assert(OMPC_DEFAULT_unknown > 0,
7739 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007740 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007741 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7742 /*Last=*/OMPC_DEFAULT_unknown)
7743 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007744 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007745 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007746 switch (Kind) {
7747 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007748 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007749 break;
7750 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007751 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007752 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007753 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007754 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007755 break;
7756 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007757 return new (Context)
7758 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007759}
7760
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007761OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7762 SourceLocation KindKwLoc,
7763 SourceLocation StartLoc,
7764 SourceLocation LParenLoc,
7765 SourceLocation EndLoc) {
7766 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007767 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007768 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7769 /*Last=*/OMPC_PROC_BIND_unknown)
7770 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007771 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007772 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007773 return new (Context)
7774 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007775}
7776
Alexey Bataev56dafe82014-06-20 07:16:17 +00007777OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007778 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007779 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007780 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007781 SourceLocation EndLoc) {
7782 OMPClause *Res = nullptr;
7783 switch (Kind) {
7784 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007785 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7786 assert(Argument.size() == NumberOfElements &&
7787 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007788 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007789 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7790 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7791 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7792 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7793 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007794 break;
7795 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007796 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7797 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7798 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7799 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007800 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007801 case OMPC_dist_schedule:
7802 Res = ActOnOpenMPDistScheduleClause(
7803 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7804 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7805 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007806 case OMPC_defaultmap:
7807 enum { Modifier, DefaultmapKind };
7808 Res = ActOnOpenMPDefaultmapClause(
7809 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7810 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007811 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7812 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007813 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007814 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007815 case OMPC_num_threads:
7816 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007817 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007818 case OMPC_collapse:
7819 case OMPC_default:
7820 case OMPC_proc_bind:
7821 case OMPC_private:
7822 case OMPC_firstprivate:
7823 case OMPC_lastprivate:
7824 case OMPC_shared:
7825 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007826 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007827 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007828 case OMPC_linear:
7829 case OMPC_aligned:
7830 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007831 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007832 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007833 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007834 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007835 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007836 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007837 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007838 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007839 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007840 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007841 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007842 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007843 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007844 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007845 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007846 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007847 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007848 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007849 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007850 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007851 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007852 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007853 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007854 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +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 Bataev56dafe82014-06-20 07:16:17 +00007861 llvm_unreachable("Clause is not allowed.");
7862 }
7863 return Res;
7864}
7865
Alexey Bataev6402bca2015-12-28 07:25:51 +00007866static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7867 OpenMPScheduleClauseModifier M2,
7868 SourceLocation M1Loc, SourceLocation M2Loc) {
7869 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7870 SmallVector<unsigned, 2> Excluded;
7871 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7872 Excluded.push_back(M2);
7873 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7874 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7875 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7876 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7877 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7878 << getListOfPossibleValues(OMPC_schedule,
7879 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7880 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7881 Excluded)
7882 << getOpenMPClauseName(OMPC_schedule);
7883 return true;
7884 }
7885 return false;
7886}
7887
Alexey Bataev56dafe82014-06-20 07:16:17 +00007888OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007889 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007890 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007891 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7892 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7893 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7894 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7895 return nullptr;
7896 // OpenMP, 2.7.1, Loop Construct, Restrictions
7897 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7898 // but not both.
7899 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7900 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7901 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7902 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7903 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7904 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7905 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7906 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7907 return nullptr;
7908 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007909 if (Kind == OMPC_SCHEDULE_unknown) {
7910 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007911 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7912 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7913 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7914 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7915 Exclude);
7916 } else {
7917 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7918 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007919 }
7920 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7921 << Values << getOpenMPClauseName(OMPC_schedule);
7922 return nullptr;
7923 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007924 // OpenMP, 2.7.1, Loop Construct, Restrictions
7925 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7926 // schedule(guided).
7927 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7928 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7929 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7930 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7931 diag::err_omp_schedule_nonmonotonic_static);
7932 return nullptr;
7933 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007934 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007935 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007936 if (ChunkSize) {
7937 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7938 !ChunkSize->isInstantiationDependent() &&
7939 !ChunkSize->containsUnexpandedParameterPack()) {
7940 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7941 ExprResult Val =
7942 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7943 if (Val.isInvalid())
7944 return nullptr;
7945
7946 ValExpr = Val.get();
7947
7948 // OpenMP [2.7.1, Restrictions]
7949 // chunk_size must be a loop invariant integer expression with a positive
7950 // value.
7951 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007952 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7953 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7954 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007955 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007956 return nullptr;
7957 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007958 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7959 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007960 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7961 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7962 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007963 }
7964 }
7965 }
7966
Alexey Bataev6402bca2015-12-28 07:25:51 +00007967 return new (Context)
7968 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007969 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007970}
7971
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007972OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7973 SourceLocation StartLoc,
7974 SourceLocation EndLoc) {
7975 OMPClause *Res = nullptr;
7976 switch (Kind) {
7977 case OMPC_ordered:
7978 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7979 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007980 case OMPC_nowait:
7981 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7982 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007983 case OMPC_untied:
7984 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7985 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007986 case OMPC_mergeable:
7987 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7988 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007989 case OMPC_read:
7990 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7991 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007992 case OMPC_write:
7993 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7994 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007995 case OMPC_update:
7996 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7997 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007998 case OMPC_capture:
7999 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8000 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008001 case OMPC_seq_cst:
8002 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8003 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008004 case OMPC_threads:
8005 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8006 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008007 case OMPC_simd:
8008 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8009 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008010 case OMPC_nogroup:
8011 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8012 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008013 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008014 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008015 case OMPC_num_threads:
8016 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008017 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008018 case OMPC_collapse:
8019 case OMPC_schedule:
8020 case OMPC_private:
8021 case OMPC_firstprivate:
8022 case OMPC_lastprivate:
8023 case OMPC_shared:
8024 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008025 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008026 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008027 case OMPC_linear:
8028 case OMPC_aligned:
8029 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008030 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008031 case OMPC_default:
8032 case OMPC_proc_bind:
8033 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008034 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008035 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008036 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008037 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008038 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008039 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008040 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008041 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008042 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008043 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008044 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008045 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008046 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008047 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008048 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008049 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008050 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008051 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008052 llvm_unreachable("Clause is not allowed.");
8053 }
8054 return Res;
8055}
8056
Alexey Bataev236070f2014-06-20 11:19:47 +00008057OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8058 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008059 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008060 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8061}
8062
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008063OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8064 SourceLocation EndLoc) {
8065 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8066}
8067
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008068OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8069 SourceLocation EndLoc) {
8070 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8071}
8072
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008073OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8074 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008075 return new (Context) OMPReadClause(StartLoc, EndLoc);
8076}
8077
Alexey Bataevdea47612014-07-23 07:46:59 +00008078OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8079 SourceLocation EndLoc) {
8080 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8081}
8082
Alexey Bataev67a4f222014-07-23 10:25:33 +00008083OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8084 SourceLocation EndLoc) {
8085 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8086}
8087
Alexey Bataev459dec02014-07-24 06:46:57 +00008088OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8089 SourceLocation EndLoc) {
8090 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8091}
8092
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008093OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8094 SourceLocation EndLoc) {
8095 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8096}
8097
Alexey Bataev346265e2015-09-25 10:37:12 +00008098OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8099 SourceLocation EndLoc) {
8100 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8101}
8102
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008103OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8104 SourceLocation EndLoc) {
8105 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8106}
8107
Alexey Bataevb825de12015-12-07 10:51:44 +00008108OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8109 SourceLocation EndLoc) {
8110 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8111}
8112
Alexey Bataevc5e02582014-06-16 07:08:35 +00008113OMPClause *Sema::ActOnOpenMPVarListClause(
8114 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8115 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8116 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008117 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008118 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8119 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8120 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008121 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008122 switch (Kind) {
8123 case OMPC_private:
8124 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8125 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008126 case OMPC_firstprivate:
8127 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8128 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008129 case OMPC_lastprivate:
8130 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8131 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008132 case OMPC_shared:
8133 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8134 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008135 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008136 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8137 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008138 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00008139 case OMPC_task_reduction:
8140 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8141 EndLoc, ReductionIdScopeSpec,
8142 ReductionId);
8143 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00008144 case OMPC_in_reduction:
8145 Res =
8146 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
8147 EndLoc, ReductionIdScopeSpec, ReductionId);
8148 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00008149 case OMPC_linear:
8150 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008151 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00008152 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008153 case OMPC_aligned:
8154 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
8155 ColonLoc, EndLoc);
8156 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008157 case OMPC_copyin:
8158 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
8159 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00008160 case OMPC_copyprivate:
8161 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8162 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00008163 case OMPC_flush:
8164 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
8165 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008166 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00008167 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00008168 StartLoc, LParenLoc, EndLoc);
8169 break;
8170 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00008171 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
8172 DepLinMapLoc, ColonLoc, VarList, StartLoc,
8173 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008174 break;
Samuel Antao661c0902016-05-26 17:39:58 +00008175 case OMPC_to:
8176 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
8177 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00008178 case OMPC_from:
8179 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
8180 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00008181 case OMPC_use_device_ptr:
8182 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8183 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00008184 case OMPC_is_device_ptr:
8185 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
8186 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008187 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008188 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008189 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008190 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008191 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008192 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008193 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008194 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008195 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008196 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008197 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008198 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008199 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008200 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008201 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008202 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008203 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008204 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008205 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00008206 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008207 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008208 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008209 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008210 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008211 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008212 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008213 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008214 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008215 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008216 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008217 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008218 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008219 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008220 llvm_unreachable("Clause is not allowed.");
8221 }
8222 return Res;
8223}
8224
Alexey Bataev90c228f2016-02-08 09:29:13 +00008225ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00008226 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00008227 ExprResult Res = BuildDeclRefExpr(
8228 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
8229 if (!Res.isUsable())
8230 return ExprError();
8231 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
8232 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
8233 if (!Res.isUsable())
8234 return ExprError();
8235 }
8236 if (VK != VK_LValue && Res.get()->isGLValue()) {
8237 Res = DefaultLvalueConversion(Res.get());
8238 if (!Res.isUsable())
8239 return ExprError();
8240 }
8241 return Res;
8242}
8243
Alexey Bataev60da77e2016-02-29 05:54:20 +00008244static std::pair<ValueDecl *, bool>
8245getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
8246 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008247 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
8248 RefExpr->containsUnexpandedParameterPack())
8249 return std::make_pair(nullptr, true);
8250
Alexey Bataevd985eda2016-02-10 11:29:16 +00008251 // OpenMP [3.1, C/C++]
8252 // A list item is a variable name.
8253 // OpenMP [2.9.3.3, Restrictions, p.1]
8254 // A variable that is part of another variable (as an array or
8255 // structure element) cannot appear in a private clause.
8256 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008257 enum {
8258 NoArrayExpr = -1,
8259 ArraySubscript = 0,
8260 OMPArraySection = 1
8261 } IsArrayExpr = NoArrayExpr;
8262 if (AllowArraySection) {
8263 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
8264 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
8265 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8266 Base = TempASE->getBase()->IgnoreParenImpCasts();
8267 RefExpr = Base;
8268 IsArrayExpr = ArraySubscript;
8269 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
8270 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
8271 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
8272 Base = TempOASE->getBase()->IgnoreParenImpCasts();
8273 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
8274 Base = TempASE->getBase()->IgnoreParenImpCasts();
8275 RefExpr = Base;
8276 IsArrayExpr = OMPArraySection;
8277 }
8278 }
8279 ELoc = RefExpr->getExprLoc();
8280 ERange = RefExpr->getSourceRange();
8281 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008282 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
8283 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
8284 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
8285 (S.getCurrentThisType().isNull() || !ME ||
8286 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
8287 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008288 if (IsArrayExpr != NoArrayExpr)
8289 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
8290 << ERange;
8291 else {
8292 S.Diag(ELoc,
8293 AllowArraySection
8294 ? diag::err_omp_expected_var_name_member_expr_or_array_item
8295 : diag::err_omp_expected_var_name_member_expr)
8296 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
8297 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008298 return std::make_pair(nullptr, false);
8299 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00008300 return std::make_pair(
8301 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008302}
8303
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008304OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8305 SourceLocation StartLoc,
8306 SourceLocation LParenLoc,
8307 SourceLocation EndLoc) {
8308 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00008309 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00008310 for (auto &RefExpr : VarList) {
8311 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008312 SourceLocation ELoc;
8313 SourceRange ERange;
8314 Expr *SimpleRefExpr = RefExpr;
8315 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008316 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008317 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008318 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008319 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008320 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008321 ValueDecl *D = Res.first;
8322 if (!D)
8323 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008324
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008325 QualType Type = D->getType();
8326 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008327
8328 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8329 // A variable that appears in a private clause must not have an incomplete
8330 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008331 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008332 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008333 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008334
Alexey Bataev758e55e2013-09-06 18:03:48 +00008335 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8336 // in a Construct]
8337 // Variables with the predetermined data-sharing attributes may not be
8338 // listed in data-sharing attributes clauses, except for the cases
8339 // listed below. For these exceptions only, listing a predetermined
8340 // variable in a data-sharing attribute clause is allowed and overrides
8341 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008342 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008343 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00008344 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8345 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008346 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008347 continue;
8348 }
8349
Kelvin Libf594a52016-12-17 05:48:59 +00008350 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008351 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008352 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00008353 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008354 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8355 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00008356 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008357 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008358 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008359 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008360 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008361 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008362 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008363 continue;
8364 }
8365
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008366 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8367 // A list item cannot appear in both a map clause and a data-sharing
8368 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008369 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008370 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008371 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008372 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008373 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008374 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008375 CurrDir == OMPD_target_parallel_for_simd ||
8376 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008377 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008378 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008379 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008380 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8381 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8382 ConflictKind = WhereFoundClauseKind;
8383 return true;
8384 })) {
8385 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008386 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00008387 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00008388 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008389 ReportOriginalDSA(*this, DSAStack, D, DVar);
8390 continue;
8391 }
8392 }
8393
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008394 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
8395 // A variable of class type (or array thereof) that appears in a private
8396 // clause requires an accessible, unambiguous default constructor for the
8397 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00008398 // Generate helper private variable and initialize it with the default
8399 // value. The address of the original variable is replaced by the address of
8400 // the new private variable in CodeGen. This new variable is not added to
8401 // IdResolver, so the code in the OpenMP region uses original variable for
8402 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008403 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008404 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8405 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00008406 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008407 if (VDPrivate->isInvalidDecl())
8408 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008409 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00008410 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008411
Alexey Bataev90c228f2016-02-08 09:29:13 +00008412 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008413 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008414 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00008415 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008416 Vars.push_back((VD || CurContext->isDependentContext())
8417 ? RefExpr->IgnoreParens()
8418 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00008419 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008420 }
8421
Alexey Bataeved09d242014-05-28 05:53:51 +00008422 if (Vars.empty())
8423 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008424
Alexey Bataev03b340a2014-10-21 03:16:40 +00008425 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
8426 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008427}
8428
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008429namespace {
8430class DiagsUninitializedSeveretyRAII {
8431private:
8432 DiagnosticsEngine &Diags;
8433 SourceLocation SavedLoc;
8434 bool IsIgnored;
8435
8436public:
8437 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
8438 bool IsIgnored)
8439 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
8440 if (!IsIgnored) {
8441 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
8442 /*Map*/ diag::Severity::Ignored, Loc);
8443 }
8444 }
8445 ~DiagsUninitializedSeveretyRAII() {
8446 if (!IsIgnored)
8447 Diags.popMappings(SavedLoc);
8448 }
8449};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008450}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008451
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008452OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8453 SourceLocation StartLoc,
8454 SourceLocation LParenLoc,
8455 SourceLocation EndLoc) {
8456 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008457 SmallVector<Expr *, 8> PrivateCopies;
8458 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00008459 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008460 bool IsImplicitClause =
8461 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
8462 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
8463
Alexey Bataeved09d242014-05-28 05:53:51 +00008464 for (auto &RefExpr : VarList) {
8465 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008466 SourceLocation ELoc;
8467 SourceRange ERange;
8468 Expr *SimpleRefExpr = RefExpr;
8469 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008470 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008471 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008472 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008473 PrivateCopies.push_back(nullptr);
8474 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008475 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008476 ValueDecl *D = Res.first;
8477 if (!D)
8478 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008479
Alexey Bataev60da77e2016-02-29 05:54:20 +00008480 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008481 QualType Type = D->getType();
8482 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008483
8484 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8485 // A variable that appears in a private clause must not have an incomplete
8486 // type or a reference type.
8487 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00008488 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008489 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008490 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008491
8492 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
8493 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00008494 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008495 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008496 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008497
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008498 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00008499 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008500 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008501 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008502 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008503 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008504 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008505 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
8506 // A list item that specifies a given variable may not appear in more
8507 // than one clause on the same directive, except that a variable may be
8508 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008509 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8510 // A list item may appear in a firstprivate or lastprivate clause but not
8511 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008512 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008513 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) &&
8514 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008515 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008516 << getOpenMPClauseName(DVar.CKind)
8517 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008518 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008519 continue;
8520 }
8521
8522 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8523 // in a Construct]
8524 // Variables with the predetermined data-sharing attributes may not be
8525 // listed in data-sharing attributes clauses, except for the cases
8526 // listed below. For these exceptions only, listing a predetermined
8527 // variable in a data-sharing attribute clause is allowed and overrides
8528 // the variable's predetermined data-sharing attributes.
8529 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8530 // in a Construct, C/C++, p.2]
8531 // Variables with const-qualified type having no mutable member may be
8532 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008533 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008534 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8535 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008536 << getOpenMPClauseName(DVar.CKind)
8537 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008538 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008539 continue;
8540 }
8541
8542 // OpenMP [2.9.3.4, Restrictions, p.2]
8543 // A list item that is private within a parallel region must not appear
8544 // in a firstprivate clause on a worksharing construct if any of the
8545 // worksharing regions arising from the worksharing construct ever bind
8546 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008547 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8548 // A list item that is private within a teams region must not appear in a
8549 // firstprivate clause on a distribute construct if any of the distribute
8550 // regions arising from the distribute construct ever bind to any of the
8551 // teams regions arising from the teams construct.
8552 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8553 // A list item that appears in a reduction clause of a teams construct
8554 // must not appear in a firstprivate clause on a distribute construct if
8555 // any of the distribute regions arising from the distribute construct
8556 // ever bind to any of the teams regions arising from the teams construct.
8557 if ((isOpenMPWorksharingDirective(CurrDir) ||
8558 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008559 !isOpenMPParallelDirective(CurrDir) &&
8560 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008561 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008562 if (DVar.CKind != OMPC_shared &&
8563 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008564 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008565 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008566 Diag(ELoc, diag::err_omp_required_access)
8567 << getOpenMPClauseName(OMPC_firstprivate)
8568 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008569 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008570 continue;
8571 }
8572 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008573 // OpenMP [2.9.3.4, Restrictions, p.3]
8574 // A list item that appears in a reduction clause of a parallel construct
8575 // must not appear in a firstprivate clause on a worksharing or task
8576 // construct if any of the worksharing or task regions arising from the
8577 // worksharing or task construct ever bind to any of the parallel regions
8578 // arising from the parallel construct.
8579 // OpenMP [2.9.3.4, Restrictions, p.4]
8580 // A list item that appears in a reduction clause in worksharing
8581 // construct must not appear in a firstprivate clause in a task construct
8582 // encountered during execution of any of the worksharing regions arising
8583 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008584 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008585 DVar = DSAStack->hasInnermostDSA(
8586 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8587 [](OpenMPDirectiveKind K) -> bool {
8588 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008589 isOpenMPWorksharingDirective(K) ||
8590 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008591 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008592 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008593 if (DVar.CKind == OMPC_reduction &&
8594 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008595 isOpenMPWorksharingDirective(DVar.DKind) ||
8596 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008597 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8598 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008599 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008600 continue;
8601 }
8602 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008603
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008604 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8605 // A list item cannot appear in both a map clause and a data-sharing
8606 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008607 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008608 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008609 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008610 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008611 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008612 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008613 CurrDir == OMPD_target_parallel_for_simd ||
8614 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008615 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008616 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008617 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008618 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8619 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8620 ConflictKind = WhereFoundClauseKind;
8621 return true;
8622 })) {
8623 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008624 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008625 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008626 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8627 ReportOriginalDSA(*this, DSAStack, D, DVar);
8628 continue;
8629 }
8630 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008631 }
8632
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008633 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008634 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008635 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008636 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8637 << getOpenMPClauseName(OMPC_firstprivate) << Type
8638 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8639 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008640 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008641 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008642 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008643 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008644 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008645 continue;
8646 }
8647
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008648 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008649 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8650 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008651 // Generate helper private variable and initialize it with the value of the
8652 // original variable. The address of the original variable is replaced by
8653 // the address of the new private variable in the CodeGen. This new variable
8654 // is not added to IdResolver, so the code in the OpenMP region uses
8655 // original variable for proper diagnostics and variable capturing.
8656 Expr *VDInitRefExpr = nullptr;
8657 // For arrays generate initializer for single element and replace it by the
8658 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008659 if (Type->isArrayType()) {
8660 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008661 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008662 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008663 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008664 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008665 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008666 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008667 InitializedEntity Entity =
8668 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008669 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8670
8671 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8672 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8673 if (Result.isInvalid())
8674 VDPrivate->setInvalidDecl();
8675 else
8676 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008677 // Remove temp variable declaration.
8678 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008679 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008680 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8681 ".firstprivate.temp");
8682 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8683 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008684 AddInitializerToDecl(VDPrivate,
8685 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008686 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008687 }
8688 if (VDPrivate->isInvalidDecl()) {
8689 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008690 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008691 diag::note_omp_task_predetermined_firstprivate_here);
8692 }
8693 continue;
8694 }
8695 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008696 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008697 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8698 RefExpr->getExprLoc());
8699 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008700 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008701 if (TopDVar.CKind == OMPC_lastprivate)
8702 Ref = TopDVar.PrivateCopy;
8703 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008704 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008705 if (!IsOpenMPCapturedDecl(D))
8706 ExprCaptures.push_back(Ref->getDecl());
8707 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008708 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008709 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008710 Vars.push_back((VD || CurContext->isDependentContext())
8711 ? RefExpr->IgnoreParens()
8712 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008713 PrivateCopies.push_back(VDPrivateRefExpr);
8714 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008715 }
8716
Alexey Bataeved09d242014-05-28 05:53:51 +00008717 if (Vars.empty())
8718 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008719
8720 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008721 Vars, PrivateCopies, Inits,
8722 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008723}
8724
Alexander Musman1bb328c2014-06-04 13:06:39 +00008725OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8726 SourceLocation StartLoc,
8727 SourceLocation LParenLoc,
8728 SourceLocation EndLoc) {
8729 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008730 SmallVector<Expr *, 8> SrcExprs;
8731 SmallVector<Expr *, 8> DstExprs;
8732 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008733 SmallVector<Decl *, 4> ExprCaptures;
8734 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008735 for (auto &RefExpr : VarList) {
8736 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008737 SourceLocation ELoc;
8738 SourceRange ERange;
8739 Expr *SimpleRefExpr = RefExpr;
8740 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008741 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008742 // It will be analyzed later.
8743 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008744 SrcExprs.push_back(nullptr);
8745 DstExprs.push_back(nullptr);
8746 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008747 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008748 ValueDecl *D = Res.first;
8749 if (!D)
8750 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008751
Alexey Bataev74caaf22016-02-20 04:09:36 +00008752 QualType Type = D->getType();
8753 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008754
8755 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8756 // A variable that appears in a lastprivate clause must not have an
8757 // incomplete type or a reference type.
8758 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008759 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008760 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008761 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008762
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008763 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008764 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8765 // in a Construct]
8766 // Variables with the predetermined data-sharing attributes may not be
8767 // listed in data-sharing attributes clauses, except for the cases
8768 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008769 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8770 // A list item may appear in a firstprivate or lastprivate clause but not
8771 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008772 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008773 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008774 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00008775 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8776 Diag(ELoc, diag::err_omp_wrong_dsa)
8777 << getOpenMPClauseName(DVar.CKind)
8778 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008779 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008780 continue;
8781 }
8782
Alexey Bataevf29276e2014-06-18 04:14:57 +00008783 // OpenMP [2.14.3.5, Restrictions, p.2]
8784 // A list item that is private within a parallel region, or that appears in
8785 // the reduction clause of a parallel construct, must not appear in a
8786 // lastprivate clause on a worksharing construct if any of the corresponding
8787 // worksharing regions ever binds to any of the corresponding parallel
8788 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008789 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008790 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008791 !isOpenMPParallelDirective(CurrDir) &&
8792 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008793 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008794 if (DVar.CKind != OMPC_shared) {
8795 Diag(ELoc, diag::err_omp_required_access)
8796 << getOpenMPClauseName(OMPC_lastprivate)
8797 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008798 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008799 continue;
8800 }
8801 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008802
Alexander Musman1bb328c2014-06-04 13:06:39 +00008803 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008804 // A variable of class type (or array thereof) that appears in a
8805 // lastprivate clause requires an accessible, unambiguous default
8806 // constructor for the class type, unless the list item is also specified
8807 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008808 // A variable of class type (or array thereof) that appears in a
8809 // lastprivate clause requires an accessible, unambiguous copy assignment
8810 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008811 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008812 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008813 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008814 D->hasAttrs() ? &D->getAttrs() : nullptr);
8815 auto *PseudoSrcExpr =
8816 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008817 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008818 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008819 D->hasAttrs() ? &D->getAttrs() : nullptr);
8820 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008821 // For arrays generate assignment operation for single element and replace
8822 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008823 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008824 PseudoDstExpr, PseudoSrcExpr);
8825 if (AssignmentOp.isInvalid())
8826 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008827 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008828 /*DiscardedValue=*/true);
8829 if (AssignmentOp.isInvalid())
8830 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008831
Alexey Bataev74caaf22016-02-20 04:09:36 +00008832 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008833 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008834 if (TopDVar.CKind == OMPC_firstprivate)
8835 Ref = TopDVar.PrivateCopy;
8836 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008837 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008838 if (!IsOpenMPCapturedDecl(D))
8839 ExprCaptures.push_back(Ref->getDecl());
8840 }
8841 if (TopDVar.CKind == OMPC_firstprivate ||
8842 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008843 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008844 ExprResult RefRes = DefaultLvalueConversion(Ref);
8845 if (!RefRes.isUsable())
8846 continue;
8847 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008848 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8849 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008850 if (!PostUpdateRes.isUsable())
8851 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008852 ExprPostUpdates.push_back(
8853 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008854 }
8855 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008856 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008857 Vars.push_back((VD || CurContext->isDependentContext())
8858 ? RefExpr->IgnoreParens()
8859 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008860 SrcExprs.push_back(PseudoSrcExpr);
8861 DstExprs.push_back(PseudoDstExpr);
8862 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008863 }
8864
8865 if (Vars.empty())
8866 return nullptr;
8867
8868 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008869 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008870 buildPreInits(Context, ExprCaptures),
8871 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008872}
8873
Alexey Bataev758e55e2013-09-06 18:03:48 +00008874OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8875 SourceLocation StartLoc,
8876 SourceLocation LParenLoc,
8877 SourceLocation EndLoc) {
8878 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008879 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008880 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008881 SourceLocation ELoc;
8882 SourceRange ERange;
8883 Expr *SimpleRefExpr = RefExpr;
8884 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008885 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008886 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008887 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008888 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008889 ValueDecl *D = Res.first;
8890 if (!D)
8891 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008892
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008893 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008894 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8895 // in a Construct]
8896 // Variables with the predetermined data-sharing attributes may not be
8897 // listed in data-sharing attributes clauses, except for the cases
8898 // listed below. For these exceptions only, listing a predetermined
8899 // variable in a data-sharing attribute clause is allowed and overrides
8900 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008901 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008902 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8903 DVar.RefExpr) {
8904 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8905 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008906 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008907 continue;
8908 }
8909
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008910 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008911 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008912 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008913 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008914 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8915 ? RefExpr->IgnoreParens()
8916 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008917 }
8918
Alexey Bataeved09d242014-05-28 05:53:51 +00008919 if (Vars.empty())
8920 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008921
8922 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8923}
8924
Alexey Bataevc5e02582014-06-16 07:08:35 +00008925namespace {
8926class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8927 DSAStackTy *Stack;
8928
8929public:
8930 bool VisitDeclRefExpr(DeclRefExpr *E) {
8931 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008932 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008933 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8934 return false;
8935 if (DVar.CKind != OMPC_unknown)
8936 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008937 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8938 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00008939 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008940 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008941 return true;
8942 return false;
8943 }
8944 return false;
8945 }
8946 bool VisitStmt(Stmt *S) {
8947 for (auto Child : S->children()) {
8948 if (Child && Visit(Child))
8949 return true;
8950 }
8951 return false;
8952 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008953 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008954};
Alexey Bataev23b69422014-06-18 07:08:49 +00008955} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008956
Alexey Bataev60da77e2016-02-29 05:54:20 +00008957namespace {
8958// Transform MemberExpression for specified FieldDecl of current class to
8959// DeclRefExpr to specified OMPCapturedExprDecl.
8960class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8961 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8962 ValueDecl *Field;
8963 DeclRefExpr *CapturedExpr;
8964
8965public:
8966 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8967 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8968
8969 ExprResult TransformMemberExpr(MemberExpr *E) {
8970 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8971 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008972 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008973 return CapturedExpr;
8974 }
8975 return BaseTransform::TransformMemberExpr(E);
8976 }
8977 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8978};
8979} // namespace
8980
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008981template <typename T>
8982static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8983 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8984 for (auto &Set : Lookups) {
8985 for (auto *D : Set) {
8986 if (auto Res = Gen(cast<ValueDecl>(D)))
8987 return Res;
8988 }
8989 }
8990 return T();
8991}
8992
8993static ExprResult
8994buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8995 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8996 const DeclarationNameInfo &ReductionId, QualType Ty,
8997 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8998 if (ReductionIdScopeSpec.isInvalid())
8999 return ExprError();
9000 SmallVector<UnresolvedSet<8>, 4> Lookups;
9001 if (S) {
9002 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9003 Lookup.suppressDiagnostics();
9004 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9005 auto *D = Lookup.getRepresentativeDecl();
9006 do {
9007 S = S->getParent();
9008 } while (S && !S->isDeclScope(D));
9009 if (S)
9010 S = S->getParent();
9011 Lookups.push_back(UnresolvedSet<8>());
9012 Lookups.back().append(Lookup.begin(), Lookup.end());
9013 Lookup.clear();
9014 }
9015 } else if (auto *ULE =
9016 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9017 Lookups.push_back(UnresolvedSet<8>());
9018 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009019 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009020 if (D == PrevD)
9021 Lookups.push_back(UnresolvedSet<8>());
9022 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9023 Lookups.back().addDecl(DRD);
9024 PrevD = D;
9025 }
9026 }
9027 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
9028 Ty->containsUnexpandedParameterPack() ||
9029 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9030 return !D->isInvalidDecl() &&
9031 (D->getType()->isDependentType() ||
9032 D->getType()->isInstantiationDependentType() ||
9033 D->getType()->containsUnexpandedParameterPack());
9034 })) {
9035 UnresolvedSet<8> ResSet;
9036 for (auto &Set : Lookups) {
9037 ResSet.append(Set.begin(), Set.end());
9038 // The last item marks the end of all declarations at the specified scope.
9039 ResSet.addDecl(Set[Set.size() - 1]);
9040 }
9041 return UnresolvedLookupExpr::Create(
9042 SemaRef.Context, /*NamingClass=*/nullptr,
9043 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9044 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9045 }
9046 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9047 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9048 if (!D->isInvalidDecl() &&
9049 SemaRef.Context.hasSameType(D->getType(), Ty))
9050 return D;
9051 return nullptr;
9052 }))
9053 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9054 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9055 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9056 if (!D->isInvalidDecl() &&
9057 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9058 !Ty.isMoreQualifiedThan(D->getType()))
9059 return D;
9060 return nullptr;
9061 })) {
9062 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9063 /*DetectVirtual=*/false);
9064 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9065 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9066 VD->getType().getUnqualifiedType()))) {
9067 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9068 /*DiagID=*/0) !=
9069 Sema::AR_inaccessible) {
9070 SemaRef.BuildBasePathArray(Paths, BasePath);
9071 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9072 }
9073 }
9074 }
9075 }
9076 if (ReductionIdScopeSpec.isSet()) {
9077 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9078 return ExprError();
9079 }
9080 return ExprEmpty();
9081}
9082
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009083namespace {
9084/// Data for the reduction-based clauses.
9085struct ReductionData {
9086 /// List of original reduction items.
9087 SmallVector<Expr *, 8> Vars;
9088 /// List of private copies of the reduction items.
9089 SmallVector<Expr *, 8> Privates;
9090 /// LHS expressions for the reduction_op expressions.
9091 SmallVector<Expr *, 8> LHSs;
9092 /// RHS expressions for the reduction_op expressions.
9093 SmallVector<Expr *, 8> RHSs;
9094 /// Reduction operation expression.
9095 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009096 /// Taskgroup descriptors for the corresponding reduction items in
9097 /// in_reduction clauses.
9098 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009099 /// List of captures for clause.
9100 SmallVector<Decl *, 4> ExprCaptures;
9101 /// List of postupdate expressions.
9102 SmallVector<Expr *, 4> ExprPostUpdates;
9103 ReductionData() = delete;
9104 /// Reserves required memory for the reduction data.
9105 ReductionData(unsigned Size) {
9106 Vars.reserve(Size);
9107 Privates.reserve(Size);
9108 LHSs.reserve(Size);
9109 RHSs.reserve(Size);
9110 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009111 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009112 ExprCaptures.reserve(Size);
9113 ExprPostUpdates.reserve(Size);
9114 }
9115 /// Stores reduction item and reduction operation only (required for dependent
9116 /// reduction item).
9117 void push(Expr *Item, Expr *ReductionOp) {
9118 Vars.emplace_back(Item);
9119 Privates.emplace_back(nullptr);
9120 LHSs.emplace_back(nullptr);
9121 RHSs.emplace_back(nullptr);
9122 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009123 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009124 }
9125 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009126 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9127 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009128 Vars.emplace_back(Item);
9129 Privates.emplace_back(Private);
9130 LHSs.emplace_back(LHS);
9131 RHSs.emplace_back(RHS);
9132 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009133 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009134 }
9135};
9136} // namespace
9137
9138static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +00009139 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
9140 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9141 SourceLocation ColonLoc, SourceLocation EndLoc,
9142 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009143 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009144 auto DN = ReductionId.getName();
9145 auto OOK = DN.getCXXOverloadedOperator();
9146 BinaryOperatorKind BOK = BO_Comma;
9147
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009148 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009149 // OpenMP [2.14.3.6, reduction clause]
9150 // C
9151 // reduction-identifier is either an identifier or one of the following
9152 // operators: +, -, *, &, |, ^, && and ||
9153 // C++
9154 // reduction-identifier is either an id-expression or one of the following
9155 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +00009156 switch (OOK) {
9157 case OO_Plus:
9158 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009159 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009160 break;
9161 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009162 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009163 break;
9164 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009165 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009166 break;
9167 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009168 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009169 break;
9170 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009171 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009172 break;
9173 case OO_AmpAmp:
9174 BOK = BO_LAnd;
9175 break;
9176 case OO_PipePipe:
9177 BOK = BO_LOr;
9178 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009179 case OO_New:
9180 case OO_Delete:
9181 case OO_Array_New:
9182 case OO_Array_Delete:
9183 case OO_Slash:
9184 case OO_Percent:
9185 case OO_Tilde:
9186 case OO_Exclaim:
9187 case OO_Equal:
9188 case OO_Less:
9189 case OO_Greater:
9190 case OO_LessEqual:
9191 case OO_GreaterEqual:
9192 case OO_PlusEqual:
9193 case OO_MinusEqual:
9194 case OO_StarEqual:
9195 case OO_SlashEqual:
9196 case OO_PercentEqual:
9197 case OO_CaretEqual:
9198 case OO_AmpEqual:
9199 case OO_PipeEqual:
9200 case OO_LessLess:
9201 case OO_GreaterGreater:
9202 case OO_LessLessEqual:
9203 case OO_GreaterGreaterEqual:
9204 case OO_EqualEqual:
9205 case OO_ExclaimEqual:
9206 case OO_PlusPlus:
9207 case OO_MinusMinus:
9208 case OO_Comma:
9209 case OO_ArrowStar:
9210 case OO_Arrow:
9211 case OO_Call:
9212 case OO_Subscript:
9213 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00009214 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009215 case NUM_OVERLOADED_OPERATORS:
9216 llvm_unreachable("Unexpected reduction identifier");
9217 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009218 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00009219 if (II->isStr("max"))
9220 BOK = BO_GT;
9221 else if (II->isStr("min"))
9222 BOK = BO_LT;
9223 }
9224 break;
9225 }
9226 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009227 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00009228 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009229 else
9230 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009231 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009232
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009233 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
9234 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009235 for (auto RefExpr : VarList) {
9236 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00009237 // OpenMP [2.1, C/C++]
9238 // A list item is a variable or array section, subject to the restrictions
9239 // specified in Section 2.4 on page 42 and in each of the sections
9240 // describing clauses and directives for which a list appears.
9241 // OpenMP [2.14.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.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009244 if (!FirstIter && IR != ER)
9245 ++IR;
9246 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009247 SourceLocation ELoc;
9248 SourceRange ERange;
9249 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009250 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +00009251 /*AllowArraySection=*/true);
9252 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009253 // Try to find 'declare reduction' corresponding construct before using
9254 // builtin/overloaded operators.
9255 QualType Type = Context.DependentTy;
9256 CXXCastPath BasePath;
9257 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009258 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009259 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009260 Expr *ReductionOp = nullptr;
9261 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009262 (DeclareReductionRef.isUnset() ||
9263 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009264 ReductionOp = DeclareReductionRef.get();
9265 // It will be analyzed later.
9266 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009267 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009268 ValueDecl *D = Res.first;
9269 if (!D)
9270 continue;
9271
Alexey Bataev88202be2017-07-27 13:20:36 +00009272 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +00009273 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009274 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
9275 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
9276 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00009277 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009278 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009279 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
9280 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
9281 Type = ATy->getElementType();
9282 else
9283 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00009284 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009285 } else
9286 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
9287 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00009288
Alexey Bataevc5e02582014-06-16 07:08:35 +00009289 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9290 // A variable that appears in a private clause must not have an incomplete
9291 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009292 if (S.RequireCompleteType(ELoc, Type,
9293 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009294 continue;
9295 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00009296 // A list item that appears in a reduction clause must not be
9297 // const-qualified.
9298 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009299 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009300 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009301 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9302 VarDecl::DeclarationOnly;
9303 S.Diag(D->getLocation(),
9304 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009305 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00009306 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009307 continue;
9308 }
9309 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
9310 // If a list-item is a reference type then it must bind to the same object
9311 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00009312 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00009313 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00009314 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009315 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +00009316 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009317 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
9318 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009319 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +00009320 continue;
9321 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00009322 }
9323 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009324
Alexey Bataevc5e02582014-06-16 07:08:35 +00009325 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9326 // in a Construct]
9327 // Variables with the predetermined data-sharing attributes may not be
9328 // listed in data-sharing attributes clauses, except for the cases
9329 // listed below. For these exceptions only, listing a predetermined
9330 // variable in a data-sharing attribute clause is allowed and overrides
9331 // the variable's predetermined data-sharing attributes.
9332 // OpenMP [2.14.3.6, Restrictions, p.3]
9333 // Any number of reduction clauses can be specified on the directive,
9334 // but a list item can appear only once in the reduction clauses for that
9335 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00009336 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009337 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009338 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009339 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009340 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009341 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009342 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009343 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009344 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009345 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009346 << getOpenMPClauseName(DVar.CKind)
9347 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009348 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009349 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009350 }
9351
9352 // OpenMP [2.14.3.6, Restrictions, p.1]
9353 // A list item that appears in a reduction clause of a worksharing
9354 // construct must be shared in the parallel regions to which any of the
9355 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009356 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009357 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009358 !isOpenMPParallelDirective(CurrDir) &&
9359 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009360 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009361 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009362 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009363 << getOpenMPClauseName(OMPC_reduction)
9364 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009365 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009366 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00009367 }
9368 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009369
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009370 // Try to find 'declare reduction' corresponding construct before using
9371 // builtin/overloaded operators.
9372 CXXCastPath BasePath;
9373 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009374 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009375 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
9376 if (DeclareReductionRef.isInvalid())
9377 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009378 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009379 (DeclareReductionRef.isUnset() ||
9380 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009381 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009382 continue;
9383 }
9384 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
9385 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009386 S.Diag(ReductionId.getLocStart(),
9387 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009388 << Type << ReductionIdRange;
9389 continue;
9390 }
9391
9392 // OpenMP [2.14.3.6, reduction clause, Restrictions]
9393 // The type of a list item that appears in a reduction clause must be valid
9394 // for the reduction-identifier. For a max or min reduction in C, the type
9395 // of the list item must be an allowed arithmetic data type: char, int,
9396 // float, double, or _Bool, possibly modified with long, short, signed, or
9397 // unsigned. For a max or min reduction in C++, the type of the list item
9398 // must be an allowed arithmetic data type: char, wchar_t, int, float,
9399 // double, or bool, possibly modified with long, short, signed, or unsigned.
9400 if (DeclareReductionRef.isUnset()) {
9401 if ((BOK == BO_GT || BOK == BO_LT) &&
9402 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009403 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
9404 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +00009405 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009406 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009407 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9408 VarDecl::DeclarationOnly;
9409 S.Diag(D->getLocation(),
9410 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009411 << D;
9412 }
9413 continue;
9414 }
9415 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009416 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +00009417 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
9418 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009419 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009420 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9421 VarDecl::DeclarationOnly;
9422 S.Diag(D->getLocation(),
9423 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009424 << D;
9425 }
9426 continue;
9427 }
9428 }
9429
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009430 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009431 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00009432 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009433 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009434 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009435 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00009436 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00009437 (!ASE &&
9438 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00009439 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009440 // Create pseudo array type for private copy. The size for this array will
9441 // be generated during codegen.
9442 // For array subscripts or single variables Private Ty is the same as Type
9443 // (type of the variable or single array element).
9444 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009445 Type,
9446 new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(),
9447 VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009448 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00009449 } else if (!ASE && !OASE &&
9450 Context.getAsArrayType(D->getType().getNonReferenceType()))
9451 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009452 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009453 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +00009454 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009455 // Add initializer for private variable.
9456 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009457 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
9458 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009459 if (DeclareReductionRef.isUsable()) {
9460 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
9461 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
9462 if (DRD->getInitializer()) {
9463 Init = DRDRef;
9464 RHSVD->setInit(DRDRef);
9465 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009466 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009467 } else {
9468 switch (BOK) {
9469 case BO_Add:
9470 case BO_Xor:
9471 case BO_Or:
9472 case BO_LOr:
9473 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
9474 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009475 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009476 break;
9477 case BO_Mul:
9478 case BO_LAnd:
9479 if (Type->isScalarType() || Type->isAnyComplexType()) {
9480 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009481 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00009482 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009483 break;
9484 case BO_And: {
9485 // '&' reduction op - initializer is '~0'.
9486 QualType OrigType = Type;
9487 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
9488 Type = ComplexTy->getElementType();
9489 if (Type->isRealFloatingType()) {
9490 llvm::APFloat InitValue =
9491 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
9492 /*isIEEE=*/true);
9493 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9494 Type, ELoc);
9495 } else if (Type->isScalarType()) {
9496 auto Size = Context.getTypeSize(Type);
9497 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
9498 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
9499 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9500 }
9501 if (Init && OrigType->isAnyComplexType()) {
9502 // Init = 0xFFFF + 0xFFFFi;
9503 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009504 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009505 }
9506 Type = OrigType;
9507 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009508 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009509 case BO_LT:
9510 case BO_GT: {
9511 // 'min' reduction op - initializer is 'Largest representable number in
9512 // the reduction list item type'.
9513 // 'max' reduction op - initializer is 'Least representable number in
9514 // the reduction list item type'.
9515 if (Type->isIntegerType() || Type->isPointerType()) {
9516 bool IsSigned = Type->hasSignedIntegerRepresentation();
9517 auto Size = Context.getTypeSize(Type);
9518 QualType IntTy =
9519 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
9520 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009521 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
9522 : llvm::APInt::getMinValue(Size)
9523 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
9524 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009525 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
9526 if (Type->isPointerType()) {
9527 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009528 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009529 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
9530 SourceLocation(), Init);
9531 if (CastExpr.isInvalid())
9532 continue;
9533 Init = CastExpr.get();
9534 }
9535 } else if (Type->isRealFloatingType()) {
9536 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9537 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9538 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9539 Type, ELoc);
9540 }
9541 break;
9542 }
9543 case BO_PtrMemD:
9544 case BO_PtrMemI:
9545 case BO_MulAssign:
9546 case BO_Div:
9547 case BO_Rem:
9548 case BO_Sub:
9549 case BO_Shl:
9550 case BO_Shr:
9551 case BO_LE:
9552 case BO_GE:
9553 case BO_EQ:
9554 case BO_NE:
9555 case BO_AndAssign:
9556 case BO_XorAssign:
9557 case BO_OrAssign:
9558 case BO_Assign:
9559 case BO_AddAssign:
9560 case BO_SubAssign:
9561 case BO_DivAssign:
9562 case BO_RemAssign:
9563 case BO_ShlAssign:
9564 case BO_ShrAssign:
9565 case BO_Comma:
9566 llvm_unreachable("Unexpected reduction operation");
9567 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009568 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009569 if (Init && DeclareReductionRef.isUnset())
9570 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
9571 else if (!Init)
9572 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009573 if (RHSVD->isInvalidDecl())
9574 continue;
9575 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009576 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
9577 << Type << ReductionIdRange;
9578 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
9579 VarDecl::DeclarationOnly;
9580 S.Diag(D->getLocation(),
9581 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00009582 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009583 continue;
9584 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009585 // Store initializer for single element in private copy. Will be used during
9586 // codegen.
9587 PrivateVD->setInit(RHSVD->getInit());
9588 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009589 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009590 ExprResult ReductionOp;
9591 if (DeclareReductionRef.isUsable()) {
9592 QualType RedTy = DeclareReductionRef.get()->getType();
9593 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009594 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9595 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009596 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009597 LHS = S.DefaultLvalueConversion(LHS.get());
9598 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009599 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9600 CK_UncheckedDerivedToBase, LHS.get(),
9601 &BasePath, LHS.get()->getValueKind());
9602 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9603 CK_UncheckedDerivedToBase, RHS.get(),
9604 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009605 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009606 FunctionProtoType::ExtProtoInfo EPI;
9607 QualType Params[] = {PtrRedTy, PtrRedTy};
9608 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9609 auto *OVE = new (Context) OpaqueValueExpr(
9610 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009611 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009612 Expr *Args[] = {LHS.get(), RHS.get()};
9613 ReductionOp = new (Context)
9614 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9615 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009616 ReductionOp = S.BuildBinOp(
9617 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009618 if (ReductionOp.isUsable()) {
9619 if (BOK != BO_LT && BOK != BO_GT) {
9620 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009621 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9622 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009623 } else {
9624 auto *ConditionalOp = new (Context) ConditionalOperator(
9625 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9626 RHSDRE, Type, VK_LValue, OK_Ordinary);
9627 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009628 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
9629 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009630 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009631 if (ReductionOp.isUsable())
9632 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009633 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009634 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009635 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009636 }
9637
Alexey Bataevfa312f32017-07-21 18:48:21 +00009638 // OpenMP [2.15.4.6, Restrictions, p.2]
9639 // A list item that appears in an in_reduction clause of a task construct
9640 // must appear in a task_reduction clause of a construct associated with a
9641 // taskgroup region that includes the participating task in its taskgroup
9642 // set. The construct associated with the innermost region that meets this
9643 // condition must specify the same reduction-identifier as the in_reduction
9644 // clause.
9645 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00009646 SourceRange ParentSR;
9647 BinaryOperatorKind ParentBOK;
9648 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +00009649 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +00009650 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +00009651 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
9652 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009653 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +00009654 Stack->getTopMostTaskgroupReductionData(
9655 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009656 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
9657 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
9658 if (!IsParentBOK && !IsParentReductionOp) {
9659 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
9660 continue;
9661 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00009662 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
9663 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
9664 IsParentReductionOp) {
9665 bool EmitError = true;
9666 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
9667 llvm::FoldingSetNodeID RedId, ParentRedId;
9668 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
9669 DeclareReductionRef.get()->Profile(RedId, Context,
9670 /*Canonical=*/true);
9671 EmitError = RedId != ParentRedId;
9672 }
9673 if (EmitError) {
9674 S.Diag(ReductionId.getLocStart(),
9675 diag::err_omp_reduction_identifier_mismatch)
9676 << ReductionIdRange << RefExpr->getSourceRange();
9677 S.Diag(ParentSR.getBegin(),
9678 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +00009679 << ParentSR
9680 << (IsParentBOK ? ParentBOKDSA.RefExpr
9681 : ParentReductionOpDSA.RefExpr)
9682 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +00009683 continue;
9684 }
9685 }
Alexey Bataev88202be2017-07-27 13:20:36 +00009686 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
9687 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +00009688 }
9689
Alexey Bataev60da77e2016-02-29 05:54:20 +00009690 DeclRefExpr *Ref = nullptr;
9691 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009692 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009693 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009694 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009695 VarsExpr =
9696 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9697 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009698 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009699 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009700 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009701 if (!S.IsOpenMPCapturedDecl(D)) {
9702 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009703 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009704 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009705 if (!RefRes.isUsable())
9706 continue;
9707 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009708 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9709 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +00009710 if (!PostUpdateRes.isUsable())
9711 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009712 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
9713 Stack->getCurrentDirective() == OMPD_taskgroup) {
9714 S.Diag(RefExpr->getExprLoc(),
9715 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009716 << RefExpr->getSourceRange();
9717 continue;
9718 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009719 RD.ExprPostUpdates.emplace_back(
9720 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009721 }
9722 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009723 }
Alexey Bataev169d96a2017-07-18 20:17:46 +00009724 // All reduction items are still marked as reduction (to do not increase
9725 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009726 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009727 if (CurrDir == OMPD_taskgroup) {
9728 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +00009729 Stack->addTaskgroupReductionData(D, ReductionIdRange,
9730 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +00009731 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +00009732 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +00009733 }
Alexey Bataev88202be2017-07-27 13:20:36 +00009734 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
9735 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009736 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009737 return RD.Vars.empty();
9738}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009739
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009740OMPClause *Sema::ActOnOpenMPReductionClause(
9741 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9742 SourceLocation ColonLoc, SourceLocation EndLoc,
9743 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9744 ArrayRef<Expr *> UnresolvedReductions) {
9745 ReductionData RD(VarList.size());
9746
Alexey Bataev169d96a2017-07-18 20:17:46 +00009747 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
9748 StartLoc, LParenLoc, ColonLoc, EndLoc,
9749 ReductionIdScopeSpec, ReductionId,
9750 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +00009751 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009752
Alexey Bataevc5e02582014-06-16 07:08:35 +00009753 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009754 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9755 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9756 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9757 buildPreInits(Context, RD.ExprCaptures),
9758 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009759}
9760
Alexey Bataev169d96a2017-07-18 20:17:46 +00009761OMPClause *Sema::ActOnOpenMPTaskReductionClause(
9762 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9763 SourceLocation ColonLoc, SourceLocation EndLoc,
9764 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9765 ArrayRef<Expr *> UnresolvedReductions) {
9766 ReductionData RD(VarList.size());
9767
9768 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
9769 VarList, StartLoc, LParenLoc, ColonLoc,
9770 EndLoc, ReductionIdScopeSpec, ReductionId,
9771 UnresolvedReductions, RD))
9772 return nullptr;
9773
9774 return OMPTaskReductionClause::Create(
9775 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9776 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
9777 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
9778 buildPreInits(Context, RD.ExprCaptures),
9779 buildPostUpdate(*this, RD.ExprPostUpdates));
9780}
9781
Alexey Bataevfa312f32017-07-21 18:48:21 +00009782OMPClause *Sema::ActOnOpenMPInReductionClause(
9783 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
9784 SourceLocation ColonLoc, SourceLocation EndLoc,
9785 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
9786 ArrayRef<Expr *> UnresolvedReductions) {
9787 ReductionData RD(VarList.size());
9788
9789 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
9790 StartLoc, LParenLoc, ColonLoc, EndLoc,
9791 ReductionIdScopeSpec, ReductionId,
9792 UnresolvedReductions, RD))
9793 return nullptr;
9794
9795 return OMPInReductionClause::Create(
9796 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
9797 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +00009798 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +00009799 buildPreInits(Context, RD.ExprCaptures),
9800 buildPostUpdate(*this, RD.ExprPostUpdates));
9801}
9802
Alexey Bataevecba70f2016-04-12 11:02:11 +00009803bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9804 SourceLocation LinLoc) {
9805 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9806 LinKind == OMPC_LINEAR_unknown) {
9807 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9808 return true;
9809 }
9810 return false;
9811}
9812
9813bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9814 OpenMPLinearClauseKind LinKind,
9815 QualType Type) {
9816 auto *VD = dyn_cast_or_null<VarDecl>(D);
9817 // A variable must not have an incomplete type or a reference type.
9818 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9819 return true;
9820 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9821 !Type->isReferenceType()) {
9822 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9823 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9824 return true;
9825 }
9826 Type = Type.getNonReferenceType();
9827
9828 // A list item must not be const-qualified.
9829 if (Type.isConstant(Context)) {
9830 Diag(ELoc, diag::err_omp_const_variable)
9831 << getOpenMPClauseName(OMPC_linear);
9832 if (D) {
9833 bool IsDecl =
9834 !VD ||
9835 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9836 Diag(D->getLocation(),
9837 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9838 << D;
9839 }
9840 return true;
9841 }
9842
9843 // A list item must be of integral or pointer type.
9844 Type = Type.getUnqualifiedType().getCanonicalType();
9845 const auto *Ty = Type.getTypePtrOrNull();
9846 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9847 !Ty->isPointerType())) {
9848 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9849 if (D) {
9850 bool IsDecl =
9851 !VD ||
9852 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9853 Diag(D->getLocation(),
9854 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9855 << D;
9856 }
9857 return true;
9858 }
9859 return false;
9860}
9861
Alexey Bataev182227b2015-08-20 10:54:39 +00009862OMPClause *Sema::ActOnOpenMPLinearClause(
9863 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9864 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9865 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009866 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009867 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009868 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009869 SmallVector<Decl *, 4> ExprCaptures;
9870 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009871 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009872 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009873 for (auto &RefExpr : VarList) {
9874 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009875 SourceLocation ELoc;
9876 SourceRange ERange;
9877 Expr *SimpleRefExpr = RefExpr;
9878 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9879 /*AllowArraySection=*/false);
9880 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009881 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009882 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009883 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009884 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009885 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009886 ValueDecl *D = Res.first;
9887 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009888 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009889
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009890 QualType Type = D->getType();
9891 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009892
9893 // OpenMP [2.14.3.7, linear clause]
9894 // A list-item cannot appear in more than one linear clause.
9895 // A list-item that appears in a linear clause cannot appear in any
9896 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009897 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009898 if (DVar.RefExpr) {
9899 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9900 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009901 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009902 continue;
9903 }
9904
Alexey Bataevecba70f2016-04-12 11:02:11 +00009905 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009906 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009907 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009908
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009909 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009910 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9911 D->hasAttrs() ? &D->getAttrs() : nullptr);
9912 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009913 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009914 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009915 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009916 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009917 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009918 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9919 if (!IsOpenMPCapturedDecl(D)) {
9920 ExprCaptures.push_back(Ref->getDecl());
9921 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9922 ExprResult RefRes = DefaultLvalueConversion(Ref);
9923 if (!RefRes.isUsable())
9924 continue;
9925 ExprResult PostUpdateRes =
9926 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9927 SimpleRefExpr, RefRes.get());
9928 if (!PostUpdateRes.isUsable())
9929 continue;
9930 ExprPostUpdates.push_back(
9931 IgnoredValueConversions(PostUpdateRes.get()).get());
9932 }
9933 }
9934 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009935 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009936 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009937 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009938 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009939 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009940 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009941 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9942
9943 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009944 Vars.push_back((VD || CurContext->isDependentContext())
9945 ? RefExpr->IgnoreParens()
9946 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009947 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009948 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009949 }
9950
9951 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009952 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009953
9954 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009955 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009956 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9957 !Step->isInstantiationDependent() &&
9958 !Step->containsUnexpandedParameterPack()) {
9959 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009960 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009961 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009962 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009963 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009964
Alexander Musman3276a272015-03-21 10:12:56 +00009965 // Build var to save the step value.
9966 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009967 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009968 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009969 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009970 ExprResult CalcStep =
9971 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009972 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009973
Alexander Musman8dba6642014-04-22 13:09:42 +00009974 // Warn about zero linear step (it would be probably better specified as
9975 // making corresponding variables 'const').
9976 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009977 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9978 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009979 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9980 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009981 if (!IsConstant && CalcStep.isUsable()) {
9982 // Calculate the step beforehand instead of doing this on each iteration.
9983 // (This is not used if the number of iterations may be kfold-ed).
9984 CalcStepExpr = CalcStep.get();
9985 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009986 }
9987
Alexey Bataev182227b2015-08-20 10:54:39 +00009988 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9989 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009990 StepExpr, CalcStepExpr,
9991 buildPreInits(Context, ExprCaptures),
9992 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009993}
9994
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009995static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9996 Expr *NumIterations, Sema &SemaRef,
9997 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009998 // Walk the vars and build update/final expressions for the CodeGen.
9999 SmallVector<Expr *, 8> Updates;
10000 SmallVector<Expr *, 8> Finals;
10001 Expr *Step = Clause.getStep();
10002 Expr *CalcStep = Clause.getCalcStep();
10003 // OpenMP [2.14.3.7, linear clause]
10004 // If linear-step is not specified it is assumed to be 1.
10005 if (Step == nullptr)
10006 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010007 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010008 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010009 }
Alexander Musman3276a272015-03-21 10:12:56 +000010010 bool HasErrors = false;
10011 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010012 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010013 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010014 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010015 SourceLocation ELoc;
10016 SourceRange ERange;
10017 Expr *SimpleRefExpr = RefExpr;
10018 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10019 /*AllowArraySection=*/false);
10020 ValueDecl *D = Res.first;
10021 if (Res.second || !D) {
10022 Updates.push_back(nullptr);
10023 Finals.push_back(nullptr);
10024 HasErrors = true;
10025 continue;
10026 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010027 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +000010028 Expr *InitExpr = *CurInit;
10029
10030 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010031 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010032 Expr *CapturedRef;
10033 if (LinKind == OMPC_LINEAR_uval)
10034 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10035 else
10036 CapturedRef =
10037 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10038 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10039 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010040
10041 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010042 ExprResult Update;
10043 if (!Info.first) {
10044 Update =
10045 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
10046 InitExpr, IV, Step, /* Subtract */ false);
10047 } else
10048 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010049 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
10050 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010051
10052 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010053 ExprResult Final;
10054 if (!Info.first) {
10055 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
10056 InitExpr, NumIterations, Step,
10057 /* Subtract */ false);
10058 } else
10059 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010060 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
10061 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010062
Alexander Musman3276a272015-03-21 10:12:56 +000010063 if (!Update.isUsable() || !Final.isUsable()) {
10064 Updates.push_back(nullptr);
10065 Finals.push_back(nullptr);
10066 HasErrors = true;
10067 } else {
10068 Updates.push_back(Update.get());
10069 Finals.push_back(Final.get());
10070 }
Richard Trieucc3949d2016-02-18 22:34:54 +000010071 ++CurInit;
10072 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000010073 }
10074 Clause.setUpdates(Updates);
10075 Clause.setFinals(Finals);
10076 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000010077}
10078
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010079OMPClause *Sema::ActOnOpenMPAlignedClause(
10080 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
10081 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
10082
10083 SmallVector<Expr *, 8> Vars;
10084 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000010085 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10086 SourceLocation ELoc;
10087 SourceRange ERange;
10088 Expr *SimpleRefExpr = RefExpr;
10089 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10090 /*AllowArraySection=*/false);
10091 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010092 // It will be analyzed later.
10093 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010094 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000010095 ValueDecl *D = Res.first;
10096 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010097 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010098
Alexey Bataev1efd1662016-03-29 10:59:56 +000010099 QualType QType = D->getType();
10100 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010101
10102 // OpenMP [2.8.1, simd construct, Restrictions]
10103 // The type of list items appearing in the aligned clause must be
10104 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010105 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010106 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000010107 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010108 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010109 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010110 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000010111 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010112 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000010113 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010114 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000010115 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010116 continue;
10117 }
10118
10119 // OpenMP [2.8.1, simd construct, Restrictions]
10120 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000010121 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000010122 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010123 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
10124 << getOpenMPClauseName(OMPC_aligned);
10125 continue;
10126 }
10127
Alexey Bataev1efd1662016-03-29 10:59:56 +000010128 DeclRefExpr *Ref = nullptr;
10129 if (!VD && IsOpenMPCapturedDecl(D))
10130 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10131 Vars.push_back(DefaultFunctionArrayConversion(
10132 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
10133 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010134 }
10135
10136 // OpenMP [2.8.1, simd construct, Description]
10137 // The parameter of the aligned clause, alignment, must be a constant
10138 // positive integer expression.
10139 // If no optional parameter is specified, implementation-defined default
10140 // alignments for SIMD instructions on the target platforms are assumed.
10141 if (Alignment != nullptr) {
10142 ExprResult AlignResult =
10143 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
10144 if (AlignResult.isInvalid())
10145 return nullptr;
10146 Alignment = AlignResult.get();
10147 }
10148 if (Vars.empty())
10149 return nullptr;
10150
10151 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
10152 EndLoc, Vars, Alignment);
10153}
10154
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010155OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
10156 SourceLocation StartLoc,
10157 SourceLocation LParenLoc,
10158 SourceLocation EndLoc) {
10159 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010160 SmallVector<Expr *, 8> SrcExprs;
10161 SmallVector<Expr *, 8> DstExprs;
10162 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000010163 for (auto &RefExpr : VarList) {
10164 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
10165 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010166 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010167 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010168 SrcExprs.push_back(nullptr);
10169 DstExprs.push_back(nullptr);
10170 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010171 continue;
10172 }
10173
Alexey Bataeved09d242014-05-28 05:53:51 +000010174 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010175 // OpenMP [2.1, C/C++]
10176 // A list item is a variable name.
10177 // OpenMP [2.14.4.1, Restrictions, p.1]
10178 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000010179 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010180 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010181 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
10182 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010183 continue;
10184 }
10185
10186 Decl *D = DE->getDecl();
10187 VarDecl *VD = cast<VarDecl>(D);
10188
10189 QualType Type = VD->getType();
10190 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
10191 // It will be analyzed later.
10192 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010193 SrcExprs.push_back(nullptr);
10194 DstExprs.push_back(nullptr);
10195 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010196 continue;
10197 }
10198
10199 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
10200 // A list item that appears in a copyin clause must be threadprivate.
10201 if (!DSAStack->isThreadPrivate(VD)) {
10202 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000010203 << getOpenMPClauseName(OMPC_copyin)
10204 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010205 continue;
10206 }
10207
10208 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10209 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000010210 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010211 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010212 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010213 auto *SrcVD =
10214 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
10215 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000010216 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010217 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
10218 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000010219 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
10220 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010221 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010222 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010223 // For arrays generate assignment operation for single element and replace
10224 // it by the original array element in CodeGen.
10225 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
10226 PseudoDstExpr, PseudoSrcExpr);
10227 if (AssignmentOp.isInvalid())
10228 continue;
10229 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
10230 /*DiscardedValue=*/true);
10231 if (AssignmentOp.isInvalid())
10232 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010233
10234 DSAStack->addDSA(VD, DE, OMPC_copyin);
10235 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010236 SrcExprs.push_back(PseudoSrcExpr);
10237 DstExprs.push_back(PseudoDstExpr);
10238 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010239 }
10240
Alexey Bataeved09d242014-05-28 05:53:51 +000010241 if (Vars.empty())
10242 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010243
Alexey Bataevf56f98c2015-04-16 05:39:01 +000010244 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10245 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010246}
10247
Alexey Bataevbae9a792014-06-27 10:37:06 +000010248OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
10249 SourceLocation StartLoc,
10250 SourceLocation LParenLoc,
10251 SourceLocation EndLoc) {
10252 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000010253 SmallVector<Expr *, 8> SrcExprs;
10254 SmallVector<Expr *, 8> DstExprs;
10255 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010256 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010257 assert(RefExpr && "NULL expr in OpenMP linear clause.");
10258 SourceLocation ELoc;
10259 SourceRange ERange;
10260 Expr *SimpleRefExpr = RefExpr;
10261 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10262 /*AllowArraySection=*/false);
10263 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010264 // It will be analyzed later.
10265 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010266 SrcExprs.push_back(nullptr);
10267 DstExprs.push_back(nullptr);
10268 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010269 }
Alexey Bataeve122da12016-03-17 10:50:17 +000010270 ValueDecl *D = Res.first;
10271 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000010272 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010273
Alexey Bataeve122da12016-03-17 10:50:17 +000010274 QualType Type = D->getType();
10275 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010276
10277 // OpenMP [2.14.4.2, Restrictions, p.2]
10278 // A list item that appears in a copyprivate clause may not appear in a
10279 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000010280 if (!VD || !DSAStack->isThreadPrivate(VD)) {
10281 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000010282 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
10283 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000010284 Diag(ELoc, diag::err_omp_wrong_dsa)
10285 << getOpenMPClauseName(DVar.CKind)
10286 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000010287 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010288 continue;
10289 }
10290
10291 // OpenMP [2.11.4.2, Restrictions, p.1]
10292 // All list items that appear in a copyprivate clause must be either
10293 // threadprivate or private in the enclosing context.
10294 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000010295 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010296 if (DVar.CKind == OMPC_shared) {
10297 Diag(ELoc, diag::err_omp_required_access)
10298 << getOpenMPClauseName(OMPC_copyprivate)
10299 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000010300 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010301 continue;
10302 }
10303 }
10304 }
10305
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010306 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010307 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010308 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010309 << getOpenMPClauseName(OMPC_copyprivate) << Type
10310 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010311 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000010312 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010313 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000010314 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010315 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000010316 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000010317 continue;
10318 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010319
Alexey Bataevbae9a792014-06-27 10:37:06 +000010320 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
10321 // A variable of class type (or array thereof) that appears in a
10322 // copyin clause requires an accessible, unambiguous copy assignment
10323 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010324 Type = Context.getBaseElementType(Type.getNonReferenceType())
10325 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000010326 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010327 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
10328 D->hasAttrs() ? &D->getAttrs() : nullptr);
10329 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000010330 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000010331 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
10332 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000010333 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000010334 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010335 PseudoDstExpr, PseudoSrcExpr);
10336 if (AssignmentOp.isInvalid())
10337 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000010338 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000010339 /*DiscardedValue=*/true);
10340 if (AssignmentOp.isInvalid())
10341 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010342
10343 // No need to mark vars as copyprivate, they are already threadprivate or
10344 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000010345 assert(VD || IsOpenMPCapturedDecl(D));
10346 Vars.push_back(
10347 VD ? RefExpr->IgnoreParens()
10348 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000010349 SrcExprs.push_back(PseudoSrcExpr);
10350 DstExprs.push_back(PseudoDstExpr);
10351 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000010352 }
10353
10354 if (Vars.empty())
10355 return nullptr;
10356
Alexey Bataeva63048e2015-03-23 06:18:07 +000010357 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10358 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000010359}
10360
Alexey Bataev6125da92014-07-21 11:26:11 +000010361OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
10362 SourceLocation StartLoc,
10363 SourceLocation LParenLoc,
10364 SourceLocation EndLoc) {
10365 if (VarList.empty())
10366 return nullptr;
10367
10368 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
10369}
Alexey Bataevdea47612014-07-23 07:46:59 +000010370
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010371OMPClause *
10372Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
10373 SourceLocation DepLoc, SourceLocation ColonLoc,
10374 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10375 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010376 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010377 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000010378 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010379 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000010380 return nullptr;
10381 }
10382 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010383 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
10384 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010385 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010386 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010387 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
10388 /*Last=*/OMPC_DEPEND_unknown, Except)
10389 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010390 return nullptr;
10391 }
10392 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000010393 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010394 llvm::APSInt DepCounter(/*BitWidth=*/32);
10395 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
10396 if (DepKind == OMPC_DEPEND_sink) {
10397 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
10398 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
10399 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010400 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010401 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010402 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
10403 DSAStack->getParentOrderedRegionParam()) {
10404 for (auto &RefExpr : VarList) {
10405 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000010406 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010407 // It will be analyzed later.
10408 Vars.push_back(RefExpr);
10409 continue;
10410 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010411
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010412 SourceLocation ELoc = RefExpr->getExprLoc();
10413 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
10414 if (DepKind == OMPC_DEPEND_sink) {
10415 if (DepCounter >= TotalDepCount) {
10416 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
10417 continue;
10418 }
10419 ++DepCounter;
10420 // OpenMP [2.13.9, Summary]
10421 // depend(dependence-type : vec), where dependence-type is:
10422 // 'sink' and where vec is the iteration vector, which has the form:
10423 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
10424 // where n is the value specified by the ordered clause in the loop
10425 // directive, xi denotes the loop iteration variable of the i-th nested
10426 // loop associated with the loop directive, and di is a constant
10427 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000010428 if (CurContext->isDependentContext()) {
10429 // It will be analyzed later.
10430 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010431 continue;
10432 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010433 SimpleExpr = SimpleExpr->IgnoreImplicit();
10434 OverloadedOperatorKind OOK = OO_None;
10435 SourceLocation OOLoc;
10436 Expr *LHS = SimpleExpr;
10437 Expr *RHS = nullptr;
10438 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
10439 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
10440 OOLoc = BO->getOperatorLoc();
10441 LHS = BO->getLHS()->IgnoreParenImpCasts();
10442 RHS = BO->getRHS()->IgnoreParenImpCasts();
10443 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
10444 OOK = OCE->getOperator();
10445 OOLoc = OCE->getOperatorLoc();
10446 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10447 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
10448 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
10449 OOK = MCE->getMethodDecl()
10450 ->getNameInfo()
10451 .getName()
10452 .getCXXOverloadedOperator();
10453 OOLoc = MCE->getCallee()->getExprLoc();
10454 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
10455 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
10456 }
10457 SourceLocation ELoc;
10458 SourceRange ERange;
10459 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
10460 /*AllowArraySection=*/false);
10461 if (Res.second) {
10462 // It will be analyzed later.
10463 Vars.push_back(RefExpr);
10464 }
10465 ValueDecl *D = Res.first;
10466 if (!D)
10467 continue;
10468
10469 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
10470 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
10471 continue;
10472 }
10473 if (RHS) {
10474 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
10475 RHS, OMPC_depend, /*StrictlyPositive=*/false);
10476 if (RHSRes.isInvalid())
10477 continue;
10478 }
10479 if (!CurContext->isDependentContext() &&
10480 DSAStack->getParentOrderedRegionParam() &&
10481 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
10482 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
10483 << DSAStack->getParentLoopControlVariable(
10484 DepCounter.getZExtValue());
10485 continue;
10486 }
10487 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010488 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010489 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010490 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000010491 (ASE &&
10492 !ASE->getBase()
10493 ->getType()
10494 .getNonReferenceType()
10495 ->isPointerType() &&
10496 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000010497 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10498 << RefExpr->getSourceRange();
10499 continue;
10500 }
10501 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
10502 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
10503 ExprResult Res = CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf,
10504 RefExpr->IgnoreParenImpCasts());
10505 getDiagnostics().setSuppressAllDiagnostics(Suppress);
10506 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
10507 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
10508 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010509 continue;
10510 }
10511 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010512 Vars.push_back(RefExpr->IgnoreParenImpCasts());
10513 }
10514
10515 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
10516 TotalDepCount > VarList.size() &&
10517 DSAStack->getParentOrderedRegionParam()) {
10518 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
10519 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
10520 }
10521 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
10522 Vars.empty())
10523 return nullptr;
10524 }
Alexey Bataev8b427062016-05-25 12:36:08 +000010525 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10526 DepKind, DepLoc, ColonLoc, Vars);
10527 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
10528 DSAStack->addDoacrossDependClause(C, OpsOffs);
10529 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010530}
Michael Wonge710d542015-08-07 16:16:36 +000010531
10532OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
10533 SourceLocation LParenLoc,
10534 SourceLocation EndLoc) {
10535 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +000010536
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010537 // OpenMP [2.9.1, Restrictions]
10538 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010539 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
10540 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010541 return nullptr;
10542
Michael Wonge710d542015-08-07 16:16:36 +000010543 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10544}
Kelvin Li0bff7af2015-11-23 05:32:03 +000010545
10546static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
10547 DSAStackTy *Stack, CXXRecordDecl *RD) {
10548 if (!RD || RD->isInvalidDecl())
10549 return true;
10550
10551 auto QTy = SemaRef.Context.getRecordType(RD);
10552 if (RD->isDynamicClass()) {
10553 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10554 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
10555 return false;
10556 }
10557 auto *DC = RD;
10558 bool IsCorrect = true;
10559 for (auto *I : DC->decls()) {
10560 if (I) {
10561 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
10562 if (MD->isStatic()) {
10563 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10564 SemaRef.Diag(MD->getLocation(),
10565 diag::note_omp_static_member_in_target);
10566 IsCorrect = false;
10567 }
10568 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
10569 if (VD->isStaticDataMember()) {
10570 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
10571 SemaRef.Diag(VD->getLocation(),
10572 diag::note_omp_static_member_in_target);
10573 IsCorrect = false;
10574 }
10575 }
10576 }
10577 }
10578
10579 for (auto &I : RD->bases()) {
10580 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
10581 I.getType()->getAsCXXRecordDecl()))
10582 IsCorrect = false;
10583 }
10584 return IsCorrect;
10585}
10586
10587static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
10588 DSAStackTy *Stack, QualType QTy) {
10589 NamedDecl *ND;
10590 if (QTy->isIncompleteType(&ND)) {
10591 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
10592 return false;
10593 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +000010594 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010595 return false;
10596 }
10597 return true;
10598}
10599
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010600/// \brief Return true if it can be proven that the provided array expression
10601/// (array section or array subscript) does NOT specify the whole size of the
10602/// array whose base type is \a BaseQTy.
10603static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
10604 const Expr *E,
10605 QualType BaseQTy) {
10606 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10607
10608 // If this is an array subscript, it refers to the whole size if the size of
10609 // the dimension is constant and equals 1. Also, an array section assumes the
10610 // format of an array subscript if no colon is used.
10611 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
10612 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10613 return ATy->getSize().getSExtValue() != 1;
10614 // Size can't be evaluated statically.
10615 return false;
10616 }
10617
10618 assert(OASE && "Expecting array section if not an array subscript.");
10619 auto *LowerBound = OASE->getLowerBound();
10620 auto *Length = OASE->getLength();
10621
10622 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000010623 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010624 if (LowerBound) {
10625 llvm::APSInt ConstLowerBound;
10626 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
10627 return false; // Can't get the integer value as a constant.
10628 if (ConstLowerBound.getSExtValue())
10629 return true;
10630 }
10631
10632 // If we don't have a length we covering the whole dimension.
10633 if (!Length)
10634 return false;
10635
10636 // If the base is a pointer, we don't have a way to get the size of the
10637 // pointee.
10638 if (BaseQTy->isPointerType())
10639 return false;
10640
10641 // We can only check if the length is the same as the size of the dimension
10642 // if we have a constant array.
10643 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
10644 if (!CATy)
10645 return false;
10646
10647 llvm::APSInt ConstLength;
10648 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10649 return false; // Can't get the integer value as a constant.
10650
10651 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10652}
10653
10654// Return true if it can be proven that the provided array expression (array
10655// section or array subscript) does NOT specify a single element of the array
10656// whose base type is \a BaseQTy.
10657static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010658 const Expr *E,
10659 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010660 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10661
10662 // An array subscript always refer to a single element. Also, an array section
10663 // assumes the format of an array subscript if no colon is used.
10664 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10665 return false;
10666
10667 assert(OASE && "Expecting array section if not an array subscript.");
10668 auto *Length = OASE->getLength();
10669
10670 // If we don't have a length we have to check if the array has unitary size
10671 // for this dimension. Also, we should always expect a length if the base type
10672 // is pointer.
10673 if (!Length) {
10674 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10675 return ATy->getSize().getSExtValue() != 1;
10676 // We cannot assume anything.
10677 return false;
10678 }
10679
10680 // Check if the length evaluates to 1.
10681 llvm::APSInt ConstLength;
10682 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10683 return false; // Can't get the integer value as a constant.
10684
10685 return ConstLength.getSExtValue() != 1;
10686}
10687
Samuel Antao661c0902016-05-26 17:39:58 +000010688// Return the expression of the base of the mappable expression or null if it
10689// cannot be determined and do all the necessary checks to see if the expression
10690// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010691// components of the expression.
10692static Expr *CheckMapClauseExpressionBase(
10693 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010694 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10695 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010696 SourceLocation ELoc = E->getExprLoc();
10697 SourceRange ERange = E->getSourceRange();
10698
10699 // The base of elements of list in a map clause have to be either:
10700 // - a reference to variable or field.
10701 // - a member expression.
10702 // - an array expression.
10703 //
10704 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10705 // reference to 'r'.
10706 //
10707 // If we have:
10708 //
10709 // struct SS {
10710 // Bla S;
10711 // foo() {
10712 // #pragma omp target map (S.Arr[:12]);
10713 // }
10714 // }
10715 //
10716 // We want to retrieve the member expression 'this->S';
10717
10718 Expr *RelevantExpr = nullptr;
10719
Samuel Antao5de996e2016-01-22 20:21:36 +000010720 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10721 // If a list item is an array section, it must specify contiguous storage.
10722 //
10723 // For this restriction it is sufficient that we make sure only references
10724 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010725 // exist except in the rightmost expression (unless they cover the whole
10726 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010727 //
10728 // r.ArrS[3:5].Arr[6:7]
10729 //
10730 // r.ArrS[3:5].x
10731 //
10732 // but these would be valid:
10733 // r.ArrS[3].Arr[6:7]
10734 //
10735 // r.ArrS[3].x
10736
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010737 bool AllowUnitySizeArraySection = true;
10738 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010739
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010740 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010741 E = E->IgnoreParenImpCasts();
10742
10743 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10744 if (!isa<VarDecl>(CurE->getDecl()))
10745 break;
10746
10747 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010748
10749 // If we got a reference to a declaration, we should not expect any array
10750 // section before that.
10751 AllowUnitySizeArraySection = false;
10752 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010753
10754 // Record the component.
10755 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10756 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010757 continue;
10758 }
10759
10760 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10761 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10762
10763 if (isa<CXXThisExpr>(BaseE))
10764 // We found a base expression: this->Val.
10765 RelevantExpr = CurE;
10766 else
10767 E = BaseE;
10768
10769 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10770 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10771 << CurE->getSourceRange();
10772 break;
10773 }
10774
10775 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10776
10777 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10778 // A bit-field cannot appear in a map clause.
10779 //
10780 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010781 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10782 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010783 break;
10784 }
10785
10786 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10787 // If the type of a list item is a reference to a type T then the type
10788 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010789 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010790
10791 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10792 // A list item cannot be a variable that is a member of a structure with
10793 // a union type.
10794 //
10795 if (auto *RT = CurType->getAs<RecordType>())
10796 if (RT->isUnionType()) {
10797 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10798 << CurE->getSourceRange();
10799 break;
10800 }
10801
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010802 // If we got a member expression, we should not expect any array section
10803 // before that:
10804 //
10805 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10806 // If a list item is an element of a structure, only the rightmost symbol
10807 // of the variable reference can be an array section.
10808 //
10809 AllowUnitySizeArraySection = false;
10810 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010811
10812 // Record the component.
10813 CurComponents.push_back(
10814 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010815 continue;
10816 }
10817
10818 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10819 E = CurE->getBase()->IgnoreParenImpCasts();
10820
10821 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10822 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10823 << 0 << CurE->getSourceRange();
10824 break;
10825 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010826
10827 // If we got an array subscript that express the whole dimension we
10828 // can have any array expressions before. If it only expressing part of
10829 // the dimension, we can only have unitary-size array expressions.
10830 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10831 E->getType()))
10832 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010833
10834 // Record the component - we don't have any declaration associated.
10835 CurComponents.push_back(
10836 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010837 continue;
10838 }
10839
10840 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010841 E = CurE->getBase()->IgnoreParenImpCasts();
10842
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010843 auto CurType =
10844 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10845
Samuel Antao5de996e2016-01-22 20:21:36 +000010846 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10847 // If the type of a list item is a reference to a type T then the type
10848 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010849 if (CurType->isReferenceType())
10850 CurType = CurType->getPointeeType();
10851
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010852 bool IsPointer = CurType->isAnyPointerType();
10853
10854 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010855 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10856 << 0 << CurE->getSourceRange();
10857 break;
10858 }
10859
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010860 bool NotWhole =
10861 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10862 bool NotUnity =
10863 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10864
Samuel Antaodab51bb2016-07-18 23:22:11 +000010865 if (AllowWholeSizeArraySection) {
10866 // Any array section is currently allowed. Allowing a whole size array
10867 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010868 //
10869 // If this array section refers to the whole dimension we can still
10870 // accept other array sections before this one, except if the base is a
10871 // pointer. Otherwise, only unitary sections are accepted.
10872 if (NotWhole || IsPointer)
10873 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010874 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010875 // A unity or whole array section is not allowed and that is not
10876 // compatible with the properties of the current array section.
10877 SemaRef.Diag(
10878 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10879 << CurE->getSourceRange();
10880 break;
10881 }
Samuel Antao90927002016-04-26 14:54:23 +000010882
10883 // Record the component - we don't have any declaration associated.
10884 CurComponents.push_back(
10885 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010886 continue;
10887 }
10888
10889 // If nothing else worked, this is not a valid map clause expression.
10890 SemaRef.Diag(ELoc,
10891 diag::err_omp_expected_named_var_member_or_array_expression)
10892 << ERange;
10893 break;
10894 }
10895
10896 return RelevantExpr;
10897}
10898
10899// Return true if expression E associated with value VD has conflicts with other
10900// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010901static bool CheckMapConflicts(
10902 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10903 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010904 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10905 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010906 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010907 SourceLocation ELoc = E->getExprLoc();
10908 SourceRange ERange = E->getSourceRange();
10909
10910 // In order to easily check the conflicts we need to match each component of
10911 // the expression under test with the components of the expressions that are
10912 // already in the stack.
10913
Samuel Antao5de996e2016-01-22 20:21:36 +000010914 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010915 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010916 "Map clause expression with unexpected base!");
10917
10918 // Variables to help detecting enclosing problems in data environment nests.
10919 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010920 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010921
Samuel Antao90927002016-04-26 14:54:23 +000010922 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10923 VD, CurrentRegionOnly,
10924 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010925 StackComponents,
10926 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010927
Samuel Antao5de996e2016-01-22 20:21:36 +000010928 assert(!StackComponents.empty() &&
10929 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010930 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010931 "Map clause expression with unexpected base!");
10932
Samuel Antao90927002016-04-26 14:54:23 +000010933 // The whole expression in the stack.
10934 auto *RE = StackComponents.front().getAssociatedExpression();
10935
Samuel Antao5de996e2016-01-22 20:21:36 +000010936 // Expressions must start from the same base. Here we detect at which
10937 // point both expressions diverge from each other and see if we can
10938 // detect if the memory referred to both expressions is contiguous and
10939 // do not overlap.
10940 auto CI = CurComponents.rbegin();
10941 auto CE = CurComponents.rend();
10942 auto SI = StackComponents.rbegin();
10943 auto SE = StackComponents.rend();
10944 for (; CI != CE && SI != SE; ++CI, ++SI) {
10945
10946 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10947 // At most one list item can be an array item derived from a given
10948 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010949 if (CurrentRegionOnly &&
10950 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10951 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10952 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10953 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10954 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010955 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010956 << CI->getAssociatedExpression()->getSourceRange();
10957 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10958 diag::note_used_here)
10959 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010960 return true;
10961 }
10962
10963 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010964 if (CI->getAssociatedExpression()->getStmtClass() !=
10965 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010966 break;
10967
10968 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010969 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010970 break;
10971 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010972 // Check if the extra components of the expressions in the enclosing
10973 // data environment are redundant for the current base declaration.
10974 // If they are, the maps completely overlap, which is legal.
10975 for (; SI != SE; ++SI) {
10976 QualType Type;
10977 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010978 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010979 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010980 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10981 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010982 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10983 Type =
10984 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10985 }
10986 if (Type.isNull() || Type->isAnyPointerType() ||
10987 CheckArrayExpressionDoesNotReferToWholeSize(
10988 SemaRef, SI->getAssociatedExpression(), Type))
10989 break;
10990 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010991
10992 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10993 // List items of map clauses in the same construct must not share
10994 // original storage.
10995 //
10996 // If the expressions are exactly the same or one is a subset of the
10997 // other, it means they are sharing storage.
10998 if (CI == CE && SI == SE) {
10999 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011000 if (CKind == OMPC_map)
11001 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11002 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011003 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011004 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11005 << ERange;
11006 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011007 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11008 << RE->getSourceRange();
11009 return true;
11010 } else {
11011 // If we find the same expression in the enclosing data environment,
11012 // that is legal.
11013 IsEnclosedByDataEnvironmentExpr = true;
11014 return false;
11015 }
11016 }
11017
Samuel Antao90927002016-04-26 14:54:23 +000011018 QualType DerivedType =
11019 std::prev(CI)->getAssociatedDeclaration()->getType();
11020 SourceLocation DerivedLoc =
11021 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011022
11023 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11024 // If the type of a list item is a reference to a type T then the type
11025 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011026 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011027
11028 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11029 // A variable for which the type is pointer and an array section
11030 // derived from that variable must not appear as list items of map
11031 // clauses of the same construct.
11032 //
11033 // Also, cover one of the cases in:
11034 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11035 // If any part of the original storage of a list item has corresponding
11036 // storage in the device data environment, all of the original storage
11037 // must have corresponding storage in the device data environment.
11038 //
11039 if (DerivedType->isAnyPointerType()) {
11040 if (CI == CE || SI == SE) {
11041 SemaRef.Diag(
11042 DerivedLoc,
11043 diag::err_omp_pointer_mapped_along_with_derived_section)
11044 << DerivedLoc;
11045 } else {
11046 assert(CI != CE && SI != SE);
11047 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11048 << DerivedLoc;
11049 }
11050 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11051 << RE->getSourceRange();
11052 return true;
11053 }
11054
11055 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11056 // List items of map clauses in the same construct must not share
11057 // original storage.
11058 //
11059 // An expression is a subset of the other.
11060 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011061 if (CKind == OMPC_map)
11062 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11063 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011064 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011065 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11066 << ERange;
11067 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011068 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11069 << RE->getSourceRange();
11070 return true;
11071 }
11072
11073 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000011074 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000011075 if (!CurrentRegionOnly && SI != SE)
11076 EnclosingExpr = RE;
11077
11078 // The current expression is a subset of the expression in the data
11079 // environment.
11080 IsEnclosedByDataEnvironmentExpr |=
11081 (!CurrentRegionOnly && CI != CE && SI == SE);
11082
11083 return false;
11084 });
11085
11086 if (CurrentRegionOnly)
11087 return FoundError;
11088
11089 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11090 // If any part of the original storage of a list item has corresponding
11091 // storage in the device data environment, all of the original storage must
11092 // have corresponding storage in the device data environment.
11093 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
11094 // If a list item is an element of a structure, and a different element of
11095 // the structure has a corresponding list item in the device data environment
11096 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000011097 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000011098 // data environment prior to the task encountering the construct.
11099 //
11100 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
11101 SemaRef.Diag(ELoc,
11102 diag::err_omp_original_storage_is_shared_and_does_not_contain)
11103 << ERange;
11104 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
11105 << EnclosingExpr->getSourceRange();
11106 return true;
11107 }
11108
11109 return FoundError;
11110}
11111
Samuel Antao661c0902016-05-26 17:39:58 +000011112namespace {
11113// Utility struct that gathers all the related lists associated with a mappable
11114// expression.
11115struct MappableVarListInfo final {
11116 // The list of expressions.
11117 ArrayRef<Expr *> VarList;
11118 // The list of processed expressions.
11119 SmallVector<Expr *, 16> ProcessedVarList;
11120 // The mappble components for each expression.
11121 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
11122 // The base declaration of the variable.
11123 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
11124
11125 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
11126 // We have a list of components and base declarations for each entry in the
11127 // variable list.
11128 VarComponents.reserve(VarList.size());
11129 VarBaseDeclarations.reserve(VarList.size());
11130 }
11131};
11132}
11133
11134// Check the validity of the provided variable list for the provided clause kind
11135// \a CKind. In the check process the valid expressions, and mappable expression
11136// components and variables are extracted and used to fill \a Vars,
11137// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
11138// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
11139static void
11140checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
11141 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
11142 SourceLocation StartLoc,
11143 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
11144 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011145 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
11146 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000011147 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011148
Samuel Antao90927002016-04-26 14:54:23 +000011149 // Keep track of the mappable components and base declarations in this clause.
11150 // Each entry in the list is going to have a list of components associated. We
11151 // record each set of the components so that we can build the clause later on.
11152 // In the end we should have the same amount of declarations and component
11153 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000011154
Samuel Antao661c0902016-05-26 17:39:58 +000011155 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000011156 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011157 SourceLocation ELoc = RE->getExprLoc();
11158
Kelvin Li0bff7af2015-11-23 05:32:03 +000011159 auto *VE = RE->IgnoreParenLValueCasts();
11160
11161 if (VE->isValueDependent() || VE->isTypeDependent() ||
11162 VE->isInstantiationDependent() ||
11163 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011164 // We can only analyze this information once the missing information is
11165 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000011166 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011167 continue;
11168 }
11169
11170 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011171
Samuel Antao5de996e2016-01-22 20:21:36 +000011172 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000011173 SemaRef.Diag(ELoc,
11174 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000011175 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000011176 continue;
11177 }
11178
Samuel Antao90927002016-04-26 14:54:23 +000011179 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
11180 ValueDecl *CurDeclaration = nullptr;
11181
11182 // Obtain the array or member expression bases if required. Also, fill the
11183 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000011184 auto *BE =
11185 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000011186 if (!BE)
11187 continue;
11188
Samuel Antao90927002016-04-26 14:54:23 +000011189 assert(!CurComponents.empty() &&
11190 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000011191
Samuel Antao90927002016-04-26 14:54:23 +000011192 // For the following checks, we rely on the base declaration which is
11193 // expected to be associated with the last component. The declaration is
11194 // expected to be a variable or a field (if 'this' is being mapped).
11195 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
11196 assert(CurDeclaration && "Null decl on map clause.");
11197 assert(
11198 CurDeclaration->isCanonicalDecl() &&
11199 "Expecting components to have associated only canonical declarations.");
11200
11201 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
11202 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000011203
11204 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000011205 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000011206
11207 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000011208 // threadprivate variables cannot appear in a map clause.
11209 // OpenMP 4.5 [2.10.5, target update Construct]
11210 // threadprivate variables cannot appear in a from clause.
11211 if (VD && DSAS->isThreadPrivate(VD)) {
11212 auto DVar = DSAS->getTopDSA(VD, false);
11213 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
11214 << getOpenMPClauseName(CKind);
11215 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011216 continue;
11217 }
11218
Samuel Antao5de996e2016-01-22 20:21:36 +000011219 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
11220 // A list item cannot appear in both a map clause and a data-sharing
11221 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000011222
Samuel Antao5de996e2016-01-22 20:21:36 +000011223 // Check conflicts with other map clause expressions. We check the conflicts
11224 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000011225 // environment, because the restrictions are different. We only have to
11226 // check conflicts across regions for the map clauses.
11227 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11228 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011229 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011230 if (CKind == OMPC_map &&
11231 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
11232 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000011233 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011234
Samuel Antao661c0902016-05-26 17:39:58 +000011235 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000011236 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11237 // If the type of a list item is a reference to a type T then the type will
11238 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011239 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011240
Samuel Antao661c0902016-05-26 17:39:58 +000011241 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
11242 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000011243 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000011244 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000011245 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
11246 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000011247 continue;
11248
Samuel Antao661c0902016-05-26 17:39:58 +000011249 if (CKind == OMPC_map) {
11250 // target enter data
11251 // OpenMP [2.10.2, Restrictions, p. 99]
11252 // A map-type must be specified in all map clauses and must be either
11253 // to or alloc.
11254 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
11255 if (DKind == OMPD_target_enter_data &&
11256 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
11257 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11258 << (IsMapTypeImplicit ? 1 : 0)
11259 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11260 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011261 continue;
11262 }
Samuel Antao661c0902016-05-26 17:39:58 +000011263
11264 // target exit_data
11265 // OpenMP [2.10.3, Restrictions, p. 102]
11266 // A map-type must be specified in all map clauses and must be either
11267 // from, release, or delete.
11268 if (DKind == OMPD_target_exit_data &&
11269 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
11270 MapType == OMPC_MAP_delete)) {
11271 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
11272 << (IsMapTypeImplicit ? 1 : 0)
11273 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
11274 << getOpenMPDirectiveName(DKind);
11275 continue;
11276 }
11277
11278 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11279 // A list item cannot appear in both a map clause and a data-sharing
11280 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000011281 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000011282 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000011283 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000011284 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
11285 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000011286 auto DVar = DSAS->getTopDSA(VD, false);
11287 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011288 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000011289 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000011290 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000011291 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
11292 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
11293 continue;
11294 }
11295 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011296 }
11297
Samuel Antao90927002016-04-26 14:54:23 +000011298 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000011299 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000011300
11301 // Store the components in the stack so that they can be used to check
11302 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000011303 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
11304 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000011305
11306 // Save the components and declaration to create the clause. For purposes of
11307 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000011308 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000011309 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11310 MVLI.VarComponents.back().append(CurComponents.begin(),
11311 CurComponents.end());
11312 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
11313 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011314 }
Samuel Antao661c0902016-05-26 17:39:58 +000011315}
11316
11317OMPClause *
11318Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
11319 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11320 SourceLocation MapLoc, SourceLocation ColonLoc,
11321 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11322 SourceLocation LParenLoc, SourceLocation EndLoc) {
11323 MappableVarListInfo MVLI(VarList);
11324 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
11325 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011326
Samuel Antao5de996e2016-01-22 20:21:36 +000011327 // We need to produce a map clause even if we don't have variables so that
11328 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000011329 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11330 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11331 MVLI.VarComponents, MapTypeModifier, MapType,
11332 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000011333}
Kelvin Li099bb8c2015-11-24 20:50:12 +000011334
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011335QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
11336 TypeResult ParsedType) {
11337 assert(ParsedType.isUsable());
11338
11339 QualType ReductionType = GetTypeFromParser(ParsedType.get());
11340 if (ReductionType.isNull())
11341 return QualType();
11342
11343 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
11344 // A type name in a declare reduction directive cannot be a function type, an
11345 // array type, a reference type, or a type qualified with const, volatile or
11346 // restrict.
11347 if (ReductionType.hasQualifiers()) {
11348 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
11349 return QualType();
11350 }
11351
11352 if (ReductionType->isFunctionType()) {
11353 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
11354 return QualType();
11355 }
11356 if (ReductionType->isReferenceType()) {
11357 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
11358 return QualType();
11359 }
11360 if (ReductionType->isArrayType()) {
11361 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
11362 return QualType();
11363 }
11364 return ReductionType;
11365}
11366
11367Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
11368 Scope *S, DeclContext *DC, DeclarationName Name,
11369 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
11370 AccessSpecifier AS, Decl *PrevDeclInScope) {
11371 SmallVector<Decl *, 8> Decls;
11372 Decls.reserve(ReductionTypes.size());
11373
11374 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
11375 ForRedeclaration);
11376 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
11377 // A reduction-identifier may not be re-declared in the current scope for the
11378 // same type or for a type that is compatible according to the base language
11379 // rules.
11380 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
11381 OMPDeclareReductionDecl *PrevDRD = nullptr;
11382 bool InCompoundScope = true;
11383 if (S != nullptr) {
11384 // Find previous declaration with the same name not referenced in other
11385 // declarations.
11386 FunctionScopeInfo *ParentFn = getEnclosingFunction();
11387 InCompoundScope =
11388 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
11389 LookupName(Lookup, S);
11390 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
11391 /*AllowInlineNamespace=*/false);
11392 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
11393 auto Filter = Lookup.makeFilter();
11394 while (Filter.hasNext()) {
11395 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
11396 if (InCompoundScope) {
11397 auto I = UsedAsPrevious.find(PrevDecl);
11398 if (I == UsedAsPrevious.end())
11399 UsedAsPrevious[PrevDecl] = false;
11400 if (auto *D = PrevDecl->getPrevDeclInScope())
11401 UsedAsPrevious[D] = true;
11402 }
11403 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
11404 PrevDecl->getLocation();
11405 }
11406 Filter.done();
11407 if (InCompoundScope) {
11408 for (auto &PrevData : UsedAsPrevious) {
11409 if (!PrevData.second) {
11410 PrevDRD = PrevData.first;
11411 break;
11412 }
11413 }
11414 }
11415 } else if (PrevDeclInScope != nullptr) {
11416 auto *PrevDRDInScope = PrevDRD =
11417 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
11418 do {
11419 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
11420 PrevDRDInScope->getLocation();
11421 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
11422 } while (PrevDRDInScope != nullptr);
11423 }
11424 for (auto &TyData : ReductionTypes) {
11425 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
11426 bool Invalid = false;
11427 if (I != PreviousRedeclTypes.end()) {
11428 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
11429 << TyData.first;
11430 Diag(I->second, diag::note_previous_definition);
11431 Invalid = true;
11432 }
11433 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
11434 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
11435 Name, TyData.first, PrevDRD);
11436 DC->addDecl(DRD);
11437 DRD->setAccess(AS);
11438 Decls.push_back(DRD);
11439 if (Invalid)
11440 DRD->setInvalidDecl();
11441 else
11442 PrevDRD = DRD;
11443 }
11444
11445 return DeclGroupPtrTy::make(
11446 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
11447}
11448
11449void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
11450 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11451
11452 // Enter new function scope.
11453 PushFunctionScope();
11454 getCurFunction()->setHasBranchProtectedScope();
11455 getCurFunction()->setHasOMPDeclareReductionCombiner();
11456
11457 if (S != nullptr)
11458 PushDeclContext(S, DRD);
11459 else
11460 CurContext = DRD;
11461
Faisal Valid143a0c2017-04-01 21:30:49 +000011462 PushExpressionEvaluationContext(
11463 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011464
11465 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011466 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
11467 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
11468 // uses semantics of argument handles by value, but it should be passed by
11469 // reference. C lang does not support references, so pass all parameters as
11470 // pointers.
11471 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011472 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011473 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011474 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
11475 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
11476 // uses semantics of argument handles by value, but it should be passed by
11477 // reference. C lang does not support references, so pass all parameters as
11478 // pointers.
11479 // Create 'T omp_out;' variable.
11480 auto *OmpOutParm =
11481 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
11482 if (S != nullptr) {
11483 PushOnScopeChains(OmpInParm, S);
11484 PushOnScopeChains(OmpOutParm, S);
11485 } else {
11486 DRD->addDecl(OmpInParm);
11487 DRD->addDecl(OmpOutParm);
11488 }
11489}
11490
11491void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
11492 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11493 DiscardCleanupsInEvaluationContext();
11494 PopExpressionEvaluationContext();
11495
11496 PopDeclContext();
11497 PopFunctionScopeInfo();
11498
11499 if (Combiner != nullptr)
11500 DRD->setCombiner(Combiner);
11501 else
11502 DRD->setInvalidDecl();
11503}
11504
11505void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
11506 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11507
11508 // Enter new function scope.
11509 PushFunctionScope();
11510 getCurFunction()->setHasBranchProtectedScope();
11511
11512 if (S != nullptr)
11513 PushDeclContext(S, DRD);
11514 else
11515 CurContext = DRD;
11516
Faisal Valid143a0c2017-04-01 21:30:49 +000011517 PushExpressionEvaluationContext(
11518 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011519
11520 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011521 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
11522 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
11523 // uses semantics of argument handles by value, but it should be passed by
11524 // reference. C lang does not support references, so pass all parameters as
11525 // pointers.
11526 // Create 'T omp_priv;' variable.
11527 auto *OmpPrivParm =
11528 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011529 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
11530 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
11531 // uses semantics of argument handles by value, but it should be passed by
11532 // reference. C lang does not support references, so pass all parameters as
11533 // pointers.
11534 // Create 'T omp_orig;' variable.
11535 auto *OmpOrigParm =
11536 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000011537 if (S != nullptr) {
11538 PushOnScopeChains(OmpPrivParm, S);
11539 PushOnScopeChains(OmpOrigParm, S);
11540 } else {
11541 DRD->addDecl(OmpPrivParm);
11542 DRD->addDecl(OmpOrigParm);
11543 }
11544}
11545
11546void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
11547 Expr *Initializer) {
11548 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11549 DiscardCleanupsInEvaluationContext();
11550 PopExpressionEvaluationContext();
11551
11552 PopDeclContext();
11553 PopFunctionScopeInfo();
11554
11555 if (Initializer != nullptr)
11556 DRD->setInitializer(Initializer);
11557 else
11558 DRD->setInvalidDecl();
11559}
11560
11561Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
11562 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
11563 for (auto *D : DeclReductions.get()) {
11564 if (IsValid) {
11565 auto *DRD = cast<OMPDeclareReductionDecl>(D);
11566 if (S != nullptr)
11567 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
11568 } else
11569 D->setInvalidDecl();
11570 }
11571 return DeclReductions;
11572}
11573
David Majnemer9d168222016-08-05 17:44:54 +000011574OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000011575 SourceLocation StartLoc,
11576 SourceLocation LParenLoc,
11577 SourceLocation EndLoc) {
11578 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011579 Stmt *HelperValStmt = nullptr;
11580 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011581
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011582 // OpenMP [teams Constrcut, Restrictions]
11583 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011584 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
11585 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011586 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000011587
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011588 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11589 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
11590 if (CaptureRegion != OMPD_unknown) {
11591 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11592 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11593 HelperValStmt = buildPreInits(Context, Captures);
11594 }
11595
11596 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
11597 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000011598}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011599
11600OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11601 SourceLocation StartLoc,
11602 SourceLocation LParenLoc,
11603 SourceLocation EndLoc) {
11604 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011605 Stmt *HelperValStmt = nullptr;
11606 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011607
11608 // OpenMP [teams Constrcut, Restrictions]
11609 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011610 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
11611 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011612 return nullptr;
11613
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011614 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11615 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
11616 if (CaptureRegion != OMPD_unknown) {
11617 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11618 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11619 HelperValStmt = buildPreInits(Context, Captures);
11620 }
11621
11622 return new (Context) OMPThreadLimitClause(
11623 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011624}
Alexey Bataeva0569352015-12-01 10:17:31 +000011625
11626OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
11627 SourceLocation StartLoc,
11628 SourceLocation LParenLoc,
11629 SourceLocation EndLoc) {
11630 Expr *ValExpr = Priority;
11631
11632 // OpenMP [2.9.1, task Constrcut]
11633 // The priority-value is a non-negative numerical scalar expression.
11634 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
11635 /*StrictlyPositive=*/false))
11636 return nullptr;
11637
11638 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11639}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011640
11641OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
11642 SourceLocation StartLoc,
11643 SourceLocation LParenLoc,
11644 SourceLocation EndLoc) {
11645 Expr *ValExpr = Grainsize;
11646
11647 // OpenMP [2.9.2, taskloop Constrcut]
11648 // The parameter of the grainsize clause must be a positive integer
11649 // expression.
11650 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
11651 /*StrictlyPositive=*/true))
11652 return nullptr;
11653
11654 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11655}
Alexey Bataev382967a2015-12-08 12:06:20 +000011656
11657OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
11658 SourceLocation StartLoc,
11659 SourceLocation LParenLoc,
11660 SourceLocation EndLoc) {
11661 Expr *ValExpr = NumTasks;
11662
11663 // OpenMP [2.9.2, taskloop Constrcut]
11664 // The parameter of the num_tasks clause must be a positive integer
11665 // expression.
11666 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11667 /*StrictlyPositive=*/true))
11668 return nullptr;
11669
11670 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11671}
11672
Alexey Bataev28c75412015-12-15 08:19:24 +000011673OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11674 SourceLocation LParenLoc,
11675 SourceLocation EndLoc) {
11676 // OpenMP [2.13.2, critical construct, Description]
11677 // ... where hint-expression is an integer constant expression that evaluates
11678 // to a valid lock hint.
11679 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11680 if (HintExpr.isInvalid())
11681 return nullptr;
11682 return new (Context)
11683 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11684}
11685
Carlo Bertollib4adf552016-01-15 18:50:31 +000011686OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11687 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11688 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11689 SourceLocation EndLoc) {
11690 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11691 std::string Values;
11692 Values += "'";
11693 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11694 Values += "'";
11695 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11696 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11697 return nullptr;
11698 }
11699 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011700 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011701 if (ChunkSize) {
11702 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11703 !ChunkSize->isInstantiationDependent() &&
11704 !ChunkSize->containsUnexpandedParameterPack()) {
11705 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11706 ExprResult Val =
11707 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11708 if (Val.isInvalid())
11709 return nullptr;
11710
11711 ValExpr = Val.get();
11712
11713 // OpenMP [2.7.1, Restrictions]
11714 // chunk_size must be a loop invariant integer expression with a positive
11715 // value.
11716 llvm::APSInt Result;
11717 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11718 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11719 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11720 << "dist_schedule" << ChunkSize->getSourceRange();
11721 return nullptr;
11722 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011723 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11724 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011725 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11726 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11727 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011728 }
11729 }
11730 }
11731
11732 return new (Context)
11733 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011734 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011735}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011736
11737OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11738 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11739 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11740 SourceLocation KindLoc, SourceLocation EndLoc) {
11741 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011742 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011743 std::string Value;
11744 SourceLocation Loc;
11745 Value += "'";
11746 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11747 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011748 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011749 Loc = MLoc;
11750 } else {
11751 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011752 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011753 Loc = KindLoc;
11754 }
11755 Value += "'";
11756 Diag(Loc, diag::err_omp_unexpected_clause_value)
11757 << Value << getOpenMPClauseName(OMPC_defaultmap);
11758 return nullptr;
11759 }
11760
11761 return new (Context)
11762 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11763}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011764
11765bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11766 DeclContext *CurLexicalContext = getCurLexicalContext();
11767 if (!CurLexicalContext->isFileContext() &&
11768 !CurLexicalContext->isExternCContext() &&
11769 !CurLexicalContext->isExternCXXContext()) {
11770 Diag(Loc, diag::err_omp_region_not_file_context);
11771 return false;
11772 }
11773 if (IsInOpenMPDeclareTargetContext) {
11774 Diag(Loc, diag::err_omp_enclosed_declare_target);
11775 return false;
11776 }
11777
11778 IsInOpenMPDeclareTargetContext = true;
11779 return true;
11780}
11781
11782void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11783 assert(IsInOpenMPDeclareTargetContext &&
11784 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11785
11786 IsInOpenMPDeclareTargetContext = false;
11787}
11788
David Majnemer9d168222016-08-05 17:44:54 +000011789void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11790 CXXScopeSpec &ScopeSpec,
11791 const DeclarationNameInfo &Id,
11792 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11793 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011794 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11795 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11796
11797 if (Lookup.isAmbiguous())
11798 return;
11799 Lookup.suppressDiagnostics();
11800
11801 if (!Lookup.isSingleResult()) {
11802 if (TypoCorrection Corrected =
11803 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11804 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11805 CTK_ErrorRecovery)) {
11806 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11807 << Id.getName());
11808 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11809 return;
11810 }
11811
11812 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11813 return;
11814 }
11815
11816 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11817 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11818 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11819 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11820
11821 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11822 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11823 ND->addAttr(A);
11824 if (ASTMutationListener *ML = Context.getASTMutationListener())
11825 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11826 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11827 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11828 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11829 << Id.getName();
11830 }
11831 } else
11832 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11833}
11834
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011835static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11836 Sema &SemaRef, Decl *D) {
11837 if (!D)
11838 return;
11839 Decl *LD = nullptr;
11840 if (isa<TagDecl>(D)) {
11841 LD = cast<TagDecl>(D)->getDefinition();
11842 } else if (isa<VarDecl>(D)) {
11843 LD = cast<VarDecl>(D)->getDefinition();
11844
11845 // If this is an implicit variable that is legal and we do not need to do
11846 // anything.
11847 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011848 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11849 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11850 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011851 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011852 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011853 return;
11854 }
11855
11856 } else if (isa<FunctionDecl>(D)) {
11857 const FunctionDecl *FD = nullptr;
11858 if (cast<FunctionDecl>(D)->hasBody(FD))
11859 LD = const_cast<FunctionDecl *>(FD);
11860
11861 // If the definition is associated with the current declaration in the
11862 // target region (it can be e.g. a lambda) that is legal and we do not need
11863 // to do anything else.
11864 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011865 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11866 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11867 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011868 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011869 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011870 return;
11871 }
11872 }
11873 if (!LD)
11874 LD = D;
11875 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11876 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11877 // Outlined declaration is not declared target.
11878 if (LD->isOutOfLine()) {
11879 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11880 SemaRef.Diag(SL, diag::note_used_here) << SR;
11881 } else {
11882 DeclContext *DC = LD->getDeclContext();
11883 while (DC) {
11884 if (isa<FunctionDecl>(DC) &&
11885 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11886 break;
11887 DC = DC->getParent();
11888 }
11889 if (DC)
11890 return;
11891
11892 // Is not declared in target context.
11893 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11894 SemaRef.Diag(SL, diag::note_used_here) << SR;
11895 }
11896 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011897 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11898 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11899 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011900 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011901 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011902 }
11903}
11904
11905static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11906 Sema &SemaRef, DSAStackTy *Stack,
11907 ValueDecl *VD) {
11908 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11909 return true;
11910 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11911 return false;
11912 return true;
11913}
11914
11915void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11916 if (!D || D->isInvalidDecl())
11917 return;
11918 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11919 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11920 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11921 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11922 if (DSAStack->isThreadPrivate(VD)) {
11923 Diag(SL, diag::err_omp_threadprivate_in_target);
11924 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11925 return;
11926 }
11927 }
11928 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11929 // Problem if any with var declared with incomplete type will be reported
11930 // as normal, so no need to check it here.
11931 if ((E || !VD->getType()->isIncompleteType()) &&
11932 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11933 // Mark decl as declared target to prevent further diagnostic.
11934 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011935 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11936 Context, OMPDeclareTargetDeclAttr::MT_To);
11937 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011938 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011939 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011940 }
11941 return;
11942 }
11943 }
11944 if (!E) {
11945 // Checking declaration inside declare target region.
11946 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11947 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011948 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11949 Context, OMPDeclareTargetDeclAttr::MT_To);
11950 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011951 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011952 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011953 }
11954 return;
11955 }
11956 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11957}
Samuel Antao661c0902016-05-26 17:39:58 +000011958
11959OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11960 SourceLocation StartLoc,
11961 SourceLocation LParenLoc,
11962 SourceLocation EndLoc) {
11963 MappableVarListInfo MVLI(VarList);
11964 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11965 if (MVLI.ProcessedVarList.empty())
11966 return nullptr;
11967
11968 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11969 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11970 MVLI.VarComponents);
11971}
Samuel Antaoec172c62016-05-26 17:49:04 +000011972
11973OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11974 SourceLocation StartLoc,
11975 SourceLocation LParenLoc,
11976 SourceLocation EndLoc) {
11977 MappableVarListInfo MVLI(VarList);
11978 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11979 if (MVLI.ProcessedVarList.empty())
11980 return nullptr;
11981
11982 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11983 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11984 MVLI.VarComponents);
11985}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011986
11987OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11988 SourceLocation StartLoc,
11989 SourceLocation LParenLoc,
11990 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011991 MappableVarListInfo MVLI(VarList);
11992 SmallVector<Expr *, 8> PrivateCopies;
11993 SmallVector<Expr *, 8> Inits;
11994
Carlo Bertolli2404b172016-07-13 15:37:16 +000011995 for (auto &RefExpr : VarList) {
11996 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11997 SourceLocation ELoc;
11998 SourceRange ERange;
11999 Expr *SimpleRefExpr = RefExpr;
12000 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12001 if (Res.second) {
12002 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012003 MVLI.ProcessedVarList.push_back(RefExpr);
12004 PrivateCopies.push_back(nullptr);
12005 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012006 }
12007 ValueDecl *D = Res.first;
12008 if (!D)
12009 continue;
12010
12011 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012012 Type = Type.getNonReferenceType().getUnqualifiedType();
12013
12014 auto *VD = dyn_cast<VarDecl>(D);
12015
12016 // Item should be a pointer or reference to pointer.
12017 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012018 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12019 << 0 << RefExpr->getSourceRange();
12020 continue;
12021 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012022
12023 // Build the private variable and the expression that refers to it.
12024 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12025 D->hasAttrs() ? &D->getAttrs() : nullptr);
12026 if (VDPrivate->isInvalidDecl())
12027 continue;
12028
12029 CurContext->addDecl(VDPrivate);
12030 auto VDPrivateRefExpr = buildDeclRefExpr(
12031 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12032
12033 // Add temporary variable to initialize the private copy of the pointer.
12034 auto *VDInit =
12035 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
12036 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12037 RefExpr->getExprLoc());
12038 AddInitializerToDecl(VDPrivate,
12039 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012040 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000012041
12042 // If required, build a capture to implement the privatization initialized
12043 // with the current list item value.
12044 DeclRefExpr *Ref = nullptr;
12045 if (!VD)
12046 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12047 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
12048 PrivateCopies.push_back(VDPrivateRefExpr);
12049 Inits.push_back(VDInitRefExpr);
12050
12051 // We need to add a data sharing attribute for this variable to make sure it
12052 // is correctly captured. A variable that shows up in a use_device_ptr has
12053 // similar properties of a first private variable.
12054 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12055
12056 // Create a mappable component for the list item. List items in this clause
12057 // only need a component.
12058 MVLI.VarBaseDeclarations.push_back(D);
12059 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12060 MVLI.VarComponents.back().push_back(
12061 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000012062 }
12063
Samuel Antaocc10b852016-07-28 14:23:26 +000012064 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000012065 return nullptr;
12066
Samuel Antaocc10b852016-07-28 14:23:26 +000012067 return OMPUseDevicePtrClause::Create(
12068 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12069 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012070}
Carlo Bertolli70594e92016-07-13 17:16:49 +000012071
12072OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
12073 SourceLocation StartLoc,
12074 SourceLocation LParenLoc,
12075 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000012076 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012077 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000012078 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000012079 SourceLocation ELoc;
12080 SourceRange ERange;
12081 Expr *SimpleRefExpr = RefExpr;
12082 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12083 if (Res.second) {
12084 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000012085 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012086 }
12087 ValueDecl *D = Res.first;
12088 if (!D)
12089 continue;
12090
12091 QualType Type = D->getType();
12092 // item should be a pointer or array or reference to pointer or array
12093 if (!Type.getNonReferenceType()->isPointerType() &&
12094 !Type.getNonReferenceType()->isArrayType()) {
12095 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
12096 << 0 << RefExpr->getSourceRange();
12097 continue;
12098 }
Samuel Antao6890b092016-07-28 14:25:09 +000012099
12100 // Check if the declaration in the clause does not show up in any data
12101 // sharing attribute.
12102 auto DVar = DSAStack->getTopDSA(D, false);
12103 if (isOpenMPPrivate(DVar.CKind)) {
12104 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12105 << getOpenMPClauseName(DVar.CKind)
12106 << getOpenMPClauseName(OMPC_is_device_ptr)
12107 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12108 ReportOriginalDSA(*this, DSAStack, D, DVar);
12109 continue;
12110 }
12111
12112 Expr *ConflictExpr;
12113 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012114 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012115 [&ConflictExpr](
12116 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
12117 OpenMPClauseKind) -> bool {
12118 ConflictExpr = R.front().getAssociatedExpression();
12119 return true;
12120 })) {
12121 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
12122 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
12123 << ConflictExpr->getSourceRange();
12124 continue;
12125 }
12126
12127 // Store the components in the stack so that they can be used to check
12128 // against other clauses later on.
12129 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
12130 DSAStack->addMappableExpressionComponents(
12131 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
12132
12133 // Record the expression we've just processed.
12134 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
12135
12136 // Create a mappable component for the list item. List items in this clause
12137 // only need a component. We use a null declaration to signal fields in
12138 // 'this'.
12139 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
12140 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
12141 "Unexpected device pointer expression!");
12142 MVLI.VarBaseDeclarations.push_back(
12143 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
12144 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12145 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012146 }
12147
Samuel Antao6890b092016-07-28 14:25:09 +000012148 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000012149 return nullptr;
12150
Samuel Antao6890b092016-07-28 14:25:09 +000012151 return OMPIsDevicePtrClause::Create(
12152 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
12153 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012154}