blob: f9474b36c2c94dcf78d7eee5c96ade01eef3aa01 [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 Bataeva769e072013-03-22 06:34:35 +000034using namespace clang;
35
Alexey Bataev758e55e2013-09-06 18:03:48 +000036//===----------------------------------------------------------------------===//
37// Stack of data-sharing attributes for variables
38//===----------------------------------------------------------------------===//
39
40namespace {
41/// \brief Default data sharing attributes, which can be applied to directive.
42enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000043 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000046};
Alexey Bataev7ff55242014-06-19 09:13:45 +000047
Alexey Bataev758e55e2013-09-06 18:03:48 +000048/// \brief Stack for tracking declarations used in OpenMP directives and
49/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000050class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000051public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000052 struct DSAVarData final {
53 OpenMPDirectiveKind DKind = OMPD_unknown;
54 OpenMPClauseKind CKind = OMPC_unknown;
55 Expr *RefExpr = nullptr;
56 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000057 SourceLocation ImplicitDSALoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000058 DSAVarData() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000059 };
Alexey Bataev8b427062016-05-25 12:36:08 +000060 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
61 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000062
Alexey Bataev758e55e2013-09-06 18:03:48 +000063private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000064 struct DSAInfo final {
65 OpenMPClauseKind Attributes = OMPC_unknown;
66 /// Pointer to a reference expression and a flag which shows that the
67 /// variable is marked as lastprivate(true) or not (false).
68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
69 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000070 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000071 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000073 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000075 /// Struct that associates a component with the clause kind where they are
76 /// found.
77 struct MappedExprComponentTy {
78 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
79 OpenMPClauseKind Kind = OMPC_unknown;
80 };
81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000082 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000083 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
84 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000085 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
86 DoacrossDependMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +000087
Alexey Bataev7ace49d2016-05-17 08:55:33 +000088 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000089 DeclSAMapTy SharingMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000090 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +000091 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000092 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000093 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +000094 SourceLocation DefaultAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000095 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +000096 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000097 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000098 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +000099 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
100 /// get the data (loop counters etc.) about enclosing loop-based construct.
101 /// This data is required during codegen.
102 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000103 /// \brief first argument (Expr *) contains optional argument of the
104 /// 'ordered' clause, the second one is true if the regions has 'ordered'
105 /// clause, false otherwise.
106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000107 bool NowaitRegion = false;
108 bool CancelRegion = false;
109 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000110 SourceLocation InnerTeamsRegionLoc;
Alexey Bataeved09d242014-05-28 05:53:51 +0000111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000112 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
114 ConstructLoc(Loc) {}
115 SharingMapTy() {}
Alexey Bataev758e55e2013-09-06 18:03:48 +0000116 };
117
Axel Naumann323862e2016-02-03 10:45:22 +0000118 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000119
120 /// \brief Stack of used declaration and their data-sharing attributes.
121 StackTy Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000122 /// \brief true, if check for DSA must be from parent directive, false, if
123 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000124 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000125 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000127 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128
129 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
130
David Majnemer9d168222016-08-05 17:44:54 +0000131 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000132
133 /// \brief Checks if the variable is a local for OpenMP region.
134 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000135
Alexey Bataev758e55e2013-09-06 18:03:48 +0000136public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 explicit DSAStackTy(Sema &S) : Stack(1), SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000138
Alexey Bataevaac108a2015-06-23 04:51:00 +0000139 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
140 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000141
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000142 bool isForceVarCapturing() const { return ForceCapturing; }
143 void setForceVarCapturing(bool V) { ForceCapturing = V; }
144
Alexey Bataev758e55e2013-09-06 18:03:48 +0000145 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000146 Scope *CurScope, SourceLocation Loc) {
147 Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
148 Stack.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 }
150
151 void pop() {
152 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
153 Stack.pop_back();
154 }
155
Alexey Bataev28c75412015-12-15 08:19:24 +0000156 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
157 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
158 }
159 const std::pair<OMPCriticalDirective *, llvm::APSInt>
160 getCriticalWithHint(const DeclarationNameInfo &Name) const {
161 auto I = Criticals.find(Name.getAsString());
162 if (I != Criticals.end())
163 return I->second;
164 return std::make_pair(nullptr, llvm::APSInt());
165 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000166 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000167 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000168 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000169 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000170
Alexey Bataev9c821032015-04-30 04:23:23 +0000171 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000172 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000173 /// \brief Check if the specified variable is a loop control variable for
174 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000175 /// \return The index of the loop control variable in the list of associated
176 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000177 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000178 /// \brief Check if the specified variable is a loop control variable for
179 /// parent region.
180 /// \return The index of the loop control variable in the list of associated
181 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000182 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000183 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
184 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000185 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000186
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000188 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
189 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190
Alexey Bataev758e55e2013-09-06 18:03:48 +0000191 /// \brief Returns data sharing attributes from top of the stack for the
192 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000193 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000194 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000195 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000196 /// \brief Checks if the specified variables has data-sharing attributes which
197 /// match specified \a CPred predicate in any directive which matches \a DPred
198 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000199 DSAVarData hasDSA(ValueDecl *D,
200 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
201 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
202 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000203 /// \brief Checks if the specified variables has data-sharing attributes which
204 /// match specified \a CPred predicate in any innermost directive which
205 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000206 DSAVarData
207 hasInnermostDSA(ValueDecl *D,
208 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
209 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
210 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000211 /// \brief Checks if the specified variables has explicit data-sharing
212 /// attributes which match specified \a CPred predicate at the specified
213 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000214 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000215 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000216 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000217
218 /// \brief Returns true if the directive at level \Level matches in the
219 /// specified \a DPred predicate.
220 bool hasExplicitDirective(
221 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
222 unsigned Level);
223
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000224 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000225 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
226 const DeclarationNameInfo &,
227 SourceLocation)> &DPred,
228 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000229
Alexey Bataev758e55e2013-09-06 18:03:48 +0000230 /// \brief Returns currently analyzed directive.
231 OpenMPDirectiveKind getCurrentDirective() const {
232 return Stack.back().Directive;
233 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000234 /// \brief Returns parent directive.
235 OpenMPDirectiveKind getParentDirective() const {
236 if (Stack.size() > 2)
237 return Stack[Stack.size() - 2].Directive;
238 return OMPD_unknown;
239 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240
241 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000242 void setDefaultDSANone(SourceLocation Loc) {
243 Stack.back().DefaultAttr = DSA_none;
244 Stack.back().DefaultAttrLoc = Loc;
245 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000246 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000247 void setDefaultDSAShared(SourceLocation Loc) {
248 Stack.back().DefaultAttr = DSA_shared;
249 Stack.back().DefaultAttrLoc = Loc;
250 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000251
252 DefaultDataSharingAttributes getDefaultDSA() const {
253 return Stack.back().DefaultAttr;
254 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000255 SourceLocation getDefaultDSALocation() const {
256 return Stack.back().DefaultAttrLoc;
257 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000258
Alexey Bataevf29276e2014-06-18 04:14:57 +0000259 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000260 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000261 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000262 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000263 }
264
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000265 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000266 void setOrderedRegion(bool IsOrdered, Expr *Param) {
267 Stack.back().OrderedRegion.setInt(IsOrdered);
268 Stack.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000269 }
270 /// \brief Returns true, if parent region is ordered (has associated
271 /// 'ordered' clause), false - otherwise.
272 bool isParentOrderedRegion() const {
273 if (Stack.size() > 2)
Alexey Bataev346265e2015-09-25 10:37:12 +0000274 return Stack[Stack.size() - 2].OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000275 return false;
276 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000277 /// \brief Returns optional parameter for the ordered region.
278 Expr *getParentOrderedRegionParam() const {
279 if (Stack.size() > 2)
280 return Stack[Stack.size() - 2].OrderedRegion.getPointer();
281 return nullptr;
282 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000283 /// \brief Marks current region as nowait (it has a 'nowait' clause).
284 void setNowaitRegion(bool IsNowait = true) {
285 Stack.back().NowaitRegion = IsNowait;
286 }
287 /// \brief Returns true, if parent region is nowait (has associated
288 /// 'nowait' clause), false - otherwise.
289 bool isParentNowaitRegion() const {
290 if (Stack.size() > 2)
291 return Stack[Stack.size() - 2].NowaitRegion;
292 return false;
293 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000294 /// \brief Marks parent region as cancel region.
295 void setParentCancelRegion(bool Cancel = true) {
296 if (Stack.size() > 2)
297 Stack[Stack.size() - 2].CancelRegion =
298 Stack[Stack.size() - 2].CancelRegion || Cancel;
299 }
300 /// \brief Return true if current region has inner cancel construct.
David Majnemer9d168222016-08-05 17:44:54 +0000301 bool isCancelRegion() const { return Stack.back().CancelRegion; }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000302
Alexey Bataev9c821032015-04-30 04:23:23 +0000303 /// \brief Set collapse value for the region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000304 void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000305 /// \brief Return collapse value for region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000306 unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
Alexey Bataev9c821032015-04-30 04:23:23 +0000307
Alexey Bataev13314bf2014-10-09 04:18:56 +0000308 /// \brief Marks current target region as one with closely nested teams
309 /// region.
310 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
311 if (Stack.size() > 2)
312 Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
313 }
314 /// \brief Returns true, if current region has closely nested teams region.
315 bool hasInnerTeamsRegion() const {
316 return getInnerTeamsRegionLoc().isValid();
317 }
318 /// \brief Returns location of the nested teams region (if any).
319 SourceLocation getInnerTeamsRegionLoc() const {
320 if (Stack.size() > 1)
321 return Stack.back().InnerTeamsRegionLoc;
322 return SourceLocation();
323 }
324
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000325 Scope *getCurScope() const { return Stack.back().CurScope; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 Scope *getCurScope() { return Stack.back().CurScope; }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000327 SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000328
Samuel Antao4c8035b2016-12-12 18:00:20 +0000329 /// Do the check specified in \a Check to all component lists and return true
330 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000331 bool checkMappableExprComponentListsForDecl(
332 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000333 const llvm::function_ref<
334 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
335 OpenMPClauseKind)> &Check) {
Samuel Antao5de996e2016-01-22 20:21:36 +0000336 auto SI = Stack.rbegin();
337 auto SE = Stack.rend();
338
339 if (SI == SE)
340 return false;
341
342 if (CurrentRegionOnly) {
343 SE = std::next(SI);
344 } else {
345 ++SI;
346 }
347
348 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000349 auto MI = SI->MappedExprComponents.find(VD);
350 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000351 for (auto &L : MI->second.Components)
352 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000353 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000354 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000355 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000356 }
357
Samuel Antao4c8035b2016-12-12 18:00:20 +0000358 /// Create a new mappable expression component list associated with a given
359 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000360 void addMappableExpressionComponents(
361 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000362 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
363 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao90927002016-04-26 14:54:23 +0000364 assert(Stack.size() > 1 &&
365 "Not expecting to retrieve components from a empty stack!");
366 auto &MEC = Stack.back().MappedExprComponents[VD];
367 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000368 MEC.Components.resize(MEC.Components.size() + 1);
369 MEC.Components.back().append(Components.begin(), Components.end());
370 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000371 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000372
373 unsigned getNestingLevel() const {
374 assert(Stack.size() > 1);
375 return Stack.size() - 2;
376 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000377 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
378 assert(Stack.size() > 2);
379 assert(isOpenMPWorksharingDirective(Stack[Stack.size() - 2].Directive));
380 Stack[Stack.size() - 2].DoacrossDepends.insert({C, OpsOffs});
381 }
382 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
383 getDoacrossDependClauses() const {
384 assert(Stack.size() > 1);
385 if (isOpenMPWorksharingDirective(Stack[Stack.size() - 1].Directive)) {
386 auto &Ref = Stack[Stack.size() - 1].DoacrossDepends;
387 return llvm::make_range(Ref.begin(), Ref.end());
388 }
389 return llvm::make_range(Stack[0].DoacrossDepends.end(),
390 Stack[0].DoacrossDepends.end());
391 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000392};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000393bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000394 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
395 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000396}
Alexey Bataeved09d242014-05-28 05:53:51 +0000397} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000398
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000399static ValueDecl *getCanonicalDecl(ValueDecl *D) {
400 auto *VD = dyn_cast<VarDecl>(D);
401 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000402 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000403 VD = VD->getCanonicalDecl();
404 D = VD;
405 } else {
406 assert(FD);
407 FD = FD->getCanonicalDecl();
408 D = FD;
409 }
410 return D;
411}
412
David Majnemer9d168222016-08-05 17:44:54 +0000413DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000414 ValueDecl *D) {
415 D = getCanonicalDecl(D);
416 auto *VD = dyn_cast<VarDecl>(D);
417 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000418 DSAVarData DVar;
Alexey Bataevdf9b1592014-06-25 04:09:13 +0000419 if (Iter == std::prev(Stack.rend())) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000420 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
421 // in a region but not in construct]
422 // File-scope or namespace-scope variables referenced in called routines
423 // in the region are shared unless they appear in a threadprivate
424 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000425 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000426 DVar.CKind = OMPC_shared;
427
428 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
429 // in a region but not in construct]
430 // Variables with static storage duration that are declared in called
431 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000432 if (VD && VD->hasGlobalStorage())
433 DVar.CKind = OMPC_shared;
434
435 // Non-static data members are shared by default.
436 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000437 DVar.CKind = OMPC_shared;
438
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439 return DVar;
440 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000441
Alexey Bataev758e55e2013-09-06 18:03:48 +0000442 DVar.DKind = Iter->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +0000443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
444 // in a Construct, C/C++, predetermined, p.1]
445 // Variables with automatic storage duration that are declared in a scope
446 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000447 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
448 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000449 DVar.CKind = OMPC_private;
450 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000451 }
452
Alexey Bataev758e55e2013-09-06 18:03:48 +0000453 // Explicitly specified attributes and local variables with predetermined
454 // attributes.
455 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000456 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000457 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000458 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000459 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000460 return DVar;
461 }
462
463 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
464 // in a Construct, C/C++, implicitly determined, p.1]
465 // In a parallel or task construct, the data-sharing attributes of these
466 // variables are determined by the default clause, if present.
467 switch (Iter->DefaultAttr) {
468 case DSA_shared:
469 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000471 return DVar;
472 case DSA_none:
473 return DVar;
474 case DSA_unspecified:
475 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
476 // in a Construct, implicitly determined, p.2]
477 // In a parallel construct, if no default clause is present, these
478 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000479 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000480 if (isOpenMPParallelDirective(DVar.DKind) ||
481 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000482 DVar.CKind = OMPC_shared;
483 return DVar;
484 }
485
486 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
487 // in a Construct, implicitly determined, p.4]
488 // In a task construct, if no default clause is present, a variable that in
489 // the enclosing context is determined to be shared by all implicit tasks
490 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000491 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000492 DSAVarData DVarTemp;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000493 for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000494 I != EE; ++I) {
Alexey Bataeved09d242014-05-28 05:53:51 +0000495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000496 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000497 // In a task construct, if no default clause is present, a variable
498 // whose data-sharing attribute is not determined by the rules above is
499 // firstprivate.
500 DVarTemp = getDSA(I, D);
501 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000502 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000503 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000504 return DVar;
505 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000506 if (isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000507 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000508 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000509 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000510 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000511 return DVar;
512 }
513 }
514 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
515 // in a Construct, implicitly determined, p.3]
516 // For constructs other than task, if no default clause is present, these
517 // variables inherit their data-sharing attributes from the enclosing
518 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000519 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000520}
521
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000522Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000523 assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000524 D = getCanonicalDecl(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000525 auto It = Stack.back().AlignedMap.find(D);
526 if (It == Stack.back().AlignedMap.end()) {
527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
528 Stack.back().AlignedMap[D] = NewDE;
529 return nullptr;
530 } else {
531 assert(It->second && "Unexpected nullptr expr in the aligned map");
532 return It->second;
533 }
534 return nullptr;
535}
536
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000537void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000538 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000539 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000540 Stack.back().LCVMap.insert(
541 std::make_pair(D, LCDeclInfo(Stack.back().LCVMap.size() + 1, Capture)));
Alexey Bataev9c821032015-04-30 04:23:23 +0000542}
543
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000544DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev9c821032015-04-30 04:23:23 +0000545 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000546 D = getCanonicalDecl(D);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000547 return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D]
548 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000549}
550
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000551DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000552 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000553 D = getCanonicalDecl(D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000554 return Stack[Stack.size() - 2].LCVMap.count(D) > 0
555 ? Stack[Stack.size() - 2].LCVMap[D]
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000556 : LCDeclInfo(0, nullptr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000557}
558
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000559ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000560 assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
561 if (Stack[Stack.size() - 2].LCVMap.size() < I)
562 return nullptr;
563 for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000564 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000565 return Pair.first;
566 }
567 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000568}
569
Alexey Bataev90c228f2016-02-08 09:29:13 +0000570void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
571 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000572 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573 if (A == OMPC_threadprivate) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000574 auto &Data = Stack[0].SharingMap[D];
575 Data.Attributes = A;
576 Data.RefExpr.setPointer(E);
577 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000578 } else {
579 assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000580 auto &Data = Stack.back().SharingMap[D];
581 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
582 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
583 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
584 (isLoopControlVariable(D).first && A == OMPC_private));
585 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
586 Data.RefExpr.setInt(/*IntVal=*/true);
587 return;
588 }
589 const bool IsLastprivate =
590 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
591 Data.Attributes = A;
592 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
593 Data.PrivateCopy = PrivateCopy;
594 if (PrivateCopy) {
595 auto &Data = Stack.back().SharingMap[PrivateCopy->getDecl()];
596 Data.Attributes = A;
597 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
598 Data.PrivateCopy = nullptr;
599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600 }
601}
602
Alexey Bataeved09d242014-05-28 05:53:51 +0000603bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000604 D = D->getCanonicalDecl();
Alexey Bataevec3da872014-01-31 05:15:34 +0000605 if (Stack.size() > 2) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000606 reverse_iterator I = Iter, E = std::prev(Stack.rend());
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000607 Scope *TopScope = nullptr;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000608 while (I != E && !isParallelOrTaskRegion(I->Directive)) {
Alexey Bataevec3da872014-01-31 05:15:34 +0000609 ++I;
610 }
Alexey Bataeved09d242014-05-28 05:53:51 +0000611 if (I == E)
612 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000613 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000614 Scope *CurScope = getCurScope();
615 while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000616 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000617 }
618 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000619 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000620 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621}
622
Alexey Bataev39f915b82015-05-08 10:41:21 +0000623/// \brief Build a variable declaration for OpenMP loop iteration variable.
624static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000625 StringRef Name, const AttrVec *Attrs = nullptr) {
Alexey Bataev39f915b82015-05-08 10:41:21 +0000626 DeclContext *DC = SemaRef.CurContext;
627 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
628 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
629 VarDecl *Decl =
630 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +0000631 if (Attrs) {
632 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
633 I != E; ++I)
634 Decl->addAttr(*I);
635 }
Alexey Bataev39f915b82015-05-08 10:41:21 +0000636 Decl->setImplicit();
637 return Decl;
638}
639
640static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
641 SourceLocation Loc,
642 bool RefersToCapture = false) {
643 D->setReferenced();
644 D->markUsed(S.Context);
645 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
646 SourceLocation(), D, RefersToCapture, Loc, Ty,
647 VK_LValue);
648}
649
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000650DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
651 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000652 DSAVarData DVar;
653
654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
655 // in a Construct, C/C++, predetermined, p.1]
656 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000657 auto *VD = dyn_cast<VarDecl>(D);
658 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
659 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000660 SemaRef.getLangOpts().OpenMPUseTLS &&
661 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000662 (VD && VD->getStorageClass() == SC_Register &&
663 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
664 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000665 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000666 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000667 }
668 if (Stack[0].SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000669 DVar.RefExpr = Stack[0].SharingMap[D].RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000670 DVar.CKind = OMPC_threadprivate;
671 return DVar;
672 }
673
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000674 if (Stack.size() == 1) {
675 // Not in OpenMP execution region and top scope was already checked.
676 return DVar;
677 }
678
Alexey Bataev758e55e2013-09-06 18:03:48 +0000679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000680 // in a Construct, C/C++, predetermined, p.4]
681 // Static data members are shared.
682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
683 // in a Construct, C/C++, predetermined, p.7]
684 // Variables with static storage duration that are declared in a scope
685 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000686 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000687 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000688 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000689 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +0000690 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000692 DVar.CKind = OMPC_shared;
693 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000694 }
695
696 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +0000697 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
698 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000699 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
700 // in a Construct, C/C++, predetermined, p.6]
701 // Variables with const qualified type having no mutable member are
702 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000703 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +0000704 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +0000705 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
706 if (auto *CTD = CTSD->getSpecializedTemplate())
707 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000708 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +0000709 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
710 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000711 // Variables with const-qualified type having no mutable member may be
712 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000713 DSAVarData DVarTemp = hasDSA(
714 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
715 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000716 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
717 return DVar;
718
Alexey Bataev758e55e2013-09-06 18:03:48 +0000719 DVar.CKind = OMPC_shared;
720 return DVar;
721 }
722
Alexey Bataev758e55e2013-09-06 18:03:48 +0000723 // Explicitly specified attributes and local variables with predetermined
724 // attributes.
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000725 auto StartI = std::next(Stack.rbegin());
726 auto EndI = std::prev(Stack.rend());
727 if (FromParent && StartI != EndI) {
728 StartI = std::next(StartI);
729 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000730 auto I = std::prev(StartI);
731 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000732 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000733 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000734 DVar.CKind = I->SharingMap[D].Attributes;
735 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000736 }
737
738 return DVar;
739}
740
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000741DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
742 bool FromParent) {
743 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000744 auto StartI = Stack.rbegin();
745 auto EndI = std::prev(Stack.rend());
746 if (FromParent && StartI != EndI) {
747 StartI = std::next(StartI);
748 }
749 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000750}
751
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000752DSAStackTy::DSAVarData
753DSAStackTy::hasDSA(ValueDecl *D,
754 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
755 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
756 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000757 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000758 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000759 auto EndI = Stack.rend();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000760 if (FromParent && StartI != EndI) {
761 StartI = std::next(StartI);
762 }
763 for (auto I = StartI, EE = EndI; I != EE; ++I) {
764 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +0000765 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000766 DSAVarData DVar = getDSA(I, D);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000767 if (CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000768 return DVar;
769 }
770 return DSAVarData();
771}
772
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000773DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
774 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
775 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
776 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000777 D = getCanonicalDecl(D);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000778 auto StartI = std::next(Stack.rbegin());
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000779 auto EndI = Stack.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +0000780 if (FromParent && StartI != EndI)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000781 StartI = std::next(StartI);
Alexey Bataeve3978122016-07-19 05:06:39 +0000782 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataevc5e02582014-06-16 07:08:35 +0000783 return DSAVarData();
Alexey Bataeve3978122016-07-19 05:06:39 +0000784 DSAVarData DVar = getDSA(StartI, D);
785 return CPred(DVar.CKind) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +0000786}
787
Alexey Bataevaac108a2015-06-23 04:51:00 +0000788bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 unsigned Level, bool NotLastprivate) {
Alexey Bataevaac108a2015-06-23 04:51:00 +0000791 if (CPred(ClauseKindMode))
792 return true;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000793 D = getCanonicalDecl(D);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000794 auto StartI = std::next(Stack.begin());
795 auto EndI = Stack.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +0000796 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +0000797 return false;
798 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000799 return (StartI->SharingMap.count(D) > 0) &&
800 StartI->SharingMap[D].RefExpr.getPointer() &&
801 CPred(StartI->SharingMap[D].Attributes) &&
802 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +0000803}
804
Samuel Antao4be30e92015-10-02 17:14:03 +0000805bool DSAStackTy::hasExplicitDirective(
806 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
807 unsigned Level) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000808 auto StartI = std::next(Stack.begin());
809 auto EndI = Stack.end();
Samuel Antao4be30e92015-10-02 17:14:03 +0000810 if (std::distance(StartI, EndI) <= (int)Level)
811 return false;
812 std::advance(StartI, Level);
813 return DPred(StartI->Directive);
814}
815
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000816bool DSAStackTy::hasDirective(
817 const llvm::function_ref<bool(OpenMPDirectiveKind,
818 const DeclarationNameInfo &, SourceLocation)>
819 &DPred,
820 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +0000821 // We look only in the enclosing region.
822 if (Stack.size() < 2)
823 return false;
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000824 auto StartI = std::next(Stack.rbegin());
825 auto EndI = std::prev(Stack.rend());
826 if (FromParent && StartI != EndI) {
827 StartI = std::next(StartI);
828 }
829 for (auto I = StartI, EE = EndI; I != EE; ++I) {
830 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
831 return true;
832 }
833 return false;
834}
835
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836void Sema::InitDataSharingAttributesStack() {
837 VarDataSharingAttributesStack = new DSAStackTy(*this);
838}
839
840#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
841
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000842bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000843 assert(LangOpts.OpenMP && "OpenMP is not allowed");
844
845 auto &Ctx = getASTContext();
846 bool IsByRef = true;
847
848 // Find the directive that is associated with the provided scope.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000849 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000850
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000852 // This table summarizes how a given variable should be passed to the device
853 // given its type and the clauses where it appears. This table is based on
854 // the description in OpenMP 4.5 [2.10.4, target Construct] and
855 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
856 //
857 // =========================================================================
858 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
859 // | |(tofrom:scalar)| | pvt | | | |
860 // =========================================================================
861 // | scl | | | | - | | bycopy|
862 // | scl | | - | x | - | - | bycopy|
863 // | scl | | x | - | - | - | null |
864 // | scl | x | | | - | | byref |
865 // | scl | x | - | x | - | - | bycopy|
866 // | scl | x | x | - | - | - | null |
867 // | scl | | - | - | - | x | byref |
868 // | scl | x | - | - | - | x | byref |
869 //
870 // | agg | n.a. | | | - | | byref |
871 // | agg | n.a. | - | x | - | - | byref |
872 // | agg | n.a. | x | - | - | - | null |
873 // | agg | n.a. | - | - | - | x | byref |
874 // | agg | n.a. | - | - | - | x[] | byref |
875 //
876 // | ptr | n.a. | | | - | | bycopy|
877 // | ptr | n.a. | - | x | - | - | bycopy|
878 // | ptr | n.a. | x | - | - | - | null |
879 // | ptr | n.a. | - | - | - | x | byref |
880 // | ptr | n.a. | - | - | - | x[] | bycopy|
881 // | ptr | n.a. | - | - | x | | bycopy|
882 // | ptr | n.a. | - | - | x | x | bycopy|
883 // | ptr | n.a. | - | - | x | x[] | bycopy|
884 // =========================================================================
885 // Legend:
886 // scl - scalar
887 // ptr - pointer
888 // agg - aggregate
889 // x - applies
890 // - - invalid in this combination
891 // [] - mapped with an array section
892 // byref - should be mapped by reference
893 // byval - should be mapped by value
894 // null - initialize a local variable to null on the device
895 //
896 // Observations:
897 // - All scalar declarations that show up in a map clause have to be passed
898 // by reference, because they may have been mapped in the enclosing data
899 // environment.
900 // - If the scalar value does not fit the size of uintptr, it has to be
901 // passed by reference, regardless the result in the table above.
902 // - For pointers mapped by value that have either an implicit map or an
903 // array section, the runtime library may pass the NULL value to the
904 // device instead of the value passed to it by the compiler.
905
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000906 if (Ty->isReferenceType())
907 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +0000908
909 // Locate map clauses and see if the variable being captured is referred to
910 // in any of those clauses. Here we only care about variables, not fields,
911 // because fields are part of aggregates.
912 bool IsVariableUsedInMapClause = false;
913 bool IsVariableAssociatedWithSection = false;
914
915 DSAStack->checkMappableExprComponentListsForDecl(
916 D, /*CurrentRegionOnly=*/true,
917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +0000918 MapExprComponents,
919 OpenMPClauseKind WhereFoundClauseKind) {
920 // Only the map clause information influences how a variable is
921 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +0000922 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +0000923 if (WhereFoundClauseKind != OMPC_map)
924 return false;
Samuel Antao86ace552016-04-27 22:40:57 +0000925
926 auto EI = MapExprComponents.rbegin();
927 auto EE = MapExprComponents.rend();
928
929 assert(EI != EE && "Invalid map expression!");
930
931 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
932 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
933
934 ++EI;
935 if (EI == EE)
936 return false;
937
938 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
939 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
940 isa<MemberExpr>(EI->getAssociatedExpression())) {
941 IsVariableAssociatedWithSection = true;
942 // There is nothing more we need to know about this variable.
943 return true;
944 }
945
946 // Keep looking for more map info.
947 return false;
948 });
949
950 if (IsVariableUsedInMapClause) {
951 // If variable is identified in a map clause it is always captured by
952 // reference except if it is a pointer that is dereferenced somehow.
953 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
954 } else {
955 // By default, all the data that has a scalar type is mapped by copy.
956 IsByRef = !Ty->isScalarType();
957 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000958 }
959
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000960 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
961 IsByRef = !DSAStack->hasExplicitDSA(
962 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
963 Level, /*NotLastprivate=*/true);
964 }
965
Samuel Antao86ace552016-04-27 22:40:57 +0000966 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000967 // and alignment, because the runtime library only deals with uintptr types.
968 // If it does not fit the uintptr size, we need to pass the data by reference
969 // instead.
970 if (!IsByRef &&
971 (Ctx.getTypeSizeInChars(Ty) >
972 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000973 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000974 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000975 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +0000976
977 return IsByRef;
978}
979
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000980unsigned Sema::getOpenMPNestingLevel() const {
981 assert(getLangOpts().OpenMP);
982 return DSAStack->getNestingLevel();
983}
984
Alexey Bataev90c228f2016-02-08 09:29:13 +0000985VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +0000986 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +0000988
989 // If we are attempting to capture a global variable in a directive with
990 // 'target' we return true so that this global is also mapped to the device.
991 //
992 // FIXME: If the declaration is enclosed in a 'declare target' directive,
993 // then it should not be captured. Therefore, an extra check has to be
994 // inserted here once support for 'declare target' is added.
995 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000996 auto *VD = dyn_cast<VarDecl>(D);
997 if (VD && !VD->hasLocalStorage()) {
Samuel Antao4be30e92015-10-02 17:14:03 +0000998 if (DSAStack->getCurrentDirective() == OMPD_target &&
Alexey Bataev90c228f2016-02-08 09:29:13 +0000999 !DSAStack->isClauseParsingMode())
1000 return VD;
Samuel Antaof0d79752016-05-27 15:21:27 +00001001 if (DSAStack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001002 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1003 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001004 return isOpenMPTargetExecutionDirective(K);
Samuel Antao4be30e92015-10-02 17:14:03 +00001005 },
Alexey Bataev90c228f2016-02-08 09:29:13 +00001006 false))
1007 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001008 }
1009
Alexey Bataev48977c32015-08-04 08:10:48 +00001010 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1011 (!DSAStack->isClauseParsingMode() ||
1012 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001013 auto &&Info = DSAStack->isLoopControlVariable(D);
1014 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001015 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001016 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001017 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001018 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001019 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001020 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001021 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001022 DVarPrivate = DSAStack->hasDSA(
1023 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1024 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001025 if (DVarPrivate.CKind != OMPC_unknown)
1026 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001027 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001028 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001029}
1030
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001031bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001032 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1033 return DSAStack->hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001034 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
Alexey Bataevaac108a2015-06-23 04:51:00 +00001035}
1036
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001038 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1039 // Return true if the current level is no longer enclosed in a target region.
1040
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 auto *VD = dyn_cast<VarDecl>(D);
1042 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001043 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1044 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001045}
1046
Alexey Bataeved09d242014-05-28 05:53:51 +00001047void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001048
1049void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1050 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001051 Scope *CurScope, SourceLocation Loc) {
1052 DSAStack->push(DKind, DirName, CurScope, Loc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001053 PushExpressionEvaluationContext(PotentiallyEvaluated);
1054}
1055
Alexey Bataevaac108a2015-06-23 04:51:00 +00001056void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1057 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001058}
1059
Alexey Bataevaac108a2015-06-23 04:51:00 +00001060void Sema::EndOpenMPClause() {
1061 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001062}
1063
Alexey Bataev758e55e2013-09-06 18:03:48 +00001064void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001065 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1066 // A variable of class type (or array thereof) that appears in a lastprivate
1067 // clause requires an accessible, unambiguous default constructor for the
1068 // class type, unless the list item is also specified in a firstprivate
1069 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001070 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001071 for (auto *C : D->clauses()) {
1072 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1073 SmallVector<Expr *, 8> PrivateCopies;
1074 for (auto *DE : Clause->varlists()) {
1075 if (DE->isValueDependent() || DE->isTypeDependent()) {
1076 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001077 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001078 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001079 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001080 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1081 QualType Type = VD->getType().getNonReferenceType();
1082 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001083 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001084 // Generate helper private variable and initialize it with the
1085 // default value. The address of the original variable is replaced
1086 // by the address of the new private variable in CodeGen. This new
1087 // variable is not added to IdResolver, so the code in the OpenMP
1088 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001089 auto *VDPrivate = buildVarDecl(
1090 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001091 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001092 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001093 if (VDPrivate->isInvalidDecl())
1094 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001095 PrivateCopies.push_back(buildDeclRefExpr(
1096 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001097 } else {
1098 // The variable is also a firstprivate, so initialization sequence
1099 // for private copy is generated already.
1100 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001101 }
1102 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001103 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001104 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001105 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001106 }
1107 }
1108 }
1109
Alexey Bataev758e55e2013-09-06 18:03:48 +00001110 DSAStack->pop();
1111 DiscardCleanupsInEvaluationContext();
1112 PopExpressionEvaluationContext();
1113}
1114
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001115static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1116 Expr *NumIterations, Sema &SemaRef,
1117 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001118
Alexey Bataeva769e072013-03-22 06:34:35 +00001119namespace {
1120
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001121class VarDeclFilterCCC : public CorrectionCandidateCallback {
1122private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001123 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001124
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001125public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001126 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001127 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001128 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001129 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001130 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001131 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1132 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001133 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001134 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001135 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001136};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001137
1138class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1139private:
1140 Sema &SemaRef;
1141
1142public:
1143 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1144 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1145 NamedDecl *ND = Candidate.getCorrectionDecl();
1146 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
1147 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1148 SemaRef.getCurScope());
1149 }
1150 return false;
1151 }
1152};
1153
Alexey Bataeved09d242014-05-28 05:53:51 +00001154} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001155
1156ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1157 CXXScopeSpec &ScopeSpec,
1158 const DeclarationNameInfo &Id) {
1159 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1160 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1161
1162 if (Lookup.isAmbiguous())
1163 return ExprError();
1164
1165 VarDecl *VD;
1166 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001167 if (TypoCorrection Corrected = CorrectTypo(
1168 Id, LookupOrdinaryName, CurScope, nullptr,
1169 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001170 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001171 PDiag(Lookup.empty()
1172 ? diag::err_undeclared_var_use_suggest
1173 : diag::err_omp_expected_var_arg_suggest)
1174 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001175 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001176 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001177 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1178 : diag::err_omp_expected_var_arg)
1179 << Id.getName();
1180 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001181 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001182 } else {
1183 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001184 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001185 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1186 return ExprError();
1187 }
1188 }
1189 Lookup.suppressDiagnostics();
1190
1191 // OpenMP [2.9.2, Syntax, C/C++]
1192 // Variables must be file-scope, namespace-scope, or static block-scope.
1193 if (!VD->hasGlobalStorage()) {
1194 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001195 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1196 bool IsDecl =
1197 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001198 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001199 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1200 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001201 return ExprError();
1202 }
1203
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001204 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1205 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001206 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1207 // A threadprivate directive for file-scope variables must appear outside
1208 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001209 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1210 !getCurLexicalContext()->isTranslationUnit()) {
1211 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001212 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1213 bool IsDecl =
1214 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1215 Diag(VD->getLocation(),
1216 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1217 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001218 return ExprError();
1219 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001220 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1221 // A threadprivate directive for static class member variables must appear
1222 // in the class definition, in the same scope in which the member
1223 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001224 if (CanonicalVD->isStaticDataMember() &&
1225 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1226 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001227 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1228 bool IsDecl =
1229 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1230 Diag(VD->getLocation(),
1231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1232 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001233 return ExprError();
1234 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001235 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1236 // A threadprivate directive for namespace-scope variables must appear
1237 // outside any definition or declaration other than the namespace
1238 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001239 if (CanonicalVD->getDeclContext()->isNamespace() &&
1240 (!getCurLexicalContext()->isFileContext() ||
1241 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1242 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001243 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1244 bool IsDecl =
1245 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1246 Diag(VD->getLocation(),
1247 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1248 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001249 return ExprError();
1250 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001251 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1252 // A threadprivate directive for static block-scope variables must appear
1253 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001254 if (CanonicalVD->isStaticLocal() && CurScope &&
1255 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001256 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001257 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1258 bool IsDecl =
1259 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1260 Diag(VD->getLocation(),
1261 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1262 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001263 return ExprError();
1264 }
1265
1266 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1267 // A threadprivate directive must lexically precede all references to any
1268 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001269 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001270 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001271 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001272 return ExprError();
1273 }
1274
1275 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001276 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1277 SourceLocation(), VD,
1278 /*RefersToEnclosingVariableOrCapture=*/false,
1279 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001280}
1281
Alexey Bataeved09d242014-05-28 05:53:51 +00001282Sema::DeclGroupPtrTy
1283Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1284 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001285 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001286 CurContext->addDecl(D);
1287 return DeclGroupPtrTy::make(DeclGroupRef(D));
1288 }
David Blaikie0403cb12016-01-15 23:43:25 +00001289 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001290}
1291
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001292namespace {
1293class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1294 Sema &SemaRef;
1295
1296public:
1297 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001298 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001299 if (VD->hasLocalStorage()) {
1300 SemaRef.Diag(E->getLocStart(),
1301 diag::err_omp_local_var_in_threadprivate_init)
1302 << E->getSourceRange();
1303 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1304 << VD << VD->getSourceRange();
1305 return true;
1306 }
1307 }
1308 return false;
1309 }
1310 bool VisitStmt(const Stmt *S) {
1311 for (auto Child : S->children()) {
1312 if (Child && Visit(Child))
1313 return true;
1314 }
1315 return false;
1316 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001317 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001318};
1319} // namespace
1320
Alexey Bataeved09d242014-05-28 05:53:51 +00001321OMPThreadPrivateDecl *
1322Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001323 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001324 for (auto &RefExpr : VarList) {
1325 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001326 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1327 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001328
Alexey Bataev376b4a42016-02-09 09:41:09 +00001329 // Mark variable as used.
1330 VD->setReferenced();
1331 VD->markUsed(Context);
1332
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001333 QualType QType = VD->getType();
1334 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1335 // It will be analyzed later.
1336 Vars.push_back(DE);
1337 continue;
1338 }
1339
Alexey Bataeva769e072013-03-22 06:34:35 +00001340 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1341 // A threadprivate variable must not have an incomplete type.
1342 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001343 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001344 continue;
1345 }
1346
1347 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1348 // A threadprivate variable must not have a reference type.
1349 if (VD->getType()->isReferenceType()) {
1350 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001351 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1352 bool IsDecl =
1353 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1354 Diag(VD->getLocation(),
1355 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1356 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001357 continue;
1358 }
1359
Samuel Antaof8b50122015-07-13 22:54:53 +00001360 // Check if this is a TLS variable. If TLS is not being supported, produce
1361 // the corresponding diagnostic.
1362 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1363 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1364 getLangOpts().OpenMPUseTLS &&
1365 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001366 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1367 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001368 Diag(ILoc, diag::err_omp_var_thread_local)
1369 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001370 bool IsDecl =
1371 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1372 Diag(VD->getLocation(),
1373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1374 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001375 continue;
1376 }
1377
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001378 // Check if initial value of threadprivate variable reference variable with
1379 // local storage (it is not supported by runtime).
1380 if (auto Init = VD->getAnyInitializer()) {
1381 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001382 if (Checker.Visit(Init))
1383 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001384 }
1385
Alexey Bataeved09d242014-05-28 05:53:51 +00001386 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001387 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001388 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1389 Context, SourceRange(Loc, Loc)));
1390 if (auto *ML = Context.getASTMutationListener())
1391 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001392 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001393 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001394 if (!Vars.empty()) {
1395 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1396 Vars);
1397 D->setAccess(AS_public);
1398 }
1399 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001400}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001401
Alexey Bataev7ff55242014-06-19 09:13:45 +00001402static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001403 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001404 bool IsLoopIterVar = false) {
1405 if (DVar.RefExpr) {
1406 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1407 << getOpenMPClauseName(DVar.CKind);
1408 return;
1409 }
1410 enum {
1411 PDSA_StaticMemberShared,
1412 PDSA_StaticLocalVarShared,
1413 PDSA_LoopIterVarPrivate,
1414 PDSA_LoopIterVarLinear,
1415 PDSA_LoopIterVarLastprivate,
1416 PDSA_ConstVarShared,
1417 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001418 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001419 PDSA_LocalVarPrivate,
1420 PDSA_Implicit
1421 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001422 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001423 auto ReportLoc = D->getLocation();
1424 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001425 if (IsLoopIterVar) {
1426 if (DVar.CKind == OMPC_private)
1427 Reason = PDSA_LoopIterVarPrivate;
1428 else if (DVar.CKind == OMPC_lastprivate)
1429 Reason = PDSA_LoopIterVarLastprivate;
1430 else
1431 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001432 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1433 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001434 Reason = PDSA_TaskVarFirstprivate;
1435 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001437 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001438 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001439 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001440 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001441 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001442 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001443 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001445 ReportHint = true;
1446 Reason = PDSA_LocalVarPrivate;
1447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001448 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001450 << Reason << ReportHint
1451 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1452 } else if (DVar.ImplicitDSALoc.isValid()) {
1453 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1454 << getOpenMPClauseName(DVar.CKind);
1455 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001456}
1457
Alexey Bataev758e55e2013-09-06 18:03:48 +00001458namespace {
1459class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1460 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001461 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001462 bool ErrorFound;
1463 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001464 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001465 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataeved09d242014-05-28 05:53:51 +00001466
Alexey Bataev758e55e2013-09-06 18:03:48 +00001467public:
1468 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001469 if (E->isTypeDependent() || E->isValueDependent() ||
1470 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1471 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001472 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001473 // Skip internally declared variables.
Alexey Bataeved09d242014-05-28 05:53:51 +00001474 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
1475 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001476
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001477 auto DVar = Stack->getTopDSA(VD, false);
1478 // Check if the variable has explicit DSA set and stop analysis if it so.
David Majnemer9d168222016-08-05 17:44:54 +00001479 if (DVar.RefExpr)
1480 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001482 auto ELoc = E->getExprLoc();
1483 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001484 // The default(none) clause requires that each variable that is referenced
1485 // in the construct, and does not have a predetermined data-sharing
1486 // attribute, must have its data-sharing attribute explicitly determined
1487 // by being listed in a data-sharing attribute clause.
1488 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001489 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001490 VarsWithInheritedDSA.count(VD) == 0) {
1491 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001492 return;
1493 }
1494
1495 // OpenMP [2.9.3.6, Restrictions, p.2]
1496 // A list item that appears in a reduction clause of the innermost
1497 // enclosing worksharing or parallel construct may not be accessed in an
1498 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001499 DVar = Stack->hasInnermostDSA(
1500 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1501 [](OpenMPDirectiveKind K) -> bool {
1502 return isOpenMPParallelDirective(K) ||
1503 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1504 },
1505 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001506 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001507 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001508 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1509 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001510 return;
1511 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001512
1513 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001515 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1516 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001517 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001518 }
1519 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001520 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001521 if (E->isTypeDependent() || E->isValueDependent() ||
1522 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1523 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001524 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
1525 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
1526 auto DVar = Stack->getTopDSA(FD, false);
1527 // Check if the variable has explicit DSA set and stop analysis if it
1528 // so.
1529 if (DVar.RefExpr)
1530 return;
1531
1532 auto ELoc = E->getExprLoc();
1533 auto DKind = Stack->getCurrentDirective();
1534 // OpenMP [2.9.3.6, Restrictions, p.2]
1535 // A list item that appears in a reduction clause of the innermost
1536 // enclosing worksharing or parallel construct may not be accessed in
Alexey Bataevd985eda2016-02-10 11:29:16 +00001537 // an explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001538 DVar = Stack->hasInnermostDSA(
1539 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1540 [](OpenMPDirectiveKind K) -> bool {
1541 return isOpenMPParallelDirective(K) ||
1542 isOpenMPWorksharingDirective(K) ||
1543 isOpenMPTeamsDirective(K);
1544 },
1545 false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001546 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001547 ErrorFound = true;
1548 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1549 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
1550 return;
1551 }
1552
1553 // Define implicit data-sharing attributes for task.
1554 DVar = Stack->getImplicitDSA(FD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1556 !Stack->isLoopControlVariable(FD).first)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001557 ImplicitFirstprivate.push_back(E);
1558 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00001559 } else
1560 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001561 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001562 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001563 for (auto *C : S->clauses()) {
1564 // Skip analysis of arguments of implicitly defined firstprivate clause
1565 // for task directives.
1566 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
1567 for (auto *CC : C->children()) {
1568 if (CC)
1569 Visit(CC);
1570 }
1571 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001572 }
1573 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001574 for (auto *C : S->children()) {
1575 if (C && !isa<OMPExecutableDirective>(C))
1576 Visit(C);
1577 }
Alexey Bataeved09d242014-05-28 05:53:51 +00001578 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001579
1580 bool isErrorFound() { return ErrorFound; }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001581 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00001583 return VarsWithInheritedDSA;
1584 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001585
Alexey Bataev7ff55242014-06-19 09:13:45 +00001586 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
1587 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00001588};
Alexey Bataeved09d242014-05-28 05:53:51 +00001589} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00001590
Alexey Bataevbae9a792014-06-27 10:37:06 +00001591void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001592 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00001593 case OMPD_parallel:
1594 case OMPD_parallel_for:
1595 case OMPD_parallel_for_simd:
1596 case OMPD_parallel_sections:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001597 case OMPD_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001598 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001599 QualType KmpInt32PtrTy =
1600 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001601 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001602 std::make_pair(".global_tid.", KmpInt32PtrTy),
1603 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1604 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001605 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001606 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1607 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001608 break;
1609 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001610 case OMPD_target_teams:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001611 case OMPD_target_parallel: {
1612 Sema::CapturedParamNameType ParamsTarget[] = {
1613 std::make_pair(StringRef(), QualType()) // __context with shared vars
1614 };
1615 // Start a captured region for 'target' with no implicit parameters.
1616 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1617 ParamsTarget);
1618 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1619 QualType KmpInt32PtrTy =
1620 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001621 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001622 std::make_pair(".global_tid.", KmpInt32PtrTy),
1623 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1624 std::make_pair(StringRef(), QualType()) // __context with shared vars
1625 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001626 // Start a captured region for 'teams' or 'parallel'. Both regions have
1627 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001628 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00001629 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001630 break;
1631 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001632 case OMPD_simd:
1633 case OMPD_for:
1634 case OMPD_for_simd:
1635 case OMPD_sections:
1636 case OMPD_section:
1637 case OMPD_single:
1638 case OMPD_master:
1639 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001640 case OMPD_taskgroup:
1641 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001642 case OMPD_ordered:
1643 case OMPD_atomic:
1644 case OMPD_target_data:
1645 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001646 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001647 case OMPD_target_parallel_for_simd:
1648 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001649 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001650 std::make_pair(StringRef(), QualType()) // __context with shared vars
1651 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001652 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1653 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001654 break;
1655 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001656 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001657 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001658 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1659 FunctionProtoType::ExtProtoInfo EPI;
1660 EPI.Variadic = true;
1661 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001662 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001663 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001664 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1665 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1666 std::make_pair(".copy_fn.",
1667 Context.getPointerType(CopyFnType).withConst()),
1668 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001669 std::make_pair(StringRef(), QualType()) // __context with shared vars
1670 };
1671 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1672 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001673 // Mark this captured region as inlined, because we don't use outlined
1674 // function directly.
1675 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1676 AlwaysInlineAttr::CreateImplicit(
1677 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001678 break;
1679 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001680 case OMPD_taskloop:
1681 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001682 QualType KmpInt32Ty =
1683 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1684 QualType KmpUInt64Ty =
1685 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1686 QualType KmpInt64Ty =
1687 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1688 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1689 FunctionProtoType::ExtProtoInfo EPI;
1690 EPI.Variadic = true;
1691 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001692 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001693 std::make_pair(".global_tid.", KmpInt32Ty),
1694 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1695 std::make_pair(".privates.",
1696 Context.VoidPtrTy.withConst().withRestrict()),
1697 std::make_pair(
1698 ".copy_fn.",
1699 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1700 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1701 std::make_pair(".lb.", KmpUInt64Ty),
1702 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1703 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001704 std::make_pair(StringRef(), QualType()) // __context with shared vars
1705 };
1706 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1707 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001708 // Mark this captured region as inlined, because we don't use outlined
1709 // function directly.
1710 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1711 AlwaysInlineAttr::CreateImplicit(
1712 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001713 break;
1714 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001715 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001716 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001717 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001718 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001719 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001720 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001721 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001722 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001723 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001724 case OMPD_target_teams_distribute_parallel_for_simd:
1725 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001726 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1727 QualType KmpInt32PtrTy =
1728 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1729 Sema::CapturedParamNameType Params[] = {
1730 std::make_pair(".global_tid.", KmpInt32PtrTy),
1731 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1732 std::make_pair(".previous.lb.", Context.getSizeType()),
1733 std::make_pair(".previous.ub.", Context.getSizeType()),
1734 std::make_pair(StringRef(), QualType()) // __context with shared vars
1735 };
1736 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1737 Params);
1738 break;
1739 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001740 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001741 case OMPD_taskyield:
1742 case OMPD_barrier:
1743 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001744 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001745 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001746 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001747 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001748 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001749 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001750 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001751 case OMPD_declare_target:
1752 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001753 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001754 llvm_unreachable("OpenMP Directive is not allowed");
1755 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001756 llvm_unreachable("Unknown OpenMP directive");
1757 }
1758}
1759
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001760int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1761 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1762 getOpenMPCaptureRegions(CaptureRegions, DKind);
1763 return CaptureRegions.size();
1764}
1765
Alexey Bataev3392d762016-02-16 11:18:12 +00001766static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001767 Expr *CaptureExpr, bool WithInit,
1768 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001769 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001770 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001771 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001772 QualType Ty = Init->getType();
1773 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1774 if (S.getLangOpts().CPlusPlus)
1775 Ty = C.getLValueReferenceType(Ty);
1776 else {
1777 Ty = C.getPointerType(Ty);
1778 ExprResult Res =
1779 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1780 if (!Res.isUsable())
1781 return nullptr;
1782 Init = Res.get();
1783 }
Alexey Bataev61205072016-03-02 04:57:40 +00001784 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001785 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001786 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1787 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001788 if (!WithInit)
1789 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001790 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001791 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001792 return CED;
1793}
1794
Alexey Bataev61205072016-03-02 04:57:40 +00001795static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1796 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001797 OMPCapturedExprDecl *CD;
1798 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1799 CD = cast<OMPCapturedExprDecl>(VD);
1800 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001801 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1802 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001803 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001804 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001805}
1806
Alexey Bataev5a3af132016-03-29 08:58:54 +00001807static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1808 if (!Ref) {
1809 auto *CD =
1810 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1811 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1812 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1813 CaptureExpr->getExprLoc());
1814 }
1815 ExprResult Res = Ref;
1816 if (!S.getLangOpts().CPlusPlus &&
1817 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1818 Ref->getType()->isPointerType())
1819 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1820 if (!Res.isUsable())
1821 return ExprError();
1822 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001823}
1824
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001825namespace {
1826// OpenMP directives parsed in this section are represented as a
1827// CapturedStatement with an associated statement. If a syntax error
1828// is detected during the parsing of the associated statement, the
1829// compiler must abort processing and close the CapturedStatement.
1830//
1831// Combined directives such as 'target parallel' have more than one
1832// nested CapturedStatements. This RAII ensures that we unwind out
1833// of all the nested CapturedStatements when an error is found.
1834class CaptureRegionUnwinderRAII {
1835private:
1836 Sema &S;
1837 bool &ErrorFound;
1838 OpenMPDirectiveKind DKind;
1839
1840public:
1841 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1842 OpenMPDirectiveKind DKind)
1843 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1844 ~CaptureRegionUnwinderRAII() {
1845 if (ErrorFound) {
1846 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1847 while (--ThisCaptureLevel >= 0)
1848 S.ActOnCapturedRegionError();
1849 }
1850 }
1851};
1852} // namespace
1853
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001854StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1855 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001856 bool ErrorFound = false;
1857 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1858 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001859 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001860 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001861 return StmtError();
1862 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001863
1864 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001865 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001866 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001867 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001868 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001869 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001870 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001871 Clause->getClauseKind() == OMPC_copyprivate ||
1872 (getLangOpts().OpenMPUseTLS &&
1873 getASTContext().getTargetInfo().isTLSSupported() &&
1874 Clause->getClauseKind() == OMPC_copyin)) {
1875 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001876 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001877 for (auto *VarRef : Clause->children()) {
1878 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001879 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001880 }
1881 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001882 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001883 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001884 if (auto *C = OMPClauseWithPreInit::get(Clause))
1885 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001886 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1887 if (auto *E = C->getPostUpdateExpr())
1888 MarkDeclarationsReferencedInExpr(E);
1889 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001890 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001891 if (Clause->getClauseKind() == OMPC_schedule)
1892 SC = cast<OMPScheduleClause>(Clause);
1893 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001894 OC = cast<OMPOrderedClause>(Clause);
1895 else if (Clause->getClauseKind() == OMPC_linear)
1896 LCs.push_back(cast<OMPLinearClause>(Clause));
1897 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001898 // OpenMP, 2.7.1 Loop Construct, Restrictions
1899 // The nonmonotonic modifier cannot be specified if an ordered clause is
1900 // specified.
1901 if (SC &&
1902 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1903 SC->getSecondScheduleModifier() ==
1904 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1905 OC) {
1906 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1907 ? SC->getFirstScheduleModifierLoc()
1908 : SC->getSecondScheduleModifierLoc(),
1909 diag::err_omp_schedule_nonmonotonic_ordered)
1910 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1911 ErrorFound = true;
1912 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001913 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1914 for (auto *C : LCs) {
1915 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1916 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1917 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001918 ErrorFound = true;
1919 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001920 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1921 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1922 OC->getNumForLoops()) {
1923 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1924 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1925 ErrorFound = true;
1926 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001927 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001928 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001929 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001930 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001931 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1932 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
1933 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
1934 // Mark all variables in private list clauses as used in inner region.
1935 // Required for proper codegen of combined directives.
1936 // TODO: add processing for other clauses.
1937 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1938 for (auto *C : PICs) {
1939 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
1940 // Find the particular capture region for the clause if the
1941 // directive is a combined one with multiple capture regions.
1942 // If the directive is not a combined one, the capture region
1943 // associated with the clause is OMPD_unknown and is generated
1944 // only once.
1945 if (CaptureRegion == ThisCaptureRegion ||
1946 CaptureRegion == OMPD_unknown) {
1947 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1948 for (auto *D : DS->decls())
1949 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1950 }
1951 }
1952 }
1953 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001954 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001955 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001956 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001957}
1958
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001959static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1960 OpenMPDirectiveKind CurrentRegion,
1961 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001962 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001963 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001964 if (Stack->getCurScope()) {
1965 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001966 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001967 bool NestingProhibited = false;
1968 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001969 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001970 enum {
1971 NoRecommend,
1972 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001973 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001974 ShouldBeInTargetRegion,
1975 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001976 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001977 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001978 // OpenMP [2.16, Nesting of Regions]
1979 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001980 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001981 // An ordered construct with the simd clause is the only OpenMP
1982 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001983 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001984 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1985 // message.
1986 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1987 ? diag::err_omp_prohibited_region_simd
1988 : diag::warn_omp_nesting_simd);
1989 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001990 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001991 if (ParentRegion == OMPD_atomic) {
1992 // OpenMP [2.16, Nesting of Regions]
1993 // OpenMP constructs may not be nested inside an atomic region.
1994 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1995 return true;
1996 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001997 if (CurrentRegion == OMPD_section) {
1998 // OpenMP [2.7.2, sections Construct, Restrictions]
1999 // Orphaned section directives are prohibited. That is, the section
2000 // directives must appear within the sections construct and must not be
2001 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002002 if (ParentRegion != OMPD_sections &&
2003 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002004 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2005 << (ParentRegion != OMPD_unknown)
2006 << getOpenMPDirectiveName(ParentRegion);
2007 return true;
2008 }
2009 return false;
2010 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002011 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002012 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002013 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002014 if (ParentRegion == OMPD_unknown &&
2015 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002016 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002017 if (CurrentRegion == OMPD_cancellation_point ||
2018 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002019 // OpenMP [2.16, Nesting of Regions]
2020 // A cancellation point construct for which construct-type-clause is
2021 // taskgroup must be nested inside a task construct. A cancellation
2022 // point construct for which construct-type-clause is not taskgroup must
2023 // be closely nested inside an OpenMP construct that matches the type
2024 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002025 // A cancel construct for which construct-type-clause is taskgroup must be
2026 // nested inside a task construct. A cancel construct for which
2027 // construct-type-clause is not taskgroup must be closely nested inside an
2028 // OpenMP construct that matches the type specified in
2029 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002030 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002031 !((CancelRegion == OMPD_parallel &&
2032 (ParentRegion == OMPD_parallel ||
2033 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002034 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002035 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2036 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002037 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2038 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002039 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2040 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002041 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002042 // OpenMP [2.16, Nesting of Regions]
2043 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002044 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002045 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002046 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002047 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2048 // OpenMP [2.16, Nesting of Regions]
2049 // A critical region may not be nested (closely or otherwise) inside a
2050 // critical region with the same name. Note that this restriction is not
2051 // sufficient to prevent deadlock.
2052 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002053 bool DeadLock = Stack->hasDirective(
2054 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2055 const DeclarationNameInfo &DNI,
2056 SourceLocation Loc) -> bool {
2057 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2058 PreviousCriticalLoc = Loc;
2059 return true;
2060 } else
2061 return false;
2062 },
2063 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002064 if (DeadLock) {
2065 SemaRef.Diag(StartLoc,
2066 diag::err_omp_prohibited_region_critical_same_name)
2067 << CurrentName.getName();
2068 if (PreviousCriticalLoc.isValid())
2069 SemaRef.Diag(PreviousCriticalLoc,
2070 diag::note_omp_previous_critical_region);
2071 return true;
2072 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002073 } else if (CurrentRegion == OMPD_barrier) {
2074 // OpenMP [2.16, Nesting of Regions]
2075 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002076 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002077 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2078 isOpenMPTaskingDirective(ParentRegion) ||
2079 ParentRegion == OMPD_master ||
2080 ParentRegion == OMPD_critical ||
2081 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002082 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002083 !isOpenMPParallelDirective(CurrentRegion) &&
2084 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002085 // OpenMP [2.16, Nesting of Regions]
2086 // A worksharing region may not be closely nested inside a worksharing,
2087 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002088 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2089 isOpenMPTaskingDirective(ParentRegion) ||
2090 ParentRegion == OMPD_master ||
2091 ParentRegion == OMPD_critical ||
2092 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002093 Recommend = ShouldBeInParallelRegion;
2094 } else if (CurrentRegion == OMPD_ordered) {
2095 // OpenMP [2.16, Nesting of Regions]
2096 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002097 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002098 // An ordered region must be closely nested inside a loop region (or
2099 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002100 // OpenMP [2.8.1,simd Construct, Restrictions]
2101 // An ordered construct with the simd clause is the only OpenMP construct
2102 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002103 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002104 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002105 !(isOpenMPSimdDirective(ParentRegion) ||
2106 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002107 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002108 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002109 // OpenMP [2.16, Nesting of Regions]
2110 // If specified, a teams construct must be contained within a target
2111 // construct.
2112 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002113 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002114 Recommend = ShouldBeInTargetRegion;
2115 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2116 }
Kelvin Libf594a52016-12-17 05:48:59 +00002117 if (!NestingProhibited &&
2118 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2119 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2120 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002121 // OpenMP [2.16, Nesting of Regions]
2122 // distribute, parallel, parallel sections, parallel workshare, and the
2123 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2124 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002125 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2126 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002127 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002128 }
David Majnemer9d168222016-08-05 17:44:54 +00002129 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002130 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002131 // OpenMP 4.5 [2.17 Nesting of Regions]
2132 // The region associated with the distribute construct must be strictly
2133 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002134 NestingProhibited =
2135 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002136 Recommend = ShouldBeInTeamsRegion;
2137 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002138 if (!NestingProhibited &&
2139 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2140 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2141 // OpenMP 4.5 [2.17 Nesting of Regions]
2142 // If a target, target update, target data, target enter data, or
2143 // target exit data construct is encountered during execution of a
2144 // target region, the behavior is unspecified.
2145 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002146 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2147 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002148 if (isOpenMPTargetExecutionDirective(K)) {
2149 OffendingRegion = K;
2150 return true;
2151 } else
2152 return false;
2153 },
2154 false /* don't skip top directive */);
2155 CloseNesting = false;
2156 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002157 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002158 if (OrphanSeen) {
2159 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2160 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2161 } else {
2162 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2163 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2164 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2165 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002166 return true;
2167 }
2168 }
2169 return false;
2170}
2171
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002172static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2173 ArrayRef<OMPClause *> Clauses,
2174 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2175 bool ErrorFound = false;
2176 unsigned NamedModifiersNumber = 0;
2177 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2178 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002179 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002180 for (const auto *C : Clauses) {
2181 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2182 // At most one if clause without a directive-name-modifier can appear on
2183 // the directive.
2184 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2185 if (FoundNameModifiers[CurNM]) {
2186 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2187 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2188 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2189 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002190 } else if (CurNM != OMPD_unknown) {
2191 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002192 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002193 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002194 FoundNameModifiers[CurNM] = IC;
2195 if (CurNM == OMPD_unknown)
2196 continue;
2197 // Check if the specified name modifier is allowed for the current
2198 // directive.
2199 // At most one if clause with the particular directive-name-modifier can
2200 // appear on the directive.
2201 bool MatchFound = false;
2202 for (auto NM : AllowedNameModifiers) {
2203 if (CurNM == NM) {
2204 MatchFound = true;
2205 break;
2206 }
2207 }
2208 if (!MatchFound) {
2209 S.Diag(IC->getNameModifierLoc(),
2210 diag::err_omp_wrong_if_directive_name_modifier)
2211 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2212 ErrorFound = true;
2213 }
2214 }
2215 }
2216 // If any if clause on the directive includes a directive-name-modifier then
2217 // all if clauses on the directive must include a directive-name-modifier.
2218 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2219 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2220 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2221 diag::err_omp_no_more_if_clause);
2222 } else {
2223 std::string Values;
2224 std::string Sep(", ");
2225 unsigned AllowedCnt = 0;
2226 unsigned TotalAllowedNum =
2227 AllowedNameModifiers.size() - NamedModifiersNumber;
2228 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2229 ++Cnt) {
2230 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2231 if (!FoundNameModifiers[NM]) {
2232 Values += "'";
2233 Values += getOpenMPDirectiveName(NM);
2234 Values += "'";
2235 if (AllowedCnt + 2 == TotalAllowedNum)
2236 Values += " or ";
2237 else if (AllowedCnt + 1 != TotalAllowedNum)
2238 Values += Sep;
2239 ++AllowedCnt;
2240 }
2241 }
2242 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2243 diag::err_omp_unnamed_if_clause)
2244 << (TotalAllowedNum > 1) << Values;
2245 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002246 for (auto Loc : NameModifierLoc) {
2247 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2248 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002249 ErrorFound = true;
2250 }
2251 return ErrorFound;
2252}
2253
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002254StmtResult Sema::ActOnOpenMPExecutableDirective(
2255 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2256 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2257 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002258 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002259 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2260 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002261 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002262
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002263 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002264 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002265 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002266 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002267 if (AStmt) {
2268 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2269
2270 // Check default data sharing attributes for referenced variables.
2271 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002272 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2273 Stmt *S = AStmt;
2274 while (--ThisCaptureLevel >= 0)
2275 S = cast<CapturedStmt>(S)->getCapturedStmt();
2276 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002277 if (DSAChecker.isErrorFound())
2278 return StmtError();
2279 // Generate list of implicitly defined firstprivate variables.
2280 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002281
2282 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2283 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2284 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2285 SourceLocation(), SourceLocation())) {
2286 ClausesWithImplicit.push_back(Implicit);
2287 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2288 DSAChecker.getImplicitFirstprivate().size();
2289 } else
2290 ErrorFound = true;
2291 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002292 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002293
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002294 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002295 switch (Kind) {
2296 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002297 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2298 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002299 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002300 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002301 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002302 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2303 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002304 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002305 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002306 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2307 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002308 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002309 case OMPD_for_simd:
2310 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2311 EndLoc, VarsWithInheritedDSA);
2312 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002313 case OMPD_sections:
2314 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2315 EndLoc);
2316 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002317 case OMPD_section:
2318 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002319 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002320 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2321 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002322 case OMPD_single:
2323 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2324 EndLoc);
2325 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002326 case OMPD_master:
2327 assert(ClausesWithImplicit.empty() &&
2328 "No clauses are allowed for 'omp master' directive");
2329 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2330 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002331 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002332 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2333 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002334 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002335 case OMPD_parallel_for:
2336 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2337 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002338 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002339 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002340 case OMPD_parallel_for_simd:
2341 Res = ActOnOpenMPParallelForSimdDirective(
2342 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002343 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002344 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002345 case OMPD_parallel_sections:
2346 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2347 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002348 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002349 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002350 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002351 Res =
2352 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002353 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002354 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002355 case OMPD_taskyield:
2356 assert(ClausesWithImplicit.empty() &&
2357 "No clauses are allowed for 'omp taskyield' directive");
2358 assert(AStmt == nullptr &&
2359 "No associated statement allowed for 'omp taskyield' directive");
2360 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2361 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002362 case OMPD_barrier:
2363 assert(ClausesWithImplicit.empty() &&
2364 "No clauses are allowed for 'omp barrier' directive");
2365 assert(AStmt == nullptr &&
2366 "No associated statement allowed for 'omp barrier' directive");
2367 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2368 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002369 case OMPD_taskwait:
2370 assert(ClausesWithImplicit.empty() &&
2371 "No clauses are allowed for 'omp taskwait' directive");
2372 assert(AStmt == nullptr &&
2373 "No associated statement allowed for 'omp taskwait' directive");
2374 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2375 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002376 case OMPD_taskgroup:
2377 assert(ClausesWithImplicit.empty() &&
2378 "No clauses are allowed for 'omp taskgroup' directive");
2379 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2380 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002381 case OMPD_flush:
2382 assert(AStmt == nullptr &&
2383 "No associated statement allowed for 'omp flush' directive");
2384 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2385 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002386 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002387 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2388 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002389 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002390 case OMPD_atomic:
2391 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2392 EndLoc);
2393 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002394 case OMPD_teams:
2395 Res =
2396 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2397 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002398 case OMPD_target:
2399 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2400 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002401 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002402 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002403 case OMPD_target_parallel:
2404 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2405 StartLoc, EndLoc);
2406 AllowedNameModifiers.push_back(OMPD_target);
2407 AllowedNameModifiers.push_back(OMPD_parallel);
2408 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002409 case OMPD_target_parallel_for:
2410 Res = ActOnOpenMPTargetParallelForDirective(
2411 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2412 AllowedNameModifiers.push_back(OMPD_target);
2413 AllowedNameModifiers.push_back(OMPD_parallel);
2414 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002415 case OMPD_cancellation_point:
2416 assert(ClausesWithImplicit.empty() &&
2417 "No clauses are allowed for 'omp cancellation point' directive");
2418 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2419 "cancellation point' directive");
2420 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2421 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002422 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002423 assert(AStmt == nullptr &&
2424 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002425 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2426 CancelRegion);
2427 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002428 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002429 case OMPD_target_data:
2430 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2431 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002432 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002433 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002434 case OMPD_target_enter_data:
2435 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2436 EndLoc);
2437 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2438 break;
Samuel Antao72590762016-01-19 20:04:50 +00002439 case OMPD_target_exit_data:
2440 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2441 EndLoc);
2442 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2443 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002444 case OMPD_taskloop:
2445 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2446 EndLoc, VarsWithInheritedDSA);
2447 AllowedNameModifiers.push_back(OMPD_taskloop);
2448 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002449 case OMPD_taskloop_simd:
2450 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2451 EndLoc, VarsWithInheritedDSA);
2452 AllowedNameModifiers.push_back(OMPD_taskloop);
2453 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002454 case OMPD_distribute:
2455 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2456 EndLoc, VarsWithInheritedDSA);
2457 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002458 case OMPD_target_update:
2459 assert(!AStmt && "Statement is not allowed for target update");
2460 Res =
2461 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2462 AllowedNameModifiers.push_back(OMPD_target_update);
2463 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002464 case OMPD_distribute_parallel_for:
2465 Res = ActOnOpenMPDistributeParallelForDirective(
2466 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2467 AllowedNameModifiers.push_back(OMPD_parallel);
2468 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002469 case OMPD_distribute_parallel_for_simd:
2470 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2472 AllowedNameModifiers.push_back(OMPD_parallel);
2473 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002474 case OMPD_distribute_simd:
2475 Res = ActOnOpenMPDistributeSimdDirective(
2476 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2477 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002478 case OMPD_target_parallel_for_simd:
2479 Res = ActOnOpenMPTargetParallelForSimdDirective(
2480 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2481 AllowedNameModifiers.push_back(OMPD_target);
2482 AllowedNameModifiers.push_back(OMPD_parallel);
2483 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002484 case OMPD_target_simd:
2485 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2486 EndLoc, VarsWithInheritedDSA);
2487 AllowedNameModifiers.push_back(OMPD_target);
2488 break;
Kelvin Li02532872016-08-05 14:37:37 +00002489 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002490 Res = ActOnOpenMPTeamsDistributeDirective(
2491 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002492 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002493 case OMPD_teams_distribute_simd:
2494 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2495 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2496 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002497 case OMPD_teams_distribute_parallel_for_simd:
2498 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2500 AllowedNameModifiers.push_back(OMPD_parallel);
2501 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002502 case OMPD_teams_distribute_parallel_for:
2503 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2504 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2505 AllowedNameModifiers.push_back(OMPD_parallel);
2506 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002507 case OMPD_target_teams:
2508 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2509 EndLoc);
2510 AllowedNameModifiers.push_back(OMPD_target);
2511 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002512 case OMPD_target_teams_distribute:
2513 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2514 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2515 AllowedNameModifiers.push_back(OMPD_target);
2516 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002517 case OMPD_target_teams_distribute_parallel_for:
2518 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2519 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2520 AllowedNameModifiers.push_back(OMPD_target);
2521 AllowedNameModifiers.push_back(OMPD_parallel);
2522 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002523 case OMPD_target_teams_distribute_parallel_for_simd:
2524 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2525 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2526 AllowedNameModifiers.push_back(OMPD_target);
2527 AllowedNameModifiers.push_back(OMPD_parallel);
2528 break;
Kelvin Lida681182017-01-10 18:08:18 +00002529 case OMPD_target_teams_distribute_simd:
2530 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2531 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2532 AllowedNameModifiers.push_back(OMPD_target);
2533 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002534 case OMPD_declare_target:
2535 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002536 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002537 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002538 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002539 llvm_unreachable("OpenMP Directive is not allowed");
2540 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002541 llvm_unreachable("Unknown OpenMP directive");
2542 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002543
Alexey Bataev4acb8592014-07-07 13:01:15 +00002544 for (auto P : VarsWithInheritedDSA) {
2545 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2546 << P.first << P.second->getSourceRange();
2547 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002548 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2549
2550 if (!AllowedNameModifiers.empty())
2551 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2552 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002553
Alexey Bataeved09d242014-05-28 05:53:51 +00002554 if (ErrorFound)
2555 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002556 return Res;
2557}
2558
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002559Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2560 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002561 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002562 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2563 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002564 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002565 assert(Linears.size() == LinModifiers.size());
2566 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002567 if (!DG || DG.get().isNull())
2568 return DeclGroupPtrTy();
2569
2570 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002571 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002572 return DG;
2573 }
2574 auto *ADecl = DG.get().getSingleDecl();
2575 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2576 ADecl = FTD->getTemplatedDecl();
2577
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002578 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2579 if (!FD) {
2580 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002581 return DeclGroupPtrTy();
2582 }
2583
Alexey Bataev2af33e32016-04-07 12:45:37 +00002584 // OpenMP [2.8.2, declare simd construct, Description]
2585 // The parameter of the simdlen clause must be a constant positive integer
2586 // expression.
2587 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002588 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002589 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002590 // OpenMP [2.8.2, declare simd construct, Description]
2591 // The special this pointer can be used as if was one of the arguments to the
2592 // function in any of the linear, aligned, or uniform clauses.
2593 // The uniform clause declares one or more arguments to have an invariant
2594 // value for all concurrent invocations of the function in the execution of a
2595 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002596 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2597 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002598 for (auto *E : Uniforms) {
2599 E = E->IgnoreParenImpCasts();
2600 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2601 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2602 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2603 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002604 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2605 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002606 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002607 }
2608 if (isa<CXXThisExpr>(E)) {
2609 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002610 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002611 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002612 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2613 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002614 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002615 // OpenMP [2.8.2, declare simd construct, Description]
2616 // The aligned clause declares that the object to which each list item points
2617 // is aligned to the number of bytes expressed in the optional parameter of
2618 // the aligned clause.
2619 // The special this pointer can be used as if was one of the arguments to the
2620 // function in any of the linear, aligned, or uniform clauses.
2621 // The type of list items appearing in the aligned clause must be array,
2622 // pointer, reference to array, or reference to pointer.
2623 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2624 Expr *AlignedThis = nullptr;
2625 for (auto *E : Aligneds) {
2626 E = E->IgnoreParenImpCasts();
2627 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2628 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2629 auto *CanonPVD = PVD->getCanonicalDecl();
2630 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2631 FD->getParamDecl(PVD->getFunctionScopeIndex())
2632 ->getCanonicalDecl() == CanonPVD) {
2633 // OpenMP [2.8.1, simd construct, Restrictions]
2634 // A list-item cannot appear in more than one aligned clause.
2635 if (AlignedArgs.count(CanonPVD) > 0) {
2636 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2637 << 1 << E->getSourceRange();
2638 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2639 diag::note_omp_explicit_dsa)
2640 << getOpenMPClauseName(OMPC_aligned);
2641 continue;
2642 }
2643 AlignedArgs[CanonPVD] = E;
2644 QualType QTy = PVD->getType()
2645 .getNonReferenceType()
2646 .getUnqualifiedType()
2647 .getCanonicalType();
2648 const Type *Ty = QTy.getTypePtrOrNull();
2649 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2650 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2651 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2652 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2653 }
2654 continue;
2655 }
2656 }
2657 if (isa<CXXThisExpr>(E)) {
2658 if (AlignedThis) {
2659 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2660 << 2 << E->getSourceRange();
2661 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2662 << getOpenMPClauseName(OMPC_aligned);
2663 }
2664 AlignedThis = E;
2665 continue;
2666 }
2667 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2668 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2669 }
2670 // The optional parameter of the aligned clause, alignment, must be a constant
2671 // positive integer expression. If no optional parameter is specified,
2672 // implementation-defined default alignments for SIMD instructions on the
2673 // target platforms are assumed.
2674 SmallVector<Expr *, 4> NewAligns;
2675 for (auto *E : Alignments) {
2676 ExprResult Align;
2677 if (E)
2678 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2679 NewAligns.push_back(Align.get());
2680 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002681 // OpenMP [2.8.2, declare simd construct, Description]
2682 // The linear clause declares one or more list items to be private to a SIMD
2683 // lane and to have a linear relationship with respect to the iteration space
2684 // of a loop.
2685 // The special this pointer can be used as if was one of the arguments to the
2686 // function in any of the linear, aligned, or uniform clauses.
2687 // When a linear-step expression is specified in a linear clause it must be
2688 // either a constant integer expression or an integer-typed parameter that is
2689 // specified in a uniform clause on the directive.
2690 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2691 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2692 auto MI = LinModifiers.begin();
2693 for (auto *E : Linears) {
2694 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2695 ++MI;
2696 E = E->IgnoreParenImpCasts();
2697 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2698 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2699 auto *CanonPVD = PVD->getCanonicalDecl();
2700 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2701 FD->getParamDecl(PVD->getFunctionScopeIndex())
2702 ->getCanonicalDecl() == CanonPVD) {
2703 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2704 // A list-item cannot appear in more than one linear clause.
2705 if (LinearArgs.count(CanonPVD) > 0) {
2706 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2707 << getOpenMPClauseName(OMPC_linear)
2708 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2709 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2710 diag::note_omp_explicit_dsa)
2711 << getOpenMPClauseName(OMPC_linear);
2712 continue;
2713 }
2714 // Each argument can appear in at most one uniform or linear clause.
2715 if (UniformedArgs.count(CanonPVD) > 0) {
2716 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2717 << getOpenMPClauseName(OMPC_linear)
2718 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2719 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2720 diag::note_omp_explicit_dsa)
2721 << getOpenMPClauseName(OMPC_uniform);
2722 continue;
2723 }
2724 LinearArgs[CanonPVD] = E;
2725 if (E->isValueDependent() || E->isTypeDependent() ||
2726 E->isInstantiationDependent() ||
2727 E->containsUnexpandedParameterPack())
2728 continue;
2729 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2730 PVD->getOriginalType());
2731 continue;
2732 }
2733 }
2734 if (isa<CXXThisExpr>(E)) {
2735 if (UniformedLinearThis) {
2736 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2737 << getOpenMPClauseName(OMPC_linear)
2738 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2739 << E->getSourceRange();
2740 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2741 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2742 : OMPC_linear);
2743 continue;
2744 }
2745 UniformedLinearThis = E;
2746 if (E->isValueDependent() || E->isTypeDependent() ||
2747 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2748 continue;
2749 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2750 E->getType());
2751 continue;
2752 }
2753 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2754 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2755 }
2756 Expr *Step = nullptr;
2757 Expr *NewStep = nullptr;
2758 SmallVector<Expr *, 4> NewSteps;
2759 for (auto *E : Steps) {
2760 // Skip the same step expression, it was checked already.
2761 if (Step == E || !E) {
2762 NewSteps.push_back(E ? NewStep : nullptr);
2763 continue;
2764 }
2765 Step = E;
2766 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2767 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2768 auto *CanonPVD = PVD->getCanonicalDecl();
2769 if (UniformedArgs.count(CanonPVD) == 0) {
2770 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2771 << Step->getSourceRange();
2772 } else if (E->isValueDependent() || E->isTypeDependent() ||
2773 E->isInstantiationDependent() ||
2774 E->containsUnexpandedParameterPack() ||
2775 CanonPVD->getType()->hasIntegerRepresentation())
2776 NewSteps.push_back(Step);
2777 else {
2778 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2779 << Step->getSourceRange();
2780 }
2781 continue;
2782 }
2783 NewStep = Step;
2784 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2785 !Step->isInstantiationDependent() &&
2786 !Step->containsUnexpandedParameterPack()) {
2787 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2788 .get();
2789 if (NewStep)
2790 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2791 }
2792 NewSteps.push_back(NewStep);
2793 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002794 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2795 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002796 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002797 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2798 const_cast<Expr **>(Linears.data()), Linears.size(),
2799 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2800 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002801 ADecl->addAttr(NewAttr);
2802 return ConvertDeclToDeclGroup(ADecl);
2803}
2804
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002805StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2806 Stmt *AStmt,
2807 SourceLocation StartLoc,
2808 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002809 if (!AStmt)
2810 return StmtError();
2811
Alexey Bataev9959db52014-05-06 10:08:46 +00002812 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2813 // 1.2.2 OpenMP Language Terminology
2814 // Structured block - An executable statement with a single entry at the
2815 // top and a single exit at the bottom.
2816 // The point of exit cannot be a branch out of the structured block.
2817 // longjmp() and throw() must not violate the entry/exit criteria.
2818 CS->getCapturedDecl()->setNothrow();
2819
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002820 getCurFunction()->setHasBranchProtectedScope();
2821
Alexey Bataev25e5b442015-09-15 12:52:43 +00002822 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2823 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002824}
2825
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002826namespace {
2827/// \brief Helper class for checking canonical form of the OpenMP loops and
2828/// extracting iteration space of each loop in the loop nest, that will be used
2829/// for IR generation.
2830class OpenMPIterationSpaceChecker {
2831 /// \brief Reference to Sema.
2832 Sema &SemaRef;
2833 /// \brief A location for diagnostics (when there is no some better location).
2834 SourceLocation DefaultLoc;
2835 /// \brief A location for diagnostics (when increment is not compatible).
2836 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002837 /// \brief A source location for referring to loop init later.
2838 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002839 /// \brief A source location for referring to condition later.
2840 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002841 /// \brief A source location for referring to increment later.
2842 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002843 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002844 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002845 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002846 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002847 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002848 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002849 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002850 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002851 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002852 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002853 /// \brief This flag is true when condition is one of:
2854 /// Var < UB
2855 /// Var <= UB
2856 /// UB > Var
2857 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002858 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002859 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002860 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002861 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002862 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002863
2864public:
2865 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002866 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002867 /// \brief Check init-expr for canonical loop form and save loop counter
2868 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002869 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002870 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2871 /// for less/greater and for strict/non-strict comparison.
2872 bool CheckCond(Expr *S);
2873 /// \brief Check incr-expr for canonical loop form and return true if it
2874 /// does not conform, otherwise save loop step (#Step).
2875 bool CheckInc(Expr *S);
2876 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002877 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002878 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002879 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002880 /// \brief Source range of the loop init.
2881 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2882 /// \brief Source range of the loop condition.
2883 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2884 /// \brief Source range of the loop increment.
2885 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2886 /// \brief True if the step should be subtracted.
2887 bool ShouldSubtractStep() const { return SubtractStep; }
2888 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002889 Expr *
2890 BuildNumIterations(Scope *S, const bool LimitedType,
2891 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002892 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002893 Expr *BuildPreCond(Scope *S, Expr *Cond,
2894 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002895 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002896 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2897 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002898 /// \brief Build reference expression to the private counter be used for
2899 /// codegen.
2900 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002901 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002902 Expr *BuildCounterInit() const;
2903 /// \brief Build step of the counter be used for codegen.
2904 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002905 /// \brief Return true if any expression is dependent.
2906 bool Dependent() const;
2907
2908private:
2909 /// \brief Check the right-hand side of an assignment in the increment
2910 /// expression.
2911 bool CheckIncRHS(Expr *RHS);
2912 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002913 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002914 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002915 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002916 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002917 /// \brief Helper to set loop increment.
2918 bool SetStep(Expr *NewStep, bool Subtract);
2919};
2920
2921bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002922 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002923 assert(!LB && !UB && !Step);
2924 return false;
2925 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002926 return LCDecl->getType()->isDependentType() ||
2927 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2928 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002929}
2930
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002931static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002932 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2933 E = ExprTemp->getSubExpr();
2934
2935 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2936 E = MTE->GetTemporaryExpr();
2937
2938 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2939 E = Binder->getSubExpr();
2940
2941 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2942 E = ICE->getSubExprAsWritten();
2943 return E->IgnoreParens();
2944}
2945
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002946bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2947 Expr *NewLCRefExpr,
2948 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002949 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002950 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002951 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002952 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002953 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002954 LCDecl = getCanonicalDecl(NewLCDecl);
2955 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002956 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2957 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002958 if ((Ctor->isCopyOrMoveConstructor() ||
2959 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2960 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002961 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002962 LB = NewLB;
2963 return false;
2964}
2965
2966bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002967 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002968 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002969 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2970 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002971 if (!NewUB)
2972 return true;
2973 UB = NewUB;
2974 TestIsLessOp = LessOp;
2975 TestIsStrictOp = StrictOp;
2976 ConditionSrcRange = SR;
2977 ConditionLoc = SL;
2978 return false;
2979}
2980
2981bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2982 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002983 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002984 if (!NewStep)
2985 return true;
2986 if (!NewStep->isValueDependent()) {
2987 // Check that the step is integer expression.
2988 SourceLocation StepLoc = NewStep->getLocStart();
2989 ExprResult Val =
2990 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2991 if (Val.isInvalid())
2992 return true;
2993 NewStep = Val.get();
2994
2995 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2996 // If test-expr is of form var relational-op b and relational-op is < or
2997 // <= then incr-expr must cause var to increase on each iteration of the
2998 // loop. If test-expr is of form var relational-op b and relational-op is
2999 // > or >= then incr-expr must cause var to decrease on each iteration of
3000 // the loop.
3001 // If test-expr is of form b relational-op var and relational-op is < or
3002 // <= then incr-expr must cause var to decrease on each iteration of the
3003 // loop. If test-expr is of form b relational-op var and relational-op is
3004 // > or >= then incr-expr must cause var to increase on each iteration of
3005 // the loop.
3006 llvm::APSInt Result;
3007 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3008 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3009 bool IsConstNeg =
3010 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003011 bool IsConstPos =
3012 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003013 bool IsConstZero = IsConstant && !Result.getBoolValue();
3014 if (UB && (IsConstZero ||
3015 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003016 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003017 SemaRef.Diag(NewStep->getExprLoc(),
3018 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003019 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003020 SemaRef.Diag(ConditionLoc,
3021 diag::note_omp_loop_cond_requres_compatible_incr)
3022 << TestIsLessOp << ConditionSrcRange;
3023 return true;
3024 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003025 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003026 NewStep =
3027 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3028 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003029 Subtract = !Subtract;
3030 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003031 }
3032
3033 Step = NewStep;
3034 SubtractStep = Subtract;
3035 return false;
3036}
3037
Alexey Bataev9c821032015-04-30 04:23:23 +00003038bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003039 // Check init-expr for canonical loop form and save loop counter
3040 // variable - #Var and its initialization value - #LB.
3041 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3042 // var = lb
3043 // integer-type var = lb
3044 // random-access-iterator-type var = lb
3045 // pointer-type var = lb
3046 //
3047 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003048 if (EmitDiags) {
3049 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3050 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003051 return true;
3052 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003053 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3054 if (!ExprTemp->cleanupsHaveSideEffects())
3055 S = ExprTemp->getSubExpr();
3056
Alexander Musmana5f070a2014-10-01 06:03:56 +00003057 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003058 if (Expr *E = dyn_cast<Expr>(S))
3059 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003060 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003061 if (BO->getOpcode() == BO_Assign) {
3062 auto *LHS = BO->getLHS()->IgnoreParens();
3063 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3064 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3065 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3066 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3067 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3068 }
3069 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3070 if (ME->isArrow() &&
3071 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3072 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3073 }
3074 }
David Majnemer9d168222016-08-05 17:44:54 +00003075 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003076 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003077 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003078 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003079 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003080 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003081 SemaRef.Diag(S->getLocStart(),
3082 diag::ext_omp_loop_not_canonical_init)
3083 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003084 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003085 }
3086 }
3087 }
David Majnemer9d168222016-08-05 17:44:54 +00003088 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003089 if (CE->getOperator() == OO_Equal) {
3090 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003091 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003092 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3093 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3094 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3095 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3096 }
3097 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3098 if (ME->isArrow() &&
3099 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3100 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3101 }
3102 }
3103 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003104
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003105 if (Dependent() || SemaRef.CurContext->isDependentContext())
3106 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003107 if (EmitDiags) {
3108 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3109 << S->getSourceRange();
3110 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003111 return true;
3112}
3113
Alexey Bataev23b69422014-06-18 07:08:49 +00003114/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003115/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003116static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003117 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003118 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003119 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003120 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3121 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003122 if ((Ctor->isCopyOrMoveConstructor() ||
3123 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3124 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003125 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003126 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3127 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3128 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3129 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3130 return getCanonicalDecl(ME->getMemberDecl());
3131 return getCanonicalDecl(VD);
3132 }
3133 }
3134 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3135 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3136 return getCanonicalDecl(ME->getMemberDecl());
3137 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003138}
3139
3140bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3141 // Check test-expr for canonical form, save upper-bound UB, flags for
3142 // less/greater and for strict/non-strict comparison.
3143 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3144 // var relational-op b
3145 // b relational-op var
3146 //
3147 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003148 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003149 return true;
3150 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003151 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003152 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003153 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003154 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003155 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003156 return SetUB(BO->getRHS(),
3157 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3158 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3159 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003160 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003161 return SetUB(BO->getLHS(),
3162 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3163 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3164 BO->getSourceRange(), BO->getOperatorLoc());
3165 }
David Majnemer9d168222016-08-05 17:44:54 +00003166 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003167 if (CE->getNumArgs() == 2) {
3168 auto Op = CE->getOperator();
3169 switch (Op) {
3170 case OO_Greater:
3171 case OO_GreaterEqual:
3172 case OO_Less:
3173 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003174 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003175 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3176 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3177 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003178 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003179 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3180 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3181 CE->getOperatorLoc());
3182 break;
3183 default:
3184 break;
3185 }
3186 }
3187 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003188 if (Dependent() || SemaRef.CurContext->isDependentContext())
3189 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003190 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003191 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003192 return true;
3193}
3194
3195bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3196 // RHS of canonical loop form increment can be:
3197 // var + incr
3198 // incr + var
3199 // var - incr
3200 //
3201 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003202 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003203 if (BO->isAdditiveOp()) {
3204 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003205 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003206 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003207 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003208 return SetStep(BO->getLHS(), false);
3209 }
David Majnemer9d168222016-08-05 17:44:54 +00003210 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003211 bool IsAdd = CE->getOperator() == OO_Plus;
3212 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003213 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003214 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003215 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003216 return SetStep(CE->getArg(0), false);
3217 }
3218 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003219 if (Dependent() || SemaRef.CurContext->isDependentContext())
3220 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003221 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003222 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003223 return true;
3224}
3225
3226bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3227 // Check incr-expr for canonical loop form and return true if it
3228 // does not conform.
3229 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3230 // ++var
3231 // var++
3232 // --var
3233 // var--
3234 // var += incr
3235 // var -= incr
3236 // var = var + incr
3237 // var = incr + var
3238 // var = var - incr
3239 //
3240 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003241 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003242 return true;
3243 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003244 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3245 if (!ExprTemp->cleanupsHaveSideEffects())
3246 S = ExprTemp->getSubExpr();
3247
Alexander Musmana5f070a2014-10-01 06:03:56 +00003248 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003249 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003250 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003251 if (UO->isIncrementDecrementOp() &&
3252 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003253 return SetStep(SemaRef
3254 .ActOnIntegerConstant(UO->getLocStart(),
3255 (UO->isDecrementOp() ? -1 : 1))
3256 .get(),
3257 false);
3258 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003259 switch (BO->getOpcode()) {
3260 case BO_AddAssign:
3261 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003262 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003263 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3264 break;
3265 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003266 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003267 return CheckIncRHS(BO->getRHS());
3268 break;
3269 default:
3270 break;
3271 }
David Majnemer9d168222016-08-05 17:44:54 +00003272 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003273 switch (CE->getOperator()) {
3274 case OO_PlusPlus:
3275 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003276 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003277 return SetStep(SemaRef
3278 .ActOnIntegerConstant(
3279 CE->getLocStart(),
3280 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3281 .get(),
3282 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003283 break;
3284 case OO_PlusEqual:
3285 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003286 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003287 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3288 break;
3289 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003290 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003291 return CheckIncRHS(CE->getArg(1));
3292 break;
3293 default:
3294 break;
3295 }
3296 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003297 if (Dependent() || SemaRef.CurContext->isDependentContext())
3298 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003299 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003300 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003301 return true;
3302}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003303
Alexey Bataev5a3af132016-03-29 08:58:54 +00003304static ExprResult
3305tryBuildCapture(Sema &SemaRef, Expr *Capture,
3306 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003307 if (SemaRef.CurContext->isDependentContext())
3308 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003309 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3310 return SemaRef.PerformImplicitConversion(
3311 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3312 /*AllowExplicit=*/true);
3313 auto I = Captures.find(Capture);
3314 if (I != Captures.end())
3315 return buildCapture(SemaRef, Capture, I->second);
3316 DeclRefExpr *Ref = nullptr;
3317 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3318 Captures[Capture] = Ref;
3319 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003320}
3321
Alexander Musmana5f070a2014-10-01 06:03:56 +00003322/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003323Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3324 Scope *S, const bool LimitedType,
3325 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003326 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003327 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003328 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003329 SemaRef.getLangOpts().CPlusPlus) {
3330 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003331 auto *UBExpr = TestIsLessOp ? UB : LB;
3332 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003333 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3334 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003335 if (!Upper || !Lower)
3336 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003337
3338 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3339
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003340 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003341 // BuildBinOp already emitted error, this one is to point user to upper
3342 // and lower bound, and to tell what is passed to 'operator-'.
3343 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3344 << Upper->getSourceRange() << Lower->getSourceRange();
3345 return nullptr;
3346 }
3347 }
3348
3349 if (!Diff.isUsable())
3350 return nullptr;
3351
3352 // Upper - Lower [- 1]
3353 if (TestIsStrictOp)
3354 Diff = SemaRef.BuildBinOp(
3355 S, DefaultLoc, BO_Sub, Diff.get(),
3356 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3357 if (!Diff.isUsable())
3358 return nullptr;
3359
3360 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003361 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3362 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003363 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003364 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003365 if (!Diff.isUsable())
3366 return nullptr;
3367
3368 // Parentheses (for dumping/debugging purposes only).
3369 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3370 if (!Diff.isUsable())
3371 return nullptr;
3372
3373 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003374 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003375 if (!Diff.isUsable())
3376 return nullptr;
3377
Alexander Musman174b3ca2014-10-06 11:16:29 +00003378 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003379 QualType Type = Diff.get()->getType();
3380 auto &C = SemaRef.Context;
3381 bool UseVarType = VarType->hasIntegerRepresentation() &&
3382 C.getTypeSize(Type) > C.getTypeSize(VarType);
3383 if (!Type->isIntegerType() || UseVarType) {
3384 unsigned NewSize =
3385 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3386 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3387 : Type->hasSignedIntegerRepresentation();
3388 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003389 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3390 Diff = SemaRef.PerformImplicitConversion(
3391 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3392 if (!Diff.isUsable())
3393 return nullptr;
3394 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003395 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003396 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003397 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3398 if (NewSize != C.getTypeSize(Type)) {
3399 if (NewSize < C.getTypeSize(Type)) {
3400 assert(NewSize == 64 && "incorrect loop var size");
3401 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3402 << InitSrcRange << ConditionSrcRange;
3403 }
3404 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003405 NewSize, Type->hasSignedIntegerRepresentation() ||
3406 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003407 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3408 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3409 Sema::AA_Converting, true);
3410 if (!Diff.isUsable())
3411 return nullptr;
3412 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003413 }
3414 }
3415
Alexander Musmana5f070a2014-10-01 06:03:56 +00003416 return Diff.get();
3417}
3418
Alexey Bataev5a3af132016-03-29 08:58:54 +00003419Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3420 Scope *S, Expr *Cond,
3421 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003422 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3423 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3424 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003425
Alexey Bataev5a3af132016-03-29 08:58:54 +00003426 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3427 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3428 if (!NewLB.isUsable() || !NewUB.isUsable())
3429 return nullptr;
3430
Alexey Bataev62dbb972015-04-22 11:59:37 +00003431 auto CondExpr = SemaRef.BuildBinOp(
3432 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3433 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003434 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003435 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003436 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3437 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003438 CondExpr = SemaRef.PerformImplicitConversion(
3439 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3440 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003441 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003442 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3443 // Otherwise use original loop conditon and evaluate it in runtime.
3444 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3445}
3446
Alexander Musmana5f070a2014-10-01 06:03:56 +00003447/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003448DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003449 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003450 auto *VD = dyn_cast<VarDecl>(LCDecl);
3451 if (!VD) {
3452 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3453 auto *Ref = buildDeclRefExpr(
3454 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003455 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3456 // If the loop control decl is explicitly marked as private, do not mark it
3457 // as captured again.
3458 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3459 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003460 return Ref;
3461 }
3462 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003463 DefaultLoc);
3464}
3465
3466Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003467 if (LCDecl && !LCDecl->isInvalidDecl()) {
3468 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003469 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003470 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3471 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003472 if (PrivateVar->isInvalidDecl())
3473 return nullptr;
3474 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3475 }
3476 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003477}
3478
Samuel Antao4c8035b2016-12-12 18:00:20 +00003479/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003480Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3481
3482/// \brief Build step of the counter be used for codegen.
3483Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3484
3485/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003486struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003487 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003488 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003489 /// \brief This expression calculates the number of iterations in the loop.
3490 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003491 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003492 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003493 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003494 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003495 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003496 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003497 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003498 /// \brief This is step for the #CounterVar used to generate its update:
3499 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003500 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003501 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003502 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003503 /// \brief Source range of the loop init.
3504 SourceRange InitSrcRange;
3505 /// \brief Source range of the loop condition.
3506 SourceRange CondSrcRange;
3507 /// \brief Source range of the loop increment.
3508 SourceRange IncSrcRange;
3509};
3510
Alexey Bataev23b69422014-06-18 07:08:49 +00003511} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003512
Alexey Bataev9c821032015-04-30 04:23:23 +00003513void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3514 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3515 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003516 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3517 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003518 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3519 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003520 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3521 if (auto *D = ISC.GetLoopDecl()) {
3522 auto *VD = dyn_cast<VarDecl>(D);
3523 if (!VD) {
3524 if (auto *Private = IsOpenMPCapturedDecl(D))
3525 VD = Private;
3526 else {
3527 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3528 /*WithInit=*/false);
3529 VD = cast<VarDecl>(Ref->getDecl());
3530 }
3531 }
3532 DSAStack->addLoopControlVariable(D, VD);
3533 }
3534 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003535 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003536 }
3537}
3538
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003539/// \brief Called on a for stmt to check and extract its iteration space
3540/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003541static bool CheckOpenMPIterationSpace(
3542 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3543 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003544 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003545 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003546 LoopIterationSpace &ResultIterSpace,
3547 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003548 // OpenMP [2.6, Canonical Loop Form]
3549 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003550 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003551 if (!For) {
3552 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003553 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3554 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3555 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3556 if (NestedLoopCount > 1) {
3557 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3558 SemaRef.Diag(DSA.getConstructLoc(),
3559 diag::note_omp_collapse_ordered_expr)
3560 << 2 << CollapseLoopCountExpr->getSourceRange()
3561 << OrderedLoopCountExpr->getSourceRange();
3562 else if (CollapseLoopCountExpr)
3563 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3564 diag::note_omp_collapse_ordered_expr)
3565 << 0 << CollapseLoopCountExpr->getSourceRange();
3566 else
3567 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3568 diag::note_omp_collapse_ordered_expr)
3569 << 1 << OrderedLoopCountExpr->getSourceRange();
3570 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003571 return true;
3572 }
3573 assert(For->getBody());
3574
3575 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3576
3577 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003578 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003579 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003580 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003581
3582 bool HasErrors = false;
3583
3584 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003585 if (auto *LCDecl = ISC.GetLoopDecl()) {
3586 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003587
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003588 // OpenMP [2.6, Canonical Loop Form]
3589 // Var is one of the following:
3590 // A variable of signed or unsigned integer type.
3591 // For C++, a variable of a random access iterator type.
3592 // For C, a variable of a pointer type.
3593 auto VarType = LCDecl->getType().getNonReferenceType();
3594 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3595 !VarType->isPointerType() &&
3596 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3597 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3598 << SemaRef.getLangOpts().CPlusPlus;
3599 HasErrors = true;
3600 }
3601
3602 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3603 // a Construct
3604 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3605 // parallel for construct is (are) private.
3606 // The loop iteration variable in the associated for-loop of a simd
3607 // construct with just one associated for-loop is linear with a
3608 // constant-linear-step that is the increment of the associated for-loop.
3609 // Exclude loop var from the list of variables with implicitly defined data
3610 // sharing attributes.
3611 VarsWithImplicitDSA.erase(LCDecl);
3612
3613 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3614 // in a Construct, C/C++].
3615 // The loop iteration variable in the associated for-loop of a simd
3616 // construct with just one associated for-loop may be listed in a linear
3617 // clause with a constant-linear-step that is the increment of the
3618 // associated for-loop.
3619 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3620 // parallel for construct may be listed in a private or lastprivate clause.
3621 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3622 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3623 // declared in the loop and it is predetermined as a private.
3624 auto PredeterminedCKind =
3625 isOpenMPSimdDirective(DKind)
3626 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3627 : OMPC_private;
3628 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3629 DVar.CKind != PredeterminedCKind) ||
3630 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3631 isOpenMPDistributeDirective(DKind)) &&
3632 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3633 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3634 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3635 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3636 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3637 << getOpenMPClauseName(PredeterminedCKind);
3638 if (DVar.RefExpr == nullptr)
3639 DVar.CKind = PredeterminedCKind;
3640 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3641 HasErrors = true;
3642 } else if (LoopDeclRefExpr != nullptr) {
3643 // Make the loop iteration variable private (for worksharing constructs),
3644 // linear (for simd directives with the only one associated loop) or
3645 // lastprivate (for simd directives with several collapsed or ordered
3646 // loops).
3647 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003648 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3649 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003650 /*FromParent=*/false);
3651 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3652 }
3653
3654 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3655
3656 // Check test-expr.
3657 HasErrors |= ISC.CheckCond(For->getCond());
3658
3659 // Check incr-expr.
3660 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003661 }
3662
Alexander Musmana5f070a2014-10-01 06:03:56 +00003663 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003664 return HasErrors;
3665
Alexander Musmana5f070a2014-10-01 06:03:56 +00003666 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003667 ResultIterSpace.PreCond =
3668 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003669 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003670 DSA.getCurScope(),
3671 (isOpenMPWorksharingDirective(DKind) ||
3672 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3673 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003674 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003675 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003676 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3677 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3678 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3679 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3680 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3681 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3682
Alexey Bataev62dbb972015-04-22 11:59:37 +00003683 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3684 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003685 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003686 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003687 ResultIterSpace.CounterInit == nullptr ||
3688 ResultIterSpace.CounterStep == nullptr);
3689
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003690 return HasErrors;
3691}
3692
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003693/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003694static ExprResult
3695BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3696 ExprResult Start,
3697 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003698 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003699 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3700 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003701 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003702 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003703 VarRef.get()->getType())) {
3704 NewStart = SemaRef.PerformImplicitConversion(
3705 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3706 /*AllowExplicit=*/true);
3707 if (!NewStart.isUsable())
3708 return ExprError();
3709 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003710
3711 auto Init =
3712 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3713 return Init;
3714}
3715
Alexander Musmana5f070a2014-10-01 06:03:56 +00003716/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003717static ExprResult
3718BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3719 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3720 ExprResult Step, bool Subtract,
3721 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003722 // Add parentheses (for debugging purposes only).
3723 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3724 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3725 !Step.isUsable())
3726 return ExprError();
3727
Alexey Bataev5a3af132016-03-29 08:58:54 +00003728 ExprResult NewStep = Step;
3729 if (Captures)
3730 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003731 if (NewStep.isInvalid())
3732 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003733 ExprResult Update =
3734 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003735 if (!Update.isUsable())
3736 return ExprError();
3737
Alexey Bataevc0214e02016-02-16 12:13:49 +00003738 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3739 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003740 ExprResult NewStart = Start;
3741 if (Captures)
3742 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003743 if (NewStart.isInvalid())
3744 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003745
Alexey Bataevc0214e02016-02-16 12:13:49 +00003746 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3747 ExprResult SavedUpdate = Update;
3748 ExprResult UpdateVal;
3749 if (VarRef.get()->getType()->isOverloadableType() ||
3750 NewStart.get()->getType()->isOverloadableType() ||
3751 Update.get()->getType()->isOverloadableType()) {
3752 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3753 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3754 Update =
3755 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3756 if (Update.isUsable()) {
3757 UpdateVal =
3758 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3759 VarRef.get(), SavedUpdate.get());
3760 if (UpdateVal.isUsable()) {
3761 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3762 UpdateVal.get());
3763 }
3764 }
3765 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3766 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003767
Alexey Bataevc0214e02016-02-16 12:13:49 +00003768 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3769 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3770 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3771 NewStart.get(), SavedUpdate.get());
3772 if (!Update.isUsable())
3773 return ExprError();
3774
Alexey Bataev11481f52016-02-17 10:29:05 +00003775 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3776 VarRef.get()->getType())) {
3777 Update = SemaRef.PerformImplicitConversion(
3778 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3779 if (!Update.isUsable())
3780 return ExprError();
3781 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003782
3783 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3784 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003785 return Update;
3786}
3787
3788/// \brief Convert integer expression \a E to make it have at least \a Bits
3789/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003790static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003791 if (E == nullptr)
3792 return ExprError();
3793 auto &C = SemaRef.Context;
3794 QualType OldType = E->getType();
3795 unsigned HasBits = C.getTypeSize(OldType);
3796 if (HasBits >= Bits)
3797 return ExprResult(E);
3798 // OK to convert to signed, because new type has more bits than old.
3799 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3800 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3801 true);
3802}
3803
3804/// \brief Check if the given expression \a E is a constant integer that fits
3805/// into \a Bits bits.
3806static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3807 if (E == nullptr)
3808 return false;
3809 llvm::APSInt Result;
3810 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3811 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3812 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003813}
3814
Alexey Bataev5a3af132016-03-29 08:58:54 +00003815/// Build preinits statement for the given declarations.
3816static Stmt *buildPreInits(ASTContext &Context,
3817 SmallVectorImpl<Decl *> &PreInits) {
3818 if (!PreInits.empty()) {
3819 return new (Context) DeclStmt(
3820 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3821 SourceLocation(), SourceLocation());
3822 }
3823 return nullptr;
3824}
3825
3826/// Build preinits statement for the given declarations.
3827static Stmt *buildPreInits(ASTContext &Context,
3828 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3829 if (!Captures.empty()) {
3830 SmallVector<Decl *, 16> PreInits;
3831 for (auto &Pair : Captures)
3832 PreInits.push_back(Pair.second->getDecl());
3833 return buildPreInits(Context, PreInits);
3834 }
3835 return nullptr;
3836}
3837
3838/// Build postupdate expression for the given list of postupdates expressions.
3839static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3840 Expr *PostUpdate = nullptr;
3841 if (!PostUpdates.empty()) {
3842 for (auto *E : PostUpdates) {
3843 Expr *ConvE = S.BuildCStyleCastExpr(
3844 E->getExprLoc(),
3845 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3846 E->getExprLoc(), E)
3847 .get();
3848 PostUpdate = PostUpdate
3849 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3850 PostUpdate, ConvE)
3851 .get()
3852 : ConvE;
3853 }
3854 }
3855 return PostUpdate;
3856}
3857
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003858/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003859/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3860/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003861static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003862CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3863 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3864 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003865 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003866 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003867 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003868 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003869 // Found 'collapse' clause - calculate collapse number.
3870 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003871 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003872 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003873 }
3874 if (OrderedLoopCountExpr) {
3875 // Found 'ordered' clause - calculate collapse number.
3876 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003877 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3878 if (Result.getLimitedValue() < NestedLoopCount) {
3879 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3880 diag::err_omp_wrong_ordered_loop_count)
3881 << OrderedLoopCountExpr->getSourceRange();
3882 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3883 diag::note_collapse_loop_count)
3884 << CollapseLoopCountExpr->getSourceRange();
3885 }
3886 NestedLoopCount = Result.getLimitedValue();
3887 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003888 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003889 // This is helper routine for loop directives (e.g., 'for', 'simd',
3890 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003891 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003892 SmallVector<LoopIterationSpace, 4> IterSpaces;
3893 IterSpaces.resize(NestedLoopCount);
3894 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003895 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003896 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003897 NestedLoopCount, CollapseLoopCountExpr,
3898 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003899 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003900 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003901 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003902 // OpenMP [2.8.1, simd construct, Restrictions]
3903 // All loops associated with the construct must be perfectly nested; that
3904 // is, there must be no intervening code nor any OpenMP directive between
3905 // any two loops.
3906 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003907 }
3908
Alexander Musmana5f070a2014-10-01 06:03:56 +00003909 Built.clear(/* size */ NestedLoopCount);
3910
3911 if (SemaRef.CurContext->isDependentContext())
3912 return NestedLoopCount;
3913
3914 // An example of what is generated for the following code:
3915 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003916 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003917 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003918 // for (k = 0; k < NK; ++k)
3919 // for (j = J0; j < NJ; j+=2) {
3920 // <loop body>
3921 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003922 //
3923 // We generate the code below.
3924 // Note: the loop body may be outlined in CodeGen.
3925 // Note: some counters may be C++ classes, operator- is used to find number of
3926 // iterations and operator+= to calculate counter value.
3927 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3928 // or i64 is currently supported).
3929 //
3930 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3931 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3932 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3933 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3934 // // similar updates for vars in clauses (e.g. 'linear')
3935 // <loop body (using local i and j)>
3936 // }
3937 // i = NI; // assign final values of counters
3938 // j = NJ;
3939 //
3940
3941 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3942 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003943 // Precondition tests if there is at least one iteration (all conditions are
3944 // true).
3945 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003946 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003947 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003948 32 /* Bits */, SemaRef
3949 .PerformImplicitConversion(
3950 N0->IgnoreImpCasts(), N0->getType(),
3951 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003952 .get(),
3953 SemaRef);
3954 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003955 64 /* Bits */, SemaRef
3956 .PerformImplicitConversion(
3957 N0->IgnoreImpCasts(), N0->getType(),
3958 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003959 .get(),
3960 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003961
3962 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3963 return NestedLoopCount;
3964
3965 auto &C = SemaRef.Context;
3966 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3967
3968 Scope *CurScope = DSA.getCurScope();
3969 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003970 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003971 PreCond =
3972 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3973 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003974 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003975 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003976 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003977 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3978 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003979 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003980 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003981 SemaRef
3982 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3983 Sema::AA_Converting,
3984 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003985 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003986 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003987 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003988 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003989 SemaRef
3990 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3991 Sema::AA_Converting,
3992 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003993 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003994 }
3995
3996 // Choose either the 32-bit or 64-bit version.
3997 ExprResult LastIteration = LastIteration64;
3998 if (LastIteration32.isUsable() &&
3999 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4000 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4001 FitsInto(
4002 32 /* Bits */,
4003 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4004 LastIteration64.get(), SemaRef)))
4005 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004006 QualType VType = LastIteration.get()->getType();
4007 QualType RealVType = VType;
4008 QualType StrideVType = VType;
4009 if (isOpenMPTaskLoopDirective(DKind)) {
4010 VType =
4011 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4012 StrideVType =
4013 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4014 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004015
4016 if (!LastIteration.isUsable())
4017 return 0;
4018
4019 // Save the number of iterations.
4020 ExprResult NumIterations = LastIteration;
4021 {
4022 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004023 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4024 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004025 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4026 if (!LastIteration.isUsable())
4027 return 0;
4028 }
4029
4030 // Calculate the last iteration number beforehand instead of doing this on
4031 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4032 llvm::APSInt Result;
4033 bool IsConstant =
4034 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4035 ExprResult CalcLastIteration;
4036 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004037 ExprResult SaveRef =
4038 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004039 LastIteration = SaveRef;
4040
4041 // Prepare SaveRef + 1.
4042 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004043 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004044 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4045 if (!NumIterations.isUsable())
4046 return 0;
4047 }
4048
4049 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4050
David Majnemer9d168222016-08-05 17:44:54 +00004051 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00004052 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004053 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4054 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004055 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004056 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4057 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004058 SemaRef.AddInitializerToDecl(LBDecl,
4059 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4060 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004061
4062 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004063 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4064 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004065 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004066 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004067
4068 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4069 // This will be used to implement clause 'lastprivate'.
4070 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004071 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4072 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004073 SemaRef.AddInitializerToDecl(ILDecl,
4074 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4075 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004076
4077 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004078 VarDecl *STDecl =
4079 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4080 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004081 SemaRef.AddInitializerToDecl(STDecl,
4082 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4083 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004084
4085 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004086 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004087 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4088 UB.get(), LastIteration.get());
4089 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4090 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4091 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4092 CondOp.get());
4093 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004094
4095 // If we have a combined directive that combines 'distribute', 'for' or
4096 // 'simd' we need to be able to access the bounds of the schedule of the
4097 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4098 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4099 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4100 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4101
4102 // We expect to have at least 2 more parameters than the 'parallel'
4103 // directive does - the lower and upper bounds of the previous schedule.
4104 assert(CD->getNumParams() >= 4 &&
4105 "Unexpected number of parameters in loop combined directive");
4106
4107 // Set the proper type for the bounds given what we learned from the
4108 // enclosed loops.
4109 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4110 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4111
4112 // Previous lower and upper bounds are obtained from the region
4113 // parameters.
4114 PrevLB =
4115 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4116 PrevUB =
4117 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4118 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004119 }
4120
4121 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004122 ExprResult IV;
4123 ExprResult Init;
4124 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004125 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4126 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004127 Expr *RHS =
4128 (isOpenMPWorksharingDirective(DKind) ||
4129 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4130 ? LB.get()
4131 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004132 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4133 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004134 }
4135
Alexander Musmanc6388682014-12-15 07:07:06 +00004136 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004137 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004138 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004139 (isOpenMPWorksharingDirective(DKind) ||
4140 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004141 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4142 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4143 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004144
4145 // Loop increment (IV = IV + 1)
4146 SourceLocation IncLoc;
4147 ExprResult Inc =
4148 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4149 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4150 if (!Inc.isUsable())
4151 return 0;
4152 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004153 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4154 if (!Inc.isUsable())
4155 return 0;
4156
4157 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4158 // Used for directives with static scheduling.
4159 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004160 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4161 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004162 // LB + ST
4163 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4164 if (!NextLB.isUsable())
4165 return 0;
4166 // LB = LB + ST
4167 NextLB =
4168 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4169 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4170 if (!NextLB.isUsable())
4171 return 0;
4172 // UB + ST
4173 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4174 if (!NextUB.isUsable())
4175 return 0;
4176 // UB = UB + ST
4177 NextUB =
4178 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4179 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4180 if (!NextUB.isUsable())
4181 return 0;
4182 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004183
4184 // Build updates and final values of the loop counters.
4185 bool HasErrors = false;
4186 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004187 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004188 Built.Updates.resize(NestedLoopCount);
4189 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004190 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004191 {
4192 ExprResult Div;
4193 // Go from inner nested loop to outer.
4194 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4195 LoopIterationSpace &IS = IterSpaces[Cnt];
4196 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4197 // Build: Iter = (IV / Div) % IS.NumIters
4198 // where Div is product of previous iterations' IS.NumIters.
4199 ExprResult Iter;
4200 if (Div.isUsable()) {
4201 Iter =
4202 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4203 } else {
4204 Iter = IV;
4205 assert((Cnt == (int)NestedLoopCount - 1) &&
4206 "unusable div expected on first iteration only");
4207 }
4208
4209 if (Cnt != 0 && Iter.isUsable())
4210 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4211 IS.NumIterations);
4212 if (!Iter.isUsable()) {
4213 HasErrors = true;
4214 break;
4215 }
4216
Alexey Bataev39f915b82015-05-08 10:41:21 +00004217 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004218 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4219 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4220 IS.CounterVar->getExprLoc(),
4221 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004222 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004223 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004224 if (!Init.isUsable()) {
4225 HasErrors = true;
4226 break;
4227 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004228 ExprResult Update = BuildCounterUpdate(
4229 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4230 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004231 if (!Update.isUsable()) {
4232 HasErrors = true;
4233 break;
4234 }
4235
4236 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4237 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004238 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004239 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004240 if (!Final.isUsable()) {
4241 HasErrors = true;
4242 break;
4243 }
4244
4245 // Build Div for the next iteration: Div <- Div * IS.NumIters
4246 if (Cnt != 0) {
4247 if (Div.isUnset())
4248 Div = IS.NumIterations;
4249 else
4250 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4251 IS.NumIterations);
4252
4253 // Add parentheses (for debugging purposes only).
4254 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004255 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004256 if (!Div.isUsable()) {
4257 HasErrors = true;
4258 break;
4259 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004260 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004261 }
4262 if (!Update.isUsable() || !Final.isUsable()) {
4263 HasErrors = true;
4264 break;
4265 }
4266 // Save results
4267 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004268 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004269 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004270 Built.Updates[Cnt] = Update.get();
4271 Built.Finals[Cnt] = Final.get();
4272 }
4273 }
4274
4275 if (HasErrors)
4276 return 0;
4277
4278 // Save results
4279 Built.IterationVarRef = IV.get();
4280 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004281 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004282 Built.CalcLastIteration =
4283 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004284 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004285 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004286 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004287 Built.Init = Init.get();
4288 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004289 Built.LB = LB.get();
4290 Built.UB = UB.get();
4291 Built.IL = IL.get();
4292 Built.ST = ST.get();
4293 Built.EUB = EUB.get();
4294 Built.NLB = NextLB.get();
4295 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004296 Built.PrevLB = PrevLB.get();
4297 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004298
Alexey Bataev8b427062016-05-25 12:36:08 +00004299 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4300 // Fill data for doacross depend clauses.
4301 for (auto Pair : DSA.getDoacrossDependClauses()) {
4302 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4303 Pair.first->setCounterValue(CounterVal);
4304 else {
4305 if (NestedLoopCount != Pair.second.size() ||
4306 NestedLoopCount != LoopMultipliers.size() + 1) {
4307 // Erroneous case - clause has some problems.
4308 Pair.first->setCounterValue(CounterVal);
4309 continue;
4310 }
4311 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4312 auto I = Pair.second.rbegin();
4313 auto IS = IterSpaces.rbegin();
4314 auto ILM = LoopMultipliers.rbegin();
4315 Expr *UpCounterVal = CounterVal;
4316 Expr *Multiplier = nullptr;
4317 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4318 if (I->first) {
4319 assert(IS->CounterStep);
4320 Expr *NormalizedOffset =
4321 SemaRef
4322 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4323 I->first, IS->CounterStep)
4324 .get();
4325 if (Multiplier) {
4326 NormalizedOffset =
4327 SemaRef
4328 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4329 NormalizedOffset, Multiplier)
4330 .get();
4331 }
4332 assert(I->second == OO_Plus || I->second == OO_Minus);
4333 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004334 UpCounterVal = SemaRef
4335 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4336 UpCounterVal, NormalizedOffset)
4337 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004338 }
4339 Multiplier = *ILM;
4340 ++I;
4341 ++IS;
4342 ++ILM;
4343 }
4344 Pair.first->setCounterValue(UpCounterVal);
4345 }
4346 }
4347
Alexey Bataevabfc0692014-06-25 06:52:00 +00004348 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004349}
4350
Alexey Bataev10e775f2015-07-30 11:36:16 +00004351static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004352 auto CollapseClauses =
4353 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4354 if (CollapseClauses.begin() != CollapseClauses.end())
4355 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004356 return nullptr;
4357}
4358
Alexey Bataev10e775f2015-07-30 11:36:16 +00004359static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004360 auto OrderedClauses =
4361 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4362 if (OrderedClauses.begin() != OrderedClauses.end())
4363 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004364 return nullptr;
4365}
4366
Kelvin Lic5609492016-07-15 04:39:07 +00004367static bool checkSimdlenSafelenSpecified(Sema &S,
4368 const ArrayRef<OMPClause *> Clauses) {
4369 OMPSafelenClause *Safelen = nullptr;
4370 OMPSimdlenClause *Simdlen = nullptr;
4371
4372 for (auto *Clause : Clauses) {
4373 if (Clause->getClauseKind() == OMPC_safelen)
4374 Safelen = cast<OMPSafelenClause>(Clause);
4375 else if (Clause->getClauseKind() == OMPC_simdlen)
4376 Simdlen = cast<OMPSimdlenClause>(Clause);
4377 if (Safelen && Simdlen)
4378 break;
4379 }
4380
4381 if (Simdlen && Safelen) {
4382 llvm::APSInt SimdlenRes, SafelenRes;
4383 auto SimdlenLength = Simdlen->getSimdlen();
4384 auto SafelenLength = Safelen->getSafelen();
4385 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4386 SimdlenLength->isInstantiationDependent() ||
4387 SimdlenLength->containsUnexpandedParameterPack())
4388 return false;
4389 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4390 SafelenLength->isInstantiationDependent() ||
4391 SafelenLength->containsUnexpandedParameterPack())
4392 return false;
4393 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4394 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4395 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4396 // If both simdlen and safelen clauses are specified, the value of the
4397 // simdlen parameter must be less than or equal to the value of the safelen
4398 // parameter.
4399 if (SimdlenRes > SafelenRes) {
4400 S.Diag(SimdlenLength->getExprLoc(),
4401 diag::err_omp_wrong_simdlen_safelen_values)
4402 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4403 return true;
4404 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004405 }
4406 return false;
4407}
4408
Alexey Bataev4acb8592014-07-07 13:01:15 +00004409StmtResult Sema::ActOnOpenMPSimdDirective(
4410 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4411 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004412 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004413 if (!AStmt)
4414 return StmtError();
4415
4416 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004417 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004418 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4419 // define the nested loops number.
4420 unsigned NestedLoopCount = CheckOpenMPLoop(
4421 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4422 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004423 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004424 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004425
Alexander Musmana5f070a2014-10-01 06:03:56 +00004426 assert((CurContext->isDependentContext() || B.builtAll()) &&
4427 "omp simd loop exprs were not built");
4428
Alexander Musman3276a272015-03-21 10:12:56 +00004429 if (!CurContext->isDependentContext()) {
4430 // Finalize the clauses that need pre-built expressions for CodeGen.
4431 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004432 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004433 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004434 B.NumIterations, *this, CurScope,
4435 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004436 return StmtError();
4437 }
4438 }
4439
Kelvin Lic5609492016-07-15 04:39:07 +00004440 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004441 return StmtError();
4442
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004443 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004444 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4445 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004446}
4447
Alexey Bataev4acb8592014-07-07 13:01:15 +00004448StmtResult Sema::ActOnOpenMPForDirective(
4449 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4450 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004451 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004452 if (!AStmt)
4453 return StmtError();
4454
4455 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004456 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004457 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4458 // define the nested loops number.
4459 unsigned NestedLoopCount = CheckOpenMPLoop(
4460 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4461 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004462 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004463 return StmtError();
4464
Alexander Musmana5f070a2014-10-01 06:03:56 +00004465 assert((CurContext->isDependentContext() || B.builtAll()) &&
4466 "omp for loop exprs were not built");
4467
Alexey Bataev54acd402015-08-04 11:18:19 +00004468 if (!CurContext->isDependentContext()) {
4469 // Finalize the clauses that need pre-built expressions for CodeGen.
4470 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004471 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004472 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004473 B.NumIterations, *this, CurScope,
4474 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004475 return StmtError();
4476 }
4477 }
4478
Alexey Bataevf29276e2014-06-18 04:14:57 +00004479 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004480 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004481 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004482}
4483
Alexander Musmanf82886e2014-09-18 05:12:34 +00004484StmtResult Sema::ActOnOpenMPForSimdDirective(
4485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4486 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004487 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004488 if (!AStmt)
4489 return StmtError();
4490
4491 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004492 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004493 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4494 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004495 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004496 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4497 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4498 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004499 if (NestedLoopCount == 0)
4500 return StmtError();
4501
Alexander Musmanc6388682014-12-15 07:07:06 +00004502 assert((CurContext->isDependentContext() || B.builtAll()) &&
4503 "omp for simd loop exprs were not built");
4504
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004505 if (!CurContext->isDependentContext()) {
4506 // Finalize the clauses that need pre-built expressions for CodeGen.
4507 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004508 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004509 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004510 B.NumIterations, *this, CurScope,
4511 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004512 return StmtError();
4513 }
4514 }
4515
Kelvin Lic5609492016-07-15 04:39:07 +00004516 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004517 return StmtError();
4518
Alexander Musmanf82886e2014-09-18 05:12:34 +00004519 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004520 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4521 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004522}
4523
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004524StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4525 Stmt *AStmt,
4526 SourceLocation StartLoc,
4527 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004528 if (!AStmt)
4529 return StmtError();
4530
4531 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004532 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004533 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004534 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004535 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004536 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004537 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004538 return StmtError();
4539 // All associated statements must be '#pragma omp section' except for
4540 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004541 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004542 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4543 if (SectionStmt)
4544 Diag(SectionStmt->getLocStart(),
4545 diag::err_omp_sections_substmt_not_section);
4546 return StmtError();
4547 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004548 cast<OMPSectionDirective>(SectionStmt)
4549 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004550 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004551 } else {
4552 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4553 return StmtError();
4554 }
4555
4556 getCurFunction()->setHasBranchProtectedScope();
4557
Alexey Bataev25e5b442015-09-15 12:52:43 +00004558 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4559 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004560}
4561
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004562StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4563 SourceLocation StartLoc,
4564 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004565 if (!AStmt)
4566 return StmtError();
4567
4568 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004569
4570 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004571 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004572
Alexey Bataev25e5b442015-09-15 12:52:43 +00004573 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4574 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004575}
4576
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004577StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4578 Stmt *AStmt,
4579 SourceLocation StartLoc,
4580 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004581 if (!AStmt)
4582 return StmtError();
4583
4584 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004585
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004586 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004587
Alexey Bataev3255bf32015-01-19 05:20:46 +00004588 // OpenMP [2.7.3, single Construct, Restrictions]
4589 // The copyprivate clause must not be used with the nowait clause.
4590 OMPClause *Nowait = nullptr;
4591 OMPClause *Copyprivate = nullptr;
4592 for (auto *Clause : Clauses) {
4593 if (Clause->getClauseKind() == OMPC_nowait)
4594 Nowait = Clause;
4595 else if (Clause->getClauseKind() == OMPC_copyprivate)
4596 Copyprivate = Clause;
4597 if (Copyprivate && Nowait) {
4598 Diag(Copyprivate->getLocStart(),
4599 diag::err_omp_single_copyprivate_with_nowait);
4600 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4601 return StmtError();
4602 }
4603 }
4604
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004605 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4606}
4607
Alexander Musman80c22892014-07-17 08:54:58 +00004608StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4609 SourceLocation StartLoc,
4610 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004611 if (!AStmt)
4612 return StmtError();
4613
4614 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004615
4616 getCurFunction()->setHasBranchProtectedScope();
4617
4618 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4619}
4620
Alexey Bataev28c75412015-12-15 08:19:24 +00004621StmtResult Sema::ActOnOpenMPCriticalDirective(
4622 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4623 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004624 if (!AStmt)
4625 return StmtError();
4626
4627 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004628
Alexey Bataev28c75412015-12-15 08:19:24 +00004629 bool ErrorFound = false;
4630 llvm::APSInt Hint;
4631 SourceLocation HintLoc;
4632 bool DependentHint = false;
4633 for (auto *C : Clauses) {
4634 if (C->getClauseKind() == OMPC_hint) {
4635 if (!DirName.getName()) {
4636 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4637 ErrorFound = true;
4638 }
4639 Expr *E = cast<OMPHintClause>(C)->getHint();
4640 if (E->isTypeDependent() || E->isValueDependent() ||
4641 E->isInstantiationDependent())
4642 DependentHint = true;
4643 else {
4644 Hint = E->EvaluateKnownConstInt(Context);
4645 HintLoc = C->getLocStart();
4646 }
4647 }
4648 }
4649 if (ErrorFound)
4650 return StmtError();
4651 auto Pair = DSAStack->getCriticalWithHint(DirName);
4652 if (Pair.first && DirName.getName() && !DependentHint) {
4653 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4654 Diag(StartLoc, diag::err_omp_critical_with_hint);
4655 if (HintLoc.isValid()) {
4656 Diag(HintLoc, diag::note_omp_critical_hint_here)
4657 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4658 } else
4659 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4660 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4661 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4662 << 1
4663 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4664 /*Radix=*/10, /*Signed=*/false);
4665 } else
4666 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4667 }
4668 }
4669
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004670 getCurFunction()->setHasBranchProtectedScope();
4671
Alexey Bataev28c75412015-12-15 08:19:24 +00004672 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4673 Clauses, AStmt);
4674 if (!Pair.first && DirName.getName() && !DependentHint)
4675 DSAStack->addCriticalWithHint(Dir, Hint);
4676 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004677}
4678
Alexey Bataev4acb8592014-07-07 13:01:15 +00004679StmtResult Sema::ActOnOpenMPParallelForDirective(
4680 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4681 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004682 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004683 if (!AStmt)
4684 return StmtError();
4685
Alexey Bataev4acb8592014-07-07 13:01:15 +00004686 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4687 // 1.2.2 OpenMP Language Terminology
4688 // Structured block - An executable statement with a single entry at the
4689 // top and a single exit at the bottom.
4690 // The point of exit cannot be a branch out of the structured block.
4691 // longjmp() and throw() must not violate the entry/exit criteria.
4692 CS->getCapturedDecl()->setNothrow();
4693
Alexander Musmanc6388682014-12-15 07:07:06 +00004694 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004695 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4696 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004697 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004698 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4699 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4700 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004701 if (NestedLoopCount == 0)
4702 return StmtError();
4703
Alexander Musmana5f070a2014-10-01 06:03:56 +00004704 assert((CurContext->isDependentContext() || B.builtAll()) &&
4705 "omp parallel for loop exprs were not built");
4706
Alexey Bataev54acd402015-08-04 11:18:19 +00004707 if (!CurContext->isDependentContext()) {
4708 // Finalize the clauses that need pre-built expressions for CodeGen.
4709 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004710 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004711 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004712 B.NumIterations, *this, CurScope,
4713 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004714 return StmtError();
4715 }
4716 }
4717
Alexey Bataev4acb8592014-07-07 13:01:15 +00004718 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004719 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004720 NestedLoopCount, Clauses, AStmt, B,
4721 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004722}
4723
Alexander Musmane4e893b2014-09-23 09:33:00 +00004724StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4725 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4726 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004727 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004728 if (!AStmt)
4729 return StmtError();
4730
Alexander Musmane4e893b2014-09-23 09:33:00 +00004731 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4732 // 1.2.2 OpenMP Language Terminology
4733 // Structured block - An executable statement with a single entry at the
4734 // top and a single exit at the bottom.
4735 // The point of exit cannot be a branch out of the structured block.
4736 // longjmp() and throw() must not violate the entry/exit criteria.
4737 CS->getCapturedDecl()->setNothrow();
4738
Alexander Musmanc6388682014-12-15 07:07:06 +00004739 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004740 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4741 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004742 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004743 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4744 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4745 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004746 if (NestedLoopCount == 0)
4747 return StmtError();
4748
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004749 if (!CurContext->isDependentContext()) {
4750 // Finalize the clauses that need pre-built expressions for CodeGen.
4751 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004752 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004753 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004754 B.NumIterations, *this, CurScope,
4755 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004756 return StmtError();
4757 }
4758 }
4759
Kelvin Lic5609492016-07-15 04:39:07 +00004760 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004761 return StmtError();
4762
Alexander Musmane4e893b2014-09-23 09:33:00 +00004763 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004764 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004765 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004766}
4767
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004768StmtResult
4769Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4770 Stmt *AStmt, SourceLocation StartLoc,
4771 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004772 if (!AStmt)
4773 return StmtError();
4774
4775 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004776 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004777 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004778 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004779 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004780 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004781 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004782 return StmtError();
4783 // All associated statements must be '#pragma omp section' except for
4784 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004785 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004786 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4787 if (SectionStmt)
4788 Diag(SectionStmt->getLocStart(),
4789 diag::err_omp_parallel_sections_substmt_not_section);
4790 return StmtError();
4791 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004792 cast<OMPSectionDirective>(SectionStmt)
4793 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004794 }
4795 } else {
4796 Diag(AStmt->getLocStart(),
4797 diag::err_omp_parallel_sections_not_compound_stmt);
4798 return StmtError();
4799 }
4800
4801 getCurFunction()->setHasBranchProtectedScope();
4802
Alexey Bataev25e5b442015-09-15 12:52:43 +00004803 return OMPParallelSectionsDirective::Create(
4804 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004805}
4806
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004807StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4808 Stmt *AStmt, SourceLocation StartLoc,
4809 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004810 if (!AStmt)
4811 return StmtError();
4812
David Majnemer9d168222016-08-05 17:44:54 +00004813 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004814 // 1.2.2 OpenMP Language Terminology
4815 // Structured block - An executable statement with a single entry at the
4816 // top and a single exit at the bottom.
4817 // The point of exit cannot be a branch out of the structured block.
4818 // longjmp() and throw() must not violate the entry/exit criteria.
4819 CS->getCapturedDecl()->setNothrow();
4820
4821 getCurFunction()->setHasBranchProtectedScope();
4822
Alexey Bataev25e5b442015-09-15 12:52:43 +00004823 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4824 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004825}
4826
Alexey Bataev68446b72014-07-18 07:47:19 +00004827StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4828 SourceLocation EndLoc) {
4829 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4830}
4831
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004832StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4833 SourceLocation EndLoc) {
4834 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4835}
4836
Alexey Bataev2df347a2014-07-18 10:17:07 +00004837StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4838 SourceLocation EndLoc) {
4839 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4840}
4841
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004842StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4843 SourceLocation StartLoc,
4844 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004845 if (!AStmt)
4846 return StmtError();
4847
4848 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004849
4850 getCurFunction()->setHasBranchProtectedScope();
4851
4852 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4853}
4854
Alexey Bataev6125da92014-07-21 11:26:11 +00004855StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4856 SourceLocation StartLoc,
4857 SourceLocation EndLoc) {
4858 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4859 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4860}
4861
Alexey Bataev346265e2015-09-25 10:37:12 +00004862StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4863 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004864 SourceLocation StartLoc,
4865 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004866 OMPClause *DependFound = nullptr;
4867 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004868 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004869 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004870 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004871 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004872 for (auto *C : Clauses) {
4873 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4874 DependFound = C;
4875 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4876 if (DependSourceClause) {
4877 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4878 << getOpenMPDirectiveName(OMPD_ordered)
4879 << getOpenMPClauseName(OMPC_depend) << 2;
4880 ErrorFound = true;
4881 } else
4882 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004883 if (DependSinkClause) {
4884 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4885 << 0;
4886 ErrorFound = true;
4887 }
4888 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4889 if (DependSourceClause) {
4890 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4891 << 1;
4892 ErrorFound = true;
4893 }
4894 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004895 }
4896 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004897 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004898 else if (C->getClauseKind() == OMPC_simd)
4899 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004900 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004901 if (!ErrorFound && !SC &&
4902 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004903 // OpenMP [2.8.1,simd Construct, Restrictions]
4904 // An ordered construct with the simd clause is the only OpenMP construct
4905 // that can appear in the simd region.
4906 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004907 ErrorFound = true;
4908 } else if (DependFound && (TC || SC)) {
4909 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4910 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4911 ErrorFound = true;
4912 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4913 Diag(DependFound->getLocStart(),
4914 diag::err_omp_ordered_directive_without_param);
4915 ErrorFound = true;
4916 } else if (TC || Clauses.empty()) {
4917 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4918 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4919 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4920 << (TC != nullptr);
4921 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4922 ErrorFound = true;
4923 }
4924 }
4925 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004926 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004927
4928 if (AStmt) {
4929 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4930
4931 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004932 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004933
4934 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004935}
4936
Alexey Bataev1d160b12015-03-13 12:27:31 +00004937namespace {
4938/// \brief Helper class for checking expression in 'omp atomic [update]'
4939/// construct.
4940class OpenMPAtomicUpdateChecker {
4941 /// \brief Error results for atomic update expressions.
4942 enum ExprAnalysisErrorCode {
4943 /// \brief A statement is not an expression statement.
4944 NotAnExpression,
4945 /// \brief Expression is not builtin binary or unary operation.
4946 NotABinaryOrUnaryExpression,
4947 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4948 NotAnUnaryIncDecExpression,
4949 /// \brief An expression is not of scalar type.
4950 NotAScalarType,
4951 /// \brief A binary operation is not an assignment operation.
4952 NotAnAssignmentOp,
4953 /// \brief RHS part of the binary operation is not a binary expression.
4954 NotABinaryExpression,
4955 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4956 /// expression.
4957 NotABinaryOperator,
4958 /// \brief RHS binary operation does not have reference to the updated LHS
4959 /// part.
4960 NotAnUpdateExpression,
4961 /// \brief No errors is found.
4962 NoError
4963 };
4964 /// \brief Reference to Sema.
4965 Sema &SemaRef;
4966 /// \brief A location for note diagnostics (when error is found).
4967 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004968 /// \brief 'x' lvalue part of the source atomic expression.
4969 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004970 /// \brief 'expr' rvalue part of the source atomic expression.
4971 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004972 /// \brief Helper expression of the form
4973 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4974 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4975 Expr *UpdateExpr;
4976 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4977 /// important for non-associative operations.
4978 bool IsXLHSInRHSPart;
4979 BinaryOperatorKind Op;
4980 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004981 /// \brief true if the source expression is a postfix unary operation, false
4982 /// if it is a prefix unary operation.
4983 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004984
4985public:
4986 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004987 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004988 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004989 /// \brief Check specified statement that it is suitable for 'atomic update'
4990 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004991 /// expression. If DiagId and NoteId == 0, then only check is performed
4992 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004993 /// \param DiagId Diagnostic which should be emitted if error is found.
4994 /// \param NoteId Diagnostic note for the main error message.
4995 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004996 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004997 /// \brief Return the 'x' lvalue part of the source atomic expression.
4998 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004999 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5000 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005001 /// \brief Return the update expression used in calculation of the updated
5002 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5003 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5004 Expr *getUpdateExpr() const { return UpdateExpr; }
5005 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5006 /// false otherwise.
5007 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5008
Alexey Bataevb78ca832015-04-01 03:33:17 +00005009 /// \brief true if the source expression is a postfix unary operation, false
5010 /// if it is a prefix unary operation.
5011 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5012
Alexey Bataev1d160b12015-03-13 12:27:31 +00005013private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005014 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5015 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005016};
5017} // namespace
5018
5019bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5020 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5021 ExprAnalysisErrorCode ErrorFound = NoError;
5022 SourceLocation ErrorLoc, NoteLoc;
5023 SourceRange ErrorRange, NoteRange;
5024 // Allowed constructs are:
5025 // x = x binop expr;
5026 // x = expr binop x;
5027 if (AtomicBinOp->getOpcode() == BO_Assign) {
5028 X = AtomicBinOp->getLHS();
5029 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5030 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5031 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5032 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5033 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005034 Op = AtomicInnerBinOp->getOpcode();
5035 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005036 auto *LHS = AtomicInnerBinOp->getLHS();
5037 auto *RHS = AtomicInnerBinOp->getRHS();
5038 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5039 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5040 /*Canonical=*/true);
5041 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5042 /*Canonical=*/true);
5043 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5044 /*Canonical=*/true);
5045 if (XId == LHSId) {
5046 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005047 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005048 } else if (XId == RHSId) {
5049 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005050 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005051 } else {
5052 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5053 ErrorRange = AtomicInnerBinOp->getSourceRange();
5054 NoteLoc = X->getExprLoc();
5055 NoteRange = X->getSourceRange();
5056 ErrorFound = NotAnUpdateExpression;
5057 }
5058 } else {
5059 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5060 ErrorRange = AtomicInnerBinOp->getSourceRange();
5061 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5062 NoteRange = SourceRange(NoteLoc, NoteLoc);
5063 ErrorFound = NotABinaryOperator;
5064 }
5065 } else {
5066 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5067 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5068 ErrorFound = NotABinaryExpression;
5069 }
5070 } else {
5071 ErrorLoc = AtomicBinOp->getExprLoc();
5072 ErrorRange = AtomicBinOp->getSourceRange();
5073 NoteLoc = AtomicBinOp->getOperatorLoc();
5074 NoteRange = SourceRange(NoteLoc, NoteLoc);
5075 ErrorFound = NotAnAssignmentOp;
5076 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005077 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005078 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5079 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5080 return true;
5081 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005082 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005083 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005084}
5085
5086bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5087 unsigned NoteId) {
5088 ExprAnalysisErrorCode ErrorFound = NoError;
5089 SourceLocation ErrorLoc, NoteLoc;
5090 SourceRange ErrorRange, NoteRange;
5091 // Allowed constructs are:
5092 // x++;
5093 // x--;
5094 // ++x;
5095 // --x;
5096 // x binop= expr;
5097 // x = x binop expr;
5098 // x = expr binop x;
5099 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5100 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5101 if (AtomicBody->getType()->isScalarType() ||
5102 AtomicBody->isInstantiationDependent()) {
5103 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5104 AtomicBody->IgnoreParenImpCasts())) {
5105 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005106 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005107 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005108 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005109 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005110 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005111 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005112 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5113 AtomicBody->IgnoreParenImpCasts())) {
5114 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005115 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005116 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005117 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5118 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005119 // Check for Unary Operation
5120 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005121 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005122 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5123 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005124 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005125 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5126 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005127 } else {
5128 ErrorFound = NotAnUnaryIncDecExpression;
5129 ErrorLoc = AtomicUnaryOp->getExprLoc();
5130 ErrorRange = AtomicUnaryOp->getSourceRange();
5131 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5132 NoteRange = SourceRange(NoteLoc, NoteLoc);
5133 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005134 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005135 ErrorFound = NotABinaryOrUnaryExpression;
5136 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5137 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5138 }
5139 } else {
5140 ErrorFound = NotAScalarType;
5141 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5142 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5143 }
5144 } else {
5145 ErrorFound = NotAnExpression;
5146 NoteLoc = ErrorLoc = S->getLocStart();
5147 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5148 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005149 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005150 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5151 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5152 return true;
5153 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005154 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005155 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005156 // Build an update expression of form 'OpaqueValueExpr(x) binop
5157 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5158 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5159 auto *OVEX = new (SemaRef.getASTContext())
5160 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5161 auto *OVEExpr = new (SemaRef.getASTContext())
5162 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5163 auto Update =
5164 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5165 IsXLHSInRHSPart ? OVEExpr : OVEX);
5166 if (Update.isInvalid())
5167 return true;
5168 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5169 Sema::AA_Casting);
5170 if (Update.isInvalid())
5171 return true;
5172 UpdateExpr = Update.get();
5173 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005174 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005175}
5176
Alexey Bataev0162e452014-07-22 10:10:35 +00005177StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5178 Stmt *AStmt,
5179 SourceLocation StartLoc,
5180 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005181 if (!AStmt)
5182 return StmtError();
5183
David Majnemer9d168222016-08-05 17:44:54 +00005184 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005185 // 1.2.2 OpenMP Language Terminology
5186 // Structured block - An executable statement with a single entry at the
5187 // top and a single exit at the bottom.
5188 // The point of exit cannot be a branch out of the structured block.
5189 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005190 OpenMPClauseKind AtomicKind = OMPC_unknown;
5191 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005192 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005193 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005194 C->getClauseKind() == OMPC_update ||
5195 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005196 if (AtomicKind != OMPC_unknown) {
5197 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5198 << SourceRange(C->getLocStart(), C->getLocEnd());
5199 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5200 << getOpenMPClauseName(AtomicKind);
5201 } else {
5202 AtomicKind = C->getClauseKind();
5203 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005204 }
5205 }
5206 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005207
Alexey Bataev459dec02014-07-24 06:46:57 +00005208 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005209 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5210 Body = EWC->getSubExpr();
5211
Alexey Bataev62cec442014-11-18 10:14:22 +00005212 Expr *X = nullptr;
5213 Expr *V = nullptr;
5214 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005215 Expr *UE = nullptr;
5216 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005217 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005218 // OpenMP [2.12.6, atomic Construct]
5219 // In the next expressions:
5220 // * x and v (as applicable) are both l-value expressions with scalar type.
5221 // * During the execution of an atomic region, multiple syntactic
5222 // occurrences of x must designate the same storage location.
5223 // * Neither of v and expr (as applicable) may access the storage location
5224 // designated by x.
5225 // * Neither of x and expr (as applicable) may access the storage location
5226 // designated by v.
5227 // * expr is an expression with scalar type.
5228 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5229 // * binop, binop=, ++, and -- are not overloaded operators.
5230 // * The expression x binop expr must be numerically equivalent to x binop
5231 // (expr). This requirement is satisfied if the operators in expr have
5232 // precedence greater than binop, or by using parentheses around expr or
5233 // subexpressions of expr.
5234 // * The expression expr binop x must be numerically equivalent to (expr)
5235 // binop x. This requirement is satisfied if the operators in expr have
5236 // precedence equal to or greater than binop, or by using parentheses around
5237 // expr or subexpressions of expr.
5238 // * For forms that allow multiple occurrences of x, the number of times
5239 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005240 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005241 enum {
5242 NotAnExpression,
5243 NotAnAssignmentOp,
5244 NotAScalarType,
5245 NotAnLValue,
5246 NoError
5247 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005248 SourceLocation ErrorLoc, NoteLoc;
5249 SourceRange ErrorRange, NoteRange;
5250 // If clause is read:
5251 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005252 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5253 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005254 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5255 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5256 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5257 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5258 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5259 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5260 if (!X->isLValue() || !V->isLValue()) {
5261 auto NotLValueExpr = X->isLValue() ? V : X;
5262 ErrorFound = NotAnLValue;
5263 ErrorLoc = AtomicBinOp->getExprLoc();
5264 ErrorRange = AtomicBinOp->getSourceRange();
5265 NoteLoc = NotLValueExpr->getExprLoc();
5266 NoteRange = NotLValueExpr->getSourceRange();
5267 }
5268 } else if (!X->isInstantiationDependent() ||
5269 !V->isInstantiationDependent()) {
5270 auto NotScalarExpr =
5271 (X->isInstantiationDependent() || X->getType()->isScalarType())
5272 ? V
5273 : X;
5274 ErrorFound = NotAScalarType;
5275 ErrorLoc = AtomicBinOp->getExprLoc();
5276 ErrorRange = AtomicBinOp->getSourceRange();
5277 NoteLoc = NotScalarExpr->getExprLoc();
5278 NoteRange = NotScalarExpr->getSourceRange();
5279 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005280 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005281 ErrorFound = NotAnAssignmentOp;
5282 ErrorLoc = AtomicBody->getExprLoc();
5283 ErrorRange = AtomicBody->getSourceRange();
5284 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5285 : AtomicBody->getExprLoc();
5286 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5287 : AtomicBody->getSourceRange();
5288 }
5289 } else {
5290 ErrorFound = NotAnExpression;
5291 NoteLoc = ErrorLoc = Body->getLocStart();
5292 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005293 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005294 if (ErrorFound != NoError) {
5295 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5296 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005297 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5298 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005299 return StmtError();
5300 } else if (CurContext->isDependentContext())
5301 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005302 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005303 enum {
5304 NotAnExpression,
5305 NotAnAssignmentOp,
5306 NotAScalarType,
5307 NotAnLValue,
5308 NoError
5309 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005310 SourceLocation ErrorLoc, NoteLoc;
5311 SourceRange ErrorRange, NoteRange;
5312 // If clause is write:
5313 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005314 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5315 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005316 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5317 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005318 X = AtomicBinOp->getLHS();
5319 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005320 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5321 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5322 if (!X->isLValue()) {
5323 ErrorFound = NotAnLValue;
5324 ErrorLoc = AtomicBinOp->getExprLoc();
5325 ErrorRange = AtomicBinOp->getSourceRange();
5326 NoteLoc = X->getExprLoc();
5327 NoteRange = X->getSourceRange();
5328 }
5329 } else if (!X->isInstantiationDependent() ||
5330 !E->isInstantiationDependent()) {
5331 auto NotScalarExpr =
5332 (X->isInstantiationDependent() || X->getType()->isScalarType())
5333 ? E
5334 : X;
5335 ErrorFound = NotAScalarType;
5336 ErrorLoc = AtomicBinOp->getExprLoc();
5337 ErrorRange = AtomicBinOp->getSourceRange();
5338 NoteLoc = NotScalarExpr->getExprLoc();
5339 NoteRange = NotScalarExpr->getSourceRange();
5340 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005341 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005342 ErrorFound = NotAnAssignmentOp;
5343 ErrorLoc = AtomicBody->getExprLoc();
5344 ErrorRange = AtomicBody->getSourceRange();
5345 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5346 : AtomicBody->getExprLoc();
5347 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5348 : AtomicBody->getSourceRange();
5349 }
5350 } else {
5351 ErrorFound = NotAnExpression;
5352 NoteLoc = ErrorLoc = Body->getLocStart();
5353 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005354 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005355 if (ErrorFound != NoError) {
5356 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5357 << ErrorRange;
5358 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5359 << NoteRange;
5360 return StmtError();
5361 } else if (CurContext->isDependentContext())
5362 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005363 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005364 // If clause is update:
5365 // x++;
5366 // x--;
5367 // ++x;
5368 // --x;
5369 // x binop= expr;
5370 // x = x binop expr;
5371 // x = expr binop x;
5372 OpenMPAtomicUpdateChecker Checker(*this);
5373 if (Checker.checkStatement(
5374 Body, (AtomicKind == OMPC_update)
5375 ? diag::err_omp_atomic_update_not_expression_statement
5376 : diag::err_omp_atomic_not_expression_statement,
5377 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005378 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005379 if (!CurContext->isDependentContext()) {
5380 E = Checker.getExpr();
5381 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005382 UE = Checker.getUpdateExpr();
5383 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005384 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005385 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005386 enum {
5387 NotAnAssignmentOp,
5388 NotACompoundStatement,
5389 NotTwoSubstatements,
5390 NotASpecificExpression,
5391 NoError
5392 } ErrorFound = NoError;
5393 SourceLocation ErrorLoc, NoteLoc;
5394 SourceRange ErrorRange, NoteRange;
5395 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5396 // If clause is a capture:
5397 // v = x++;
5398 // v = x--;
5399 // v = ++x;
5400 // v = --x;
5401 // v = x binop= expr;
5402 // v = x = x binop expr;
5403 // v = x = expr binop x;
5404 auto *AtomicBinOp =
5405 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5406 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5407 V = AtomicBinOp->getLHS();
5408 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5409 OpenMPAtomicUpdateChecker Checker(*this);
5410 if (Checker.checkStatement(
5411 Body, diag::err_omp_atomic_capture_not_expression_statement,
5412 diag::note_omp_atomic_update))
5413 return StmtError();
5414 E = Checker.getExpr();
5415 X = Checker.getX();
5416 UE = Checker.getUpdateExpr();
5417 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5418 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005419 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005420 ErrorLoc = AtomicBody->getExprLoc();
5421 ErrorRange = AtomicBody->getSourceRange();
5422 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5423 : AtomicBody->getExprLoc();
5424 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5425 : AtomicBody->getSourceRange();
5426 ErrorFound = NotAnAssignmentOp;
5427 }
5428 if (ErrorFound != NoError) {
5429 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5430 << ErrorRange;
5431 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5432 return StmtError();
5433 } else if (CurContext->isDependentContext()) {
5434 UE = V = E = X = nullptr;
5435 }
5436 } else {
5437 // If clause is a capture:
5438 // { v = x; x = expr; }
5439 // { v = x; x++; }
5440 // { v = x; x--; }
5441 // { v = x; ++x; }
5442 // { v = x; --x; }
5443 // { v = x; x binop= expr; }
5444 // { v = x; x = x binop expr; }
5445 // { v = x; x = expr binop x; }
5446 // { x++; v = x; }
5447 // { x--; v = x; }
5448 // { ++x; v = x; }
5449 // { --x; v = x; }
5450 // { x binop= expr; v = x; }
5451 // { x = x binop expr; v = x; }
5452 // { x = expr binop x; v = x; }
5453 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5454 // Check that this is { expr1; expr2; }
5455 if (CS->size() == 2) {
5456 auto *First = CS->body_front();
5457 auto *Second = CS->body_back();
5458 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5459 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5460 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5461 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5462 // Need to find what subexpression is 'v' and what is 'x'.
5463 OpenMPAtomicUpdateChecker Checker(*this);
5464 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5465 BinaryOperator *BinOp = nullptr;
5466 if (IsUpdateExprFound) {
5467 BinOp = dyn_cast<BinaryOperator>(First);
5468 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5469 }
5470 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5471 // { v = x; x++; }
5472 // { v = x; x--; }
5473 // { v = x; ++x; }
5474 // { v = x; --x; }
5475 // { v = x; x binop= expr; }
5476 // { v = x; x = x binop expr; }
5477 // { v = x; x = expr binop x; }
5478 // Check that the first expression has form v = x.
5479 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5480 llvm::FoldingSetNodeID XId, PossibleXId;
5481 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5482 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5483 IsUpdateExprFound = XId == PossibleXId;
5484 if (IsUpdateExprFound) {
5485 V = BinOp->getLHS();
5486 X = Checker.getX();
5487 E = Checker.getExpr();
5488 UE = Checker.getUpdateExpr();
5489 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005490 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005491 }
5492 }
5493 if (!IsUpdateExprFound) {
5494 IsUpdateExprFound = !Checker.checkStatement(First);
5495 BinOp = nullptr;
5496 if (IsUpdateExprFound) {
5497 BinOp = dyn_cast<BinaryOperator>(Second);
5498 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5499 }
5500 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5501 // { x++; v = x; }
5502 // { x--; v = x; }
5503 // { ++x; v = x; }
5504 // { --x; v = x; }
5505 // { x binop= expr; v = x; }
5506 // { x = x binop expr; v = x; }
5507 // { x = expr binop x; v = x; }
5508 // Check that the second expression has form v = x.
5509 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5510 llvm::FoldingSetNodeID XId, PossibleXId;
5511 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5512 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5513 IsUpdateExprFound = XId == PossibleXId;
5514 if (IsUpdateExprFound) {
5515 V = BinOp->getLHS();
5516 X = Checker.getX();
5517 E = Checker.getExpr();
5518 UE = Checker.getUpdateExpr();
5519 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005520 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005521 }
5522 }
5523 }
5524 if (!IsUpdateExprFound) {
5525 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005526 auto *FirstExpr = dyn_cast<Expr>(First);
5527 auto *SecondExpr = dyn_cast<Expr>(Second);
5528 if (!FirstExpr || !SecondExpr ||
5529 !(FirstExpr->isInstantiationDependent() ||
5530 SecondExpr->isInstantiationDependent())) {
5531 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5532 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005533 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005534 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5535 : First->getLocStart();
5536 NoteRange = ErrorRange = FirstBinOp
5537 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005538 : SourceRange(ErrorLoc, ErrorLoc);
5539 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005540 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5541 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5542 ErrorFound = NotAnAssignmentOp;
5543 NoteLoc = ErrorLoc = SecondBinOp
5544 ? SecondBinOp->getOperatorLoc()
5545 : Second->getLocStart();
5546 NoteRange = ErrorRange =
5547 SecondBinOp ? SecondBinOp->getSourceRange()
5548 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005549 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005550 auto *PossibleXRHSInFirst =
5551 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5552 auto *PossibleXLHSInSecond =
5553 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5554 llvm::FoldingSetNodeID X1Id, X2Id;
5555 PossibleXRHSInFirst->Profile(X1Id, Context,
5556 /*Canonical=*/true);
5557 PossibleXLHSInSecond->Profile(X2Id, Context,
5558 /*Canonical=*/true);
5559 IsUpdateExprFound = X1Id == X2Id;
5560 if (IsUpdateExprFound) {
5561 V = FirstBinOp->getLHS();
5562 X = SecondBinOp->getLHS();
5563 E = SecondBinOp->getRHS();
5564 UE = nullptr;
5565 IsXLHSInRHSPart = false;
5566 IsPostfixUpdate = true;
5567 } else {
5568 ErrorFound = NotASpecificExpression;
5569 ErrorLoc = FirstBinOp->getExprLoc();
5570 ErrorRange = FirstBinOp->getSourceRange();
5571 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5572 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5573 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005574 }
5575 }
5576 }
5577 }
5578 } else {
5579 NoteLoc = ErrorLoc = Body->getLocStart();
5580 NoteRange = ErrorRange =
5581 SourceRange(Body->getLocStart(), Body->getLocStart());
5582 ErrorFound = NotTwoSubstatements;
5583 }
5584 } else {
5585 NoteLoc = ErrorLoc = Body->getLocStart();
5586 NoteRange = ErrorRange =
5587 SourceRange(Body->getLocStart(), Body->getLocStart());
5588 ErrorFound = NotACompoundStatement;
5589 }
5590 if (ErrorFound != NoError) {
5591 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5592 << ErrorRange;
5593 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5594 return StmtError();
5595 } else if (CurContext->isDependentContext()) {
5596 UE = V = E = X = nullptr;
5597 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005598 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005599 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005600
5601 getCurFunction()->setHasBranchProtectedScope();
5602
Alexey Bataev62cec442014-11-18 10:14:22 +00005603 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005604 X, V, E, UE, IsXLHSInRHSPart,
5605 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005606}
5607
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005608StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5609 Stmt *AStmt,
5610 SourceLocation StartLoc,
5611 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005612 if (!AStmt)
5613 return StmtError();
5614
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005615 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5616 // 1.2.2 OpenMP Language Terminology
5617 // Structured block - An executable statement with a single entry at the
5618 // top and a single exit at the bottom.
5619 // The point of exit cannot be a branch out of the structured block.
5620 // longjmp() and throw() must not violate the entry/exit criteria.
5621 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005622
Alexey Bataev13314bf2014-10-09 04:18:56 +00005623 // OpenMP [2.16, Nesting of Regions]
5624 // If specified, a teams construct must be contained within a target
5625 // construct. That target construct must contain no statements or directives
5626 // outside of the teams construct.
5627 if (DSAStack->hasInnerTeamsRegion()) {
5628 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5629 bool OMPTeamsFound = true;
5630 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5631 auto I = CS->body_begin();
5632 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005633 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005634 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5635 OMPTeamsFound = false;
5636 break;
5637 }
5638 ++I;
5639 }
5640 assert(I != CS->body_end() && "Not found statement");
5641 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005642 } else {
5643 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5644 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005645 }
5646 if (!OMPTeamsFound) {
5647 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5648 Diag(DSAStack->getInnerTeamsRegionLoc(),
5649 diag::note_omp_nested_teams_construct_here);
5650 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5651 << isa<OMPExecutableDirective>(S);
5652 return StmtError();
5653 }
5654 }
5655
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005656 getCurFunction()->setHasBranchProtectedScope();
5657
5658 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5659}
5660
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005661StmtResult
5662Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5663 Stmt *AStmt, SourceLocation StartLoc,
5664 SourceLocation EndLoc) {
5665 if (!AStmt)
5666 return StmtError();
5667
5668 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5669 // 1.2.2 OpenMP Language Terminology
5670 // Structured block - An executable statement with a single entry at the
5671 // top and a single exit at the bottom.
5672 // The point of exit cannot be a branch out of the structured block.
5673 // longjmp() and throw() must not violate the entry/exit criteria.
5674 CS->getCapturedDecl()->setNothrow();
5675
5676 getCurFunction()->setHasBranchProtectedScope();
5677
5678 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5679 AStmt);
5680}
5681
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005682StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5683 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5684 SourceLocation EndLoc,
5685 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5686 if (!AStmt)
5687 return StmtError();
5688
5689 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5690 // 1.2.2 OpenMP Language Terminology
5691 // Structured block - An executable statement with a single entry at the
5692 // top and a single exit at the bottom.
5693 // The point of exit cannot be a branch out of the structured block.
5694 // longjmp() and throw() must not violate the entry/exit criteria.
5695 CS->getCapturedDecl()->setNothrow();
5696
5697 OMPLoopDirective::HelperExprs B;
5698 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5699 // define the nested loops number.
5700 unsigned NestedLoopCount =
5701 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5702 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5703 VarsWithImplicitDSA, B);
5704 if (NestedLoopCount == 0)
5705 return StmtError();
5706
5707 assert((CurContext->isDependentContext() || B.builtAll()) &&
5708 "omp target parallel for loop exprs were not built");
5709
5710 if (!CurContext->isDependentContext()) {
5711 // Finalize the clauses that need pre-built expressions for CodeGen.
5712 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005713 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005714 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005715 B.NumIterations, *this, CurScope,
5716 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005717 return StmtError();
5718 }
5719 }
5720
5721 getCurFunction()->setHasBranchProtectedScope();
5722 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5723 NestedLoopCount, Clauses, AStmt,
5724 B, DSAStack->isCancelRegion());
5725}
5726
Samuel Antaodf67fc42016-01-19 19:15:56 +00005727/// \brief Check for existence of a map clause in the list of clauses.
5728static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5729 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5730 I != E; ++I) {
5731 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5732 return true;
5733 }
5734 }
5735
5736 return false;
5737}
5738
Michael Wong65f367f2015-07-21 13:44:28 +00005739StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5740 Stmt *AStmt,
5741 SourceLocation StartLoc,
5742 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005743 if (!AStmt)
5744 return StmtError();
5745
5746 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5747
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005748 // OpenMP [2.10.1, Restrictions, p. 97]
5749 // At least one map clause must appear on the directive.
5750 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005751 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5752 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005753 return StmtError();
5754 }
5755
Michael Wong65f367f2015-07-21 13:44:28 +00005756 getCurFunction()->setHasBranchProtectedScope();
5757
5758 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5759 AStmt);
5760}
5761
Samuel Antaodf67fc42016-01-19 19:15:56 +00005762StmtResult
5763Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5764 SourceLocation StartLoc,
5765 SourceLocation EndLoc) {
5766 // OpenMP [2.10.2, Restrictions, p. 99]
5767 // At least one map clause must appear on the directive.
5768 if (!HasMapClause(Clauses)) {
5769 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5770 << getOpenMPDirectiveName(OMPD_target_enter_data);
5771 return StmtError();
5772 }
5773
5774 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5775 Clauses);
5776}
5777
Samuel Antao72590762016-01-19 20:04:50 +00005778StmtResult
5779Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5780 SourceLocation StartLoc,
5781 SourceLocation EndLoc) {
5782 // OpenMP [2.10.3, Restrictions, p. 102]
5783 // At least one map clause must appear on the directive.
5784 if (!HasMapClause(Clauses)) {
5785 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5786 << getOpenMPDirectiveName(OMPD_target_exit_data);
5787 return StmtError();
5788 }
5789
5790 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5791}
5792
Samuel Antao686c70c2016-05-26 17:30:50 +00005793StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5794 SourceLocation StartLoc,
5795 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005796 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005797 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005798 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005799 seenMotionClause = true;
5800 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005801 if (!seenMotionClause) {
5802 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5803 return StmtError();
5804 }
5805 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5806}
5807
Alexey Bataev13314bf2014-10-09 04:18:56 +00005808StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5809 Stmt *AStmt, SourceLocation StartLoc,
5810 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005811 if (!AStmt)
5812 return StmtError();
5813
Alexey Bataev13314bf2014-10-09 04:18:56 +00005814 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5815 // 1.2.2 OpenMP Language Terminology
5816 // Structured block - An executable statement with a single entry at the
5817 // top and a single exit at the bottom.
5818 // The point of exit cannot be a branch out of the structured block.
5819 // longjmp() and throw() must not violate the entry/exit criteria.
5820 CS->getCapturedDecl()->setNothrow();
5821
5822 getCurFunction()->setHasBranchProtectedScope();
5823
5824 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5825}
5826
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005827StmtResult
5828Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5829 SourceLocation EndLoc,
5830 OpenMPDirectiveKind CancelRegion) {
5831 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5832 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5833 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5834 << getOpenMPDirectiveName(CancelRegion);
5835 return StmtError();
5836 }
5837 if (DSAStack->isParentNowaitRegion()) {
5838 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5839 return StmtError();
5840 }
5841 if (DSAStack->isParentOrderedRegion()) {
5842 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5843 return StmtError();
5844 }
5845 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5846 CancelRegion);
5847}
5848
Alexey Bataev87933c72015-09-18 08:07:34 +00005849StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5850 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005851 SourceLocation EndLoc,
5852 OpenMPDirectiveKind CancelRegion) {
5853 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5854 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5855 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5856 << getOpenMPDirectiveName(CancelRegion);
5857 return StmtError();
5858 }
5859 if (DSAStack->isParentNowaitRegion()) {
5860 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5861 return StmtError();
5862 }
5863 if (DSAStack->isParentOrderedRegion()) {
5864 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5865 return StmtError();
5866 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005867 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005868 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5869 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005870}
5871
Alexey Bataev382967a2015-12-08 12:06:20 +00005872static bool checkGrainsizeNumTasksClauses(Sema &S,
5873 ArrayRef<OMPClause *> Clauses) {
5874 OMPClause *PrevClause = nullptr;
5875 bool ErrorFound = false;
5876 for (auto *C : Clauses) {
5877 if (C->getClauseKind() == OMPC_grainsize ||
5878 C->getClauseKind() == OMPC_num_tasks) {
5879 if (!PrevClause)
5880 PrevClause = C;
5881 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5882 S.Diag(C->getLocStart(),
5883 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5884 << getOpenMPClauseName(C->getClauseKind())
5885 << getOpenMPClauseName(PrevClause->getClauseKind());
5886 S.Diag(PrevClause->getLocStart(),
5887 diag::note_omp_previous_grainsize_num_tasks)
5888 << getOpenMPClauseName(PrevClause->getClauseKind());
5889 ErrorFound = true;
5890 }
5891 }
5892 }
5893 return ErrorFound;
5894}
5895
Alexey Bataev49f6e782015-12-01 04:18:41 +00005896StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5897 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5898 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005899 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005900 if (!AStmt)
5901 return StmtError();
5902
5903 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5904 OMPLoopDirective::HelperExprs B;
5905 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5906 // define the nested loops number.
5907 unsigned NestedLoopCount =
5908 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005909 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005910 VarsWithImplicitDSA, B);
5911 if (NestedLoopCount == 0)
5912 return StmtError();
5913
5914 assert((CurContext->isDependentContext() || B.builtAll()) &&
5915 "omp for loop exprs were not built");
5916
Alexey Bataev382967a2015-12-08 12:06:20 +00005917 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5918 // The grainsize clause and num_tasks clause are mutually exclusive and may
5919 // not appear on the same taskloop directive.
5920 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5921 return StmtError();
5922
Alexey Bataev49f6e782015-12-01 04:18:41 +00005923 getCurFunction()->setHasBranchProtectedScope();
5924 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5925 NestedLoopCount, Clauses, AStmt, B);
5926}
5927
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005928StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5929 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5930 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005931 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005932 if (!AStmt)
5933 return StmtError();
5934
5935 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5936 OMPLoopDirective::HelperExprs B;
5937 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5938 // define the nested loops number.
5939 unsigned NestedLoopCount =
5940 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5941 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5942 VarsWithImplicitDSA, B);
5943 if (NestedLoopCount == 0)
5944 return StmtError();
5945
5946 assert((CurContext->isDependentContext() || B.builtAll()) &&
5947 "omp for loop exprs were not built");
5948
Alexey Bataev5a3af132016-03-29 08:58:54 +00005949 if (!CurContext->isDependentContext()) {
5950 // Finalize the clauses that need pre-built expressions for CodeGen.
5951 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005952 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005953 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005954 B.NumIterations, *this, CurScope,
5955 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005956 return StmtError();
5957 }
5958 }
5959
Alexey Bataev382967a2015-12-08 12:06:20 +00005960 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5961 // The grainsize clause and num_tasks clause are mutually exclusive and may
5962 // not appear on the same taskloop directive.
5963 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5964 return StmtError();
5965
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005966 getCurFunction()->setHasBranchProtectedScope();
5967 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5968 NestedLoopCount, Clauses, AStmt, B);
5969}
5970
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005971StmtResult Sema::ActOnOpenMPDistributeDirective(
5972 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5973 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005974 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005975 if (!AStmt)
5976 return StmtError();
5977
5978 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5979 OMPLoopDirective::HelperExprs B;
5980 // In presence of clause 'collapse' with number of loops, it will
5981 // define the nested loops number.
5982 unsigned NestedLoopCount =
5983 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5984 nullptr /*ordered not a clause on distribute*/, AStmt,
5985 *this, *DSAStack, VarsWithImplicitDSA, B);
5986 if (NestedLoopCount == 0)
5987 return StmtError();
5988
5989 assert((CurContext->isDependentContext() || B.builtAll()) &&
5990 "omp for loop exprs were not built");
5991
5992 getCurFunction()->setHasBranchProtectedScope();
5993 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5994 NestedLoopCount, Clauses, AStmt, B);
5995}
5996
Carlo Bertolli9925f152016-06-27 14:55:37 +00005997StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5998 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5999 SourceLocation EndLoc,
6000 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6001 if (!AStmt)
6002 return StmtError();
6003
6004 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6005 // 1.2.2 OpenMP Language Terminology
6006 // Structured block - An executable statement with a single entry at the
6007 // top and a single exit at the bottom.
6008 // The point of exit cannot be a branch out of the structured block.
6009 // longjmp() and throw() must not violate the entry/exit criteria.
6010 CS->getCapturedDecl()->setNothrow();
6011
6012 OMPLoopDirective::HelperExprs B;
6013 // In presence of clause 'collapse' with number of loops, it will
6014 // define the nested loops number.
6015 unsigned NestedLoopCount = CheckOpenMPLoop(
6016 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6017 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6018 VarsWithImplicitDSA, B);
6019 if (NestedLoopCount == 0)
6020 return StmtError();
6021
6022 assert((CurContext->isDependentContext() || B.builtAll()) &&
6023 "omp for loop exprs were not built");
6024
6025 getCurFunction()->setHasBranchProtectedScope();
6026 return OMPDistributeParallelForDirective::Create(
6027 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6028}
6029
Kelvin Li4a39add2016-07-05 05:00:15 +00006030StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6031 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6032 SourceLocation EndLoc,
6033 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6034 if (!AStmt)
6035 return StmtError();
6036
6037 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6038 // 1.2.2 OpenMP Language Terminology
6039 // Structured block - An executable statement with a single entry at the
6040 // top and a single exit at the bottom.
6041 // The point of exit cannot be a branch out of the structured block.
6042 // longjmp() and throw() must not violate the entry/exit criteria.
6043 CS->getCapturedDecl()->setNothrow();
6044
6045 OMPLoopDirective::HelperExprs B;
6046 // In presence of clause 'collapse' with number of loops, it will
6047 // define the nested loops number.
6048 unsigned NestedLoopCount = CheckOpenMPLoop(
6049 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6050 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6051 VarsWithImplicitDSA, B);
6052 if (NestedLoopCount == 0)
6053 return StmtError();
6054
6055 assert((CurContext->isDependentContext() || B.builtAll()) &&
6056 "omp for loop exprs were not built");
6057
Kelvin Lic5609492016-07-15 04:39:07 +00006058 if (checkSimdlenSafelenSpecified(*this, Clauses))
6059 return StmtError();
6060
Kelvin Li4a39add2016-07-05 05:00:15 +00006061 getCurFunction()->setHasBranchProtectedScope();
6062 return OMPDistributeParallelForSimdDirective::Create(
6063 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6064}
6065
Kelvin Li787f3fc2016-07-06 04:45:38 +00006066StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6067 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6068 SourceLocation EndLoc,
6069 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6070 if (!AStmt)
6071 return StmtError();
6072
6073 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6074 // 1.2.2 OpenMP Language Terminology
6075 // Structured block - An executable statement with a single entry at the
6076 // top and a single exit at the bottom.
6077 // The point of exit cannot be a branch out of the structured block.
6078 // longjmp() and throw() must not violate the entry/exit criteria.
6079 CS->getCapturedDecl()->setNothrow();
6080
6081 OMPLoopDirective::HelperExprs B;
6082 // In presence of clause 'collapse' with number of loops, it will
6083 // define the nested loops number.
6084 unsigned NestedLoopCount =
6085 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6086 nullptr /*ordered not a clause on distribute*/, AStmt,
6087 *this, *DSAStack, VarsWithImplicitDSA, B);
6088 if (NestedLoopCount == 0)
6089 return StmtError();
6090
6091 assert((CurContext->isDependentContext() || B.builtAll()) &&
6092 "omp for loop exprs were not built");
6093
Kelvin Lic5609492016-07-15 04:39:07 +00006094 if (checkSimdlenSafelenSpecified(*this, Clauses))
6095 return StmtError();
6096
Kelvin Li787f3fc2016-07-06 04:45:38 +00006097 getCurFunction()->setHasBranchProtectedScope();
6098 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6099 NestedLoopCount, Clauses, AStmt, B);
6100}
6101
Kelvin Lia579b912016-07-14 02:54:56 +00006102StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6103 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6104 SourceLocation EndLoc,
6105 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6106 if (!AStmt)
6107 return StmtError();
6108
6109 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6110 // 1.2.2 OpenMP Language Terminology
6111 // Structured block - An executable statement with a single entry at the
6112 // top and a single exit at the bottom.
6113 // The point of exit cannot be a branch out of the structured block.
6114 // longjmp() and throw() must not violate the entry/exit criteria.
6115 CS->getCapturedDecl()->setNothrow();
6116
6117 OMPLoopDirective::HelperExprs B;
6118 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6119 // define the nested loops number.
6120 unsigned NestedLoopCount = CheckOpenMPLoop(
6121 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6122 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6123 VarsWithImplicitDSA, B);
6124 if (NestedLoopCount == 0)
6125 return StmtError();
6126
6127 assert((CurContext->isDependentContext() || B.builtAll()) &&
6128 "omp target parallel for simd loop exprs were not built");
6129
6130 if (!CurContext->isDependentContext()) {
6131 // Finalize the clauses that need pre-built expressions for CodeGen.
6132 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006133 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006134 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6135 B.NumIterations, *this, CurScope,
6136 DSAStack))
6137 return StmtError();
6138 }
6139 }
Kelvin Lic5609492016-07-15 04:39:07 +00006140 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006141 return StmtError();
6142
6143 getCurFunction()->setHasBranchProtectedScope();
6144 return OMPTargetParallelForSimdDirective::Create(
6145 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6146}
6147
Kelvin Li986330c2016-07-20 22:57:10 +00006148StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6149 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6150 SourceLocation EndLoc,
6151 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6152 if (!AStmt)
6153 return StmtError();
6154
6155 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6156 // 1.2.2 OpenMP Language Terminology
6157 // Structured block - An executable statement with a single entry at the
6158 // top and a single exit at the bottom.
6159 // The point of exit cannot be a branch out of the structured block.
6160 // longjmp() and throw() must not violate the entry/exit criteria.
6161 CS->getCapturedDecl()->setNothrow();
6162
6163 OMPLoopDirective::HelperExprs B;
6164 // In presence of clause 'collapse' with number of loops, it will define the
6165 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006166 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006167 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6168 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6169 VarsWithImplicitDSA, B);
6170 if (NestedLoopCount == 0)
6171 return StmtError();
6172
6173 assert((CurContext->isDependentContext() || B.builtAll()) &&
6174 "omp target simd loop exprs were not built");
6175
6176 if (!CurContext->isDependentContext()) {
6177 // Finalize the clauses that need pre-built expressions for CodeGen.
6178 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006179 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006180 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6181 B.NumIterations, *this, CurScope,
6182 DSAStack))
6183 return StmtError();
6184 }
6185 }
6186
6187 if (checkSimdlenSafelenSpecified(*this, Clauses))
6188 return StmtError();
6189
6190 getCurFunction()->setHasBranchProtectedScope();
6191 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6192 NestedLoopCount, Clauses, AStmt, B);
6193}
6194
Kelvin Li02532872016-08-05 14:37:37 +00006195StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6196 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6197 SourceLocation EndLoc,
6198 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6199 if (!AStmt)
6200 return StmtError();
6201
6202 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6203 // 1.2.2 OpenMP Language Terminology
6204 // Structured block - An executable statement with a single entry at the
6205 // top and a single exit at the bottom.
6206 // The point of exit cannot be a branch out of the structured block.
6207 // longjmp() and throw() must not violate the entry/exit criteria.
6208 CS->getCapturedDecl()->setNothrow();
6209
6210 OMPLoopDirective::HelperExprs B;
6211 // In presence of clause 'collapse' with number of loops, it will
6212 // define the nested loops number.
6213 unsigned NestedLoopCount =
6214 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6215 nullptr /*ordered not a clause on distribute*/, AStmt,
6216 *this, *DSAStack, VarsWithImplicitDSA, B);
6217 if (NestedLoopCount == 0)
6218 return StmtError();
6219
6220 assert((CurContext->isDependentContext() || B.builtAll()) &&
6221 "omp teams distribute loop exprs were not built");
6222
6223 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006224 return OMPTeamsDistributeDirective::Create(
6225 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006226}
6227
Kelvin Li4e325f72016-10-25 12:50:55 +00006228StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6229 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6230 SourceLocation EndLoc,
6231 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6232 if (!AStmt)
6233 return StmtError();
6234
6235 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6236 // 1.2.2 OpenMP Language Terminology
6237 // Structured block - An executable statement with a single entry at the
6238 // top and a single exit at the bottom.
6239 // The point of exit cannot be a branch out of the structured block.
6240 // longjmp() and throw() must not violate the entry/exit criteria.
6241 CS->getCapturedDecl()->setNothrow();
6242
6243 OMPLoopDirective::HelperExprs B;
6244 // In presence of clause 'collapse' with number of loops, it will
6245 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006246 unsigned NestedLoopCount = CheckOpenMPLoop(
6247 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6248 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6249 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006250
6251 if (NestedLoopCount == 0)
6252 return StmtError();
6253
6254 assert((CurContext->isDependentContext() || B.builtAll()) &&
6255 "omp teams distribute simd loop exprs were not built");
6256
6257 if (!CurContext->isDependentContext()) {
6258 // Finalize the clauses that need pre-built expressions for CodeGen.
6259 for (auto C : Clauses) {
6260 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6261 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6262 B.NumIterations, *this, CurScope,
6263 DSAStack))
6264 return StmtError();
6265 }
6266 }
6267
6268 if (checkSimdlenSafelenSpecified(*this, Clauses))
6269 return StmtError();
6270
6271 getCurFunction()->setHasBranchProtectedScope();
6272 return OMPTeamsDistributeSimdDirective::Create(
6273 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6274}
6275
Kelvin Li579e41c2016-11-30 23:51:03 +00006276StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6277 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6278 SourceLocation EndLoc,
6279 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6280 if (!AStmt)
6281 return StmtError();
6282
6283 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6284 // 1.2.2 OpenMP Language Terminology
6285 // Structured block - An executable statement with a single entry at the
6286 // top and a single exit at the bottom.
6287 // The point of exit cannot be a branch out of the structured block.
6288 // longjmp() and throw() must not violate the entry/exit criteria.
6289 CS->getCapturedDecl()->setNothrow();
6290
6291 OMPLoopDirective::HelperExprs B;
6292 // In presence of clause 'collapse' with number of loops, it will
6293 // define the nested loops number.
6294 auto NestedLoopCount = CheckOpenMPLoop(
6295 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6296 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6297 VarsWithImplicitDSA, B);
6298
6299 if (NestedLoopCount == 0)
6300 return StmtError();
6301
6302 assert((CurContext->isDependentContext() || B.builtAll()) &&
6303 "omp for loop exprs were not built");
6304
6305 if (!CurContext->isDependentContext()) {
6306 // Finalize the clauses that need pre-built expressions for CodeGen.
6307 for (auto C : Clauses) {
6308 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6309 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6310 B.NumIterations, *this, CurScope,
6311 DSAStack))
6312 return StmtError();
6313 }
6314 }
6315
6316 if (checkSimdlenSafelenSpecified(*this, Clauses))
6317 return StmtError();
6318
6319 getCurFunction()->setHasBranchProtectedScope();
6320 return OMPTeamsDistributeParallelForSimdDirective::Create(
6321 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6322}
6323
Kelvin Li7ade93f2016-12-09 03:24:30 +00006324StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6325 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6326 SourceLocation EndLoc,
6327 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6328 if (!AStmt)
6329 return StmtError();
6330
6331 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6332 // 1.2.2 OpenMP Language Terminology
6333 // Structured block - An executable statement with a single entry at the
6334 // top and a single exit at the bottom.
6335 // The point of exit cannot be a branch out of the structured block.
6336 // longjmp() and throw() must not violate the entry/exit criteria.
6337 CS->getCapturedDecl()->setNothrow();
6338
6339 OMPLoopDirective::HelperExprs B;
6340 // In presence of clause 'collapse' with number of loops, it will
6341 // define the nested loops number.
6342 unsigned NestedLoopCount = CheckOpenMPLoop(
6343 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6344 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6345 VarsWithImplicitDSA, B);
6346
6347 if (NestedLoopCount == 0)
6348 return StmtError();
6349
6350 assert((CurContext->isDependentContext() || B.builtAll()) &&
6351 "omp for loop exprs were not built");
6352
6353 if (!CurContext->isDependentContext()) {
6354 // Finalize the clauses that need pre-built expressions for CodeGen.
6355 for (auto C : Clauses) {
6356 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6357 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6358 B.NumIterations, *this, CurScope,
6359 DSAStack))
6360 return StmtError();
6361 }
6362 }
6363
6364 getCurFunction()->setHasBranchProtectedScope();
6365 return OMPTeamsDistributeParallelForDirective::Create(
6366 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6367}
6368
Kelvin Libf594a52016-12-17 05:48:59 +00006369StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6370 Stmt *AStmt,
6371 SourceLocation StartLoc,
6372 SourceLocation EndLoc) {
6373 if (!AStmt)
6374 return StmtError();
6375
6376 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6377 // 1.2.2 OpenMP Language Terminology
6378 // Structured block - An executable statement with a single entry at the
6379 // top and a single exit at the bottom.
6380 // The point of exit cannot be a branch out of the structured block.
6381 // longjmp() and throw() must not violate the entry/exit criteria.
6382 CS->getCapturedDecl()->setNothrow();
6383
6384 getCurFunction()->setHasBranchProtectedScope();
6385
6386 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6387 AStmt);
6388}
6389
Kelvin Li83c451e2016-12-25 04:52:54 +00006390StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6391 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6392 SourceLocation EndLoc,
6393 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6394 if (!AStmt)
6395 return StmtError();
6396
6397 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6398 // 1.2.2 OpenMP Language Terminology
6399 // Structured block - An executable statement with a single entry at the
6400 // top and a single exit at the bottom.
6401 // The point of exit cannot be a branch out of the structured block.
6402 // longjmp() and throw() must not violate the entry/exit criteria.
6403 CS->getCapturedDecl()->setNothrow();
6404
6405 OMPLoopDirective::HelperExprs B;
6406 // In presence of clause 'collapse' with number of loops, it will
6407 // define the nested loops number.
6408 auto NestedLoopCount = CheckOpenMPLoop(
6409 OMPD_target_teams_distribute,
6410 getCollapseNumberExpr(Clauses),
6411 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6412 VarsWithImplicitDSA, B);
6413 if (NestedLoopCount == 0)
6414 return StmtError();
6415
6416 assert((CurContext->isDependentContext() || B.builtAll()) &&
6417 "omp target teams distribute loop exprs were not built");
6418
6419 getCurFunction()->setHasBranchProtectedScope();
6420 return OMPTargetTeamsDistributeDirective::Create(
6421 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6422}
6423
Kelvin Li80e8f562016-12-29 22:16:30 +00006424StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6425 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6426 SourceLocation EndLoc,
6427 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6428 if (!AStmt)
6429 return StmtError();
6430
6431 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6432 // 1.2.2 OpenMP Language Terminology
6433 // Structured block - An executable statement with a single entry at the
6434 // top and a single exit at the bottom.
6435 // The point of exit cannot be a branch out of the structured block.
6436 // longjmp() and throw() must not violate the entry/exit criteria.
6437 CS->getCapturedDecl()->setNothrow();
6438
6439 OMPLoopDirective::HelperExprs B;
6440 // In presence of clause 'collapse' with number of loops, it will
6441 // define the nested loops number.
6442 auto NestedLoopCount = CheckOpenMPLoop(
6443 OMPD_target_teams_distribute_parallel_for,
6444 getCollapseNumberExpr(Clauses),
6445 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6446 VarsWithImplicitDSA, B);
6447 if (NestedLoopCount == 0)
6448 return StmtError();
6449
6450 assert((CurContext->isDependentContext() || B.builtAll()) &&
6451 "omp target teams distribute parallel for loop exprs were not built");
6452
6453 if (!CurContext->isDependentContext()) {
6454 // Finalize the clauses that need pre-built expressions for CodeGen.
6455 for (auto C : Clauses) {
6456 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6457 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6458 B.NumIterations, *this, CurScope,
6459 DSAStack))
6460 return StmtError();
6461 }
6462 }
6463
6464 getCurFunction()->setHasBranchProtectedScope();
6465 return OMPTargetTeamsDistributeParallelForDirective::Create(
6466 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6467}
6468
Kelvin Li1851df52017-01-03 05:23:48 +00006469StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6470 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6471 SourceLocation EndLoc,
6472 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6473 if (!AStmt)
6474 return StmtError();
6475
6476 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6477 // 1.2.2 OpenMP Language Terminology
6478 // Structured block - An executable statement with a single entry at the
6479 // top and a single exit at the bottom.
6480 // The point of exit cannot be a branch out of the structured block.
6481 // longjmp() and throw() must not violate the entry/exit criteria.
6482 CS->getCapturedDecl()->setNothrow();
6483
6484 OMPLoopDirective::HelperExprs B;
6485 // In presence of clause 'collapse' with number of loops, it will
6486 // define the nested loops number.
6487 auto NestedLoopCount = CheckOpenMPLoop(
6488 OMPD_target_teams_distribute_parallel_for_simd,
6489 getCollapseNumberExpr(Clauses),
6490 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6491 VarsWithImplicitDSA, B);
6492 if (NestedLoopCount == 0)
6493 return StmtError();
6494
6495 assert((CurContext->isDependentContext() || B.builtAll()) &&
6496 "omp target teams distribute parallel for simd loop exprs were not "
6497 "built");
6498
6499 if (!CurContext->isDependentContext()) {
6500 // Finalize the clauses that need pre-built expressions for CodeGen.
6501 for (auto C : Clauses) {
6502 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6503 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6504 B.NumIterations, *this, CurScope,
6505 DSAStack))
6506 return StmtError();
6507 }
6508 }
6509
6510 getCurFunction()->setHasBranchProtectedScope();
6511 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6512 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6513}
6514
Kelvin Lida681182017-01-10 18:08:18 +00006515StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6516 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6517 SourceLocation EndLoc,
6518 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6519 if (!AStmt)
6520 return StmtError();
6521
6522 auto *CS = cast<CapturedStmt>(AStmt);
6523 // 1.2.2 OpenMP Language Terminology
6524 // Structured block - An executable statement with a single entry at the
6525 // top and a single exit at the bottom.
6526 // The point of exit cannot be a branch out of the structured block.
6527 // longjmp() and throw() must not violate the entry/exit criteria.
6528 CS->getCapturedDecl()->setNothrow();
6529
6530 OMPLoopDirective::HelperExprs B;
6531 // In presence of clause 'collapse' with number of loops, it will
6532 // define the nested loops number.
6533 auto NestedLoopCount = CheckOpenMPLoop(
6534 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6535 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6536 VarsWithImplicitDSA, B);
6537 if (NestedLoopCount == 0)
6538 return StmtError();
6539
6540 assert((CurContext->isDependentContext() || B.builtAll()) &&
6541 "omp target teams distribute simd loop exprs were not built");
6542
6543 getCurFunction()->setHasBranchProtectedScope();
6544 return OMPTargetTeamsDistributeSimdDirective::Create(
6545 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6546}
6547
Alexey Bataeved09d242014-05-28 05:53:51 +00006548OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006549 SourceLocation StartLoc,
6550 SourceLocation LParenLoc,
6551 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006552 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006553 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006554 case OMPC_final:
6555 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6556 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006557 case OMPC_num_threads:
6558 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6559 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006560 case OMPC_safelen:
6561 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6562 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006563 case OMPC_simdlen:
6564 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6565 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006566 case OMPC_collapse:
6567 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6568 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006569 case OMPC_ordered:
6570 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6571 break;
Michael Wonge710d542015-08-07 16:16:36 +00006572 case OMPC_device:
6573 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6574 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006575 case OMPC_num_teams:
6576 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6577 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006578 case OMPC_thread_limit:
6579 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6580 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006581 case OMPC_priority:
6582 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6583 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006584 case OMPC_grainsize:
6585 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6586 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006587 case OMPC_num_tasks:
6588 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6589 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006590 case OMPC_hint:
6591 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6592 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006593 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006594 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006595 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006596 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006597 case OMPC_private:
6598 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006599 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006600 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006601 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006602 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006603 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006604 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006605 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006606 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006607 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006608 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006609 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006610 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006611 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006612 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006613 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006614 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006615 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006616 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006617 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006618 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006619 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006620 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006621 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006622 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006623 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006624 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006625 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006626 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006627 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006628 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006629 llvm_unreachable("Clause is not allowed.");
6630 }
6631 return Res;
6632}
6633
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006634// An OpenMP directive such as 'target parallel' has two captured regions:
6635// for the 'target' and 'parallel' respectively. This function returns
6636// the region in which to capture expressions associated with a clause.
6637// A return value of OMPD_unknown signifies that the expression should not
6638// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006639static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
6640 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
6641 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006642 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6643
6644 switch (CKind) {
6645 case OMPC_if:
6646 switch (DKind) {
6647 case OMPD_target_parallel:
6648 // If this clause applies to the nested 'parallel' region, capture within
6649 // the 'target' region, otherwise do not capture.
6650 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6651 CaptureRegion = OMPD_target;
6652 break;
6653 case OMPD_cancel:
6654 case OMPD_parallel:
6655 case OMPD_parallel_sections:
6656 case OMPD_parallel_for:
6657 case OMPD_parallel_for_simd:
6658 case OMPD_target:
6659 case OMPD_target_simd:
6660 case OMPD_target_parallel_for:
6661 case OMPD_target_parallel_for_simd:
6662 case OMPD_target_teams:
6663 case OMPD_target_teams_distribute:
6664 case OMPD_target_teams_distribute_simd:
6665 case OMPD_target_teams_distribute_parallel_for:
6666 case OMPD_target_teams_distribute_parallel_for_simd:
6667 case OMPD_teams_distribute_parallel_for:
6668 case OMPD_teams_distribute_parallel_for_simd:
6669 case OMPD_distribute_parallel_for:
6670 case OMPD_distribute_parallel_for_simd:
6671 case OMPD_task:
6672 case OMPD_taskloop:
6673 case OMPD_taskloop_simd:
6674 case OMPD_target_data:
6675 case OMPD_target_enter_data:
6676 case OMPD_target_exit_data:
6677 case OMPD_target_update:
6678 // Do not capture if-clause expressions.
6679 break;
6680 case OMPD_threadprivate:
6681 case OMPD_taskyield:
6682 case OMPD_barrier:
6683 case OMPD_taskwait:
6684 case OMPD_cancellation_point:
6685 case OMPD_flush:
6686 case OMPD_declare_reduction:
6687 case OMPD_declare_simd:
6688 case OMPD_declare_target:
6689 case OMPD_end_declare_target:
6690 case OMPD_teams:
6691 case OMPD_simd:
6692 case OMPD_for:
6693 case OMPD_for_simd:
6694 case OMPD_sections:
6695 case OMPD_section:
6696 case OMPD_single:
6697 case OMPD_master:
6698 case OMPD_critical:
6699 case OMPD_taskgroup:
6700 case OMPD_distribute:
6701 case OMPD_ordered:
6702 case OMPD_atomic:
6703 case OMPD_distribute_simd:
6704 case OMPD_teams_distribute:
6705 case OMPD_teams_distribute_simd:
6706 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6707 case OMPD_unknown:
6708 llvm_unreachable("Unknown OpenMP directive");
6709 }
6710 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006711 case OMPC_num_threads:
6712 switch (DKind) {
6713 case OMPD_target_parallel:
6714 CaptureRegion = OMPD_target;
6715 break;
6716 case OMPD_cancel:
6717 case OMPD_parallel:
6718 case OMPD_parallel_sections:
6719 case OMPD_parallel_for:
6720 case OMPD_parallel_for_simd:
6721 case OMPD_target:
6722 case OMPD_target_simd:
6723 case OMPD_target_parallel_for:
6724 case OMPD_target_parallel_for_simd:
6725 case OMPD_target_teams:
6726 case OMPD_target_teams_distribute:
6727 case OMPD_target_teams_distribute_simd:
6728 case OMPD_target_teams_distribute_parallel_for:
6729 case OMPD_target_teams_distribute_parallel_for_simd:
6730 case OMPD_teams_distribute_parallel_for:
6731 case OMPD_teams_distribute_parallel_for_simd:
6732 case OMPD_distribute_parallel_for:
6733 case OMPD_distribute_parallel_for_simd:
6734 case OMPD_task:
6735 case OMPD_taskloop:
6736 case OMPD_taskloop_simd:
6737 case OMPD_target_data:
6738 case OMPD_target_enter_data:
6739 case OMPD_target_exit_data:
6740 case OMPD_target_update:
6741 // Do not capture num_threads-clause expressions.
6742 break;
6743 case OMPD_threadprivate:
6744 case OMPD_taskyield:
6745 case OMPD_barrier:
6746 case OMPD_taskwait:
6747 case OMPD_cancellation_point:
6748 case OMPD_flush:
6749 case OMPD_declare_reduction:
6750 case OMPD_declare_simd:
6751 case OMPD_declare_target:
6752 case OMPD_end_declare_target:
6753 case OMPD_teams:
6754 case OMPD_simd:
6755 case OMPD_for:
6756 case OMPD_for_simd:
6757 case OMPD_sections:
6758 case OMPD_section:
6759 case OMPD_single:
6760 case OMPD_master:
6761 case OMPD_critical:
6762 case OMPD_taskgroup:
6763 case OMPD_distribute:
6764 case OMPD_ordered:
6765 case OMPD_atomic:
6766 case OMPD_distribute_simd:
6767 case OMPD_teams_distribute:
6768 case OMPD_teams_distribute_simd:
6769 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
6770 case OMPD_unknown:
6771 llvm_unreachable("Unknown OpenMP directive");
6772 }
6773 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00006774 case OMPC_num_teams:
6775 switch (DKind) {
6776 case OMPD_target_teams:
6777 CaptureRegion = OMPD_target;
6778 break;
6779 case OMPD_cancel:
6780 case OMPD_parallel:
6781 case OMPD_parallel_sections:
6782 case OMPD_parallel_for:
6783 case OMPD_parallel_for_simd:
6784 case OMPD_target:
6785 case OMPD_target_simd:
6786 case OMPD_target_parallel:
6787 case OMPD_target_parallel_for:
6788 case OMPD_target_parallel_for_simd:
6789 case OMPD_target_teams_distribute:
6790 case OMPD_target_teams_distribute_simd:
6791 case OMPD_target_teams_distribute_parallel_for:
6792 case OMPD_target_teams_distribute_parallel_for_simd:
6793 case OMPD_teams_distribute_parallel_for:
6794 case OMPD_teams_distribute_parallel_for_simd:
6795 case OMPD_distribute_parallel_for:
6796 case OMPD_distribute_parallel_for_simd:
6797 case OMPD_task:
6798 case OMPD_taskloop:
6799 case OMPD_taskloop_simd:
6800 case OMPD_target_data:
6801 case OMPD_target_enter_data:
6802 case OMPD_target_exit_data:
6803 case OMPD_target_update:
6804 case OMPD_teams:
6805 case OMPD_teams_distribute:
6806 case OMPD_teams_distribute_simd:
6807 // Do not capture num_teams-clause expressions.
6808 break;
6809 case OMPD_threadprivate:
6810 case OMPD_taskyield:
6811 case OMPD_barrier:
6812 case OMPD_taskwait:
6813 case OMPD_cancellation_point:
6814 case OMPD_flush:
6815 case OMPD_declare_reduction:
6816 case OMPD_declare_simd:
6817 case OMPD_declare_target:
6818 case OMPD_end_declare_target:
6819 case OMPD_simd:
6820 case OMPD_for:
6821 case OMPD_for_simd:
6822 case OMPD_sections:
6823 case OMPD_section:
6824 case OMPD_single:
6825 case OMPD_master:
6826 case OMPD_critical:
6827 case OMPD_taskgroup:
6828 case OMPD_distribute:
6829 case OMPD_ordered:
6830 case OMPD_atomic:
6831 case OMPD_distribute_simd:
6832 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
6833 case OMPD_unknown:
6834 llvm_unreachable("Unknown OpenMP directive");
6835 }
6836 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006837 case OMPC_schedule:
6838 case OMPC_dist_schedule:
6839 case OMPC_firstprivate:
6840 case OMPC_lastprivate:
6841 case OMPC_reduction:
6842 case OMPC_linear:
6843 case OMPC_default:
6844 case OMPC_proc_bind:
6845 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006846 case OMPC_safelen:
6847 case OMPC_simdlen:
6848 case OMPC_collapse:
6849 case OMPC_private:
6850 case OMPC_shared:
6851 case OMPC_aligned:
6852 case OMPC_copyin:
6853 case OMPC_copyprivate:
6854 case OMPC_ordered:
6855 case OMPC_nowait:
6856 case OMPC_untied:
6857 case OMPC_mergeable:
6858 case OMPC_threadprivate:
6859 case OMPC_flush:
6860 case OMPC_read:
6861 case OMPC_write:
6862 case OMPC_update:
6863 case OMPC_capture:
6864 case OMPC_seq_cst:
6865 case OMPC_depend:
6866 case OMPC_device:
6867 case OMPC_threads:
6868 case OMPC_simd:
6869 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006870 case OMPC_thread_limit:
6871 case OMPC_priority:
6872 case OMPC_grainsize:
6873 case OMPC_nogroup:
6874 case OMPC_num_tasks:
6875 case OMPC_hint:
6876 case OMPC_defaultmap:
6877 case OMPC_unknown:
6878 case OMPC_uniform:
6879 case OMPC_to:
6880 case OMPC_from:
6881 case OMPC_use_device_ptr:
6882 case OMPC_is_device_ptr:
6883 llvm_unreachable("Unexpected OpenMP clause.");
6884 }
6885 return CaptureRegion;
6886}
6887
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006888OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6889 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006890 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006891 SourceLocation NameModifierLoc,
6892 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006893 SourceLocation EndLoc) {
6894 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006895 Stmt *HelperValStmt = nullptr;
6896 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006897 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6898 !Condition->isInstantiationDependent() &&
6899 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006900 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006901 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006902 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006903
Richard Smith03a4aa32016-06-23 19:02:52 +00006904 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006905
6906 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6907 CaptureRegion =
6908 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
6909 if (CaptureRegion != OMPD_unknown) {
6910 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6911 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6912 HelperValStmt = buildPreInits(Context, Captures);
6913 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006914 }
6915
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006916 return new (Context)
6917 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
6918 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006919}
6920
Alexey Bataev3778b602014-07-17 07:32:53 +00006921OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6922 SourceLocation StartLoc,
6923 SourceLocation LParenLoc,
6924 SourceLocation EndLoc) {
6925 Expr *ValExpr = Condition;
6926 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6927 !Condition->isInstantiationDependent() &&
6928 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006929 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006930 if (Val.isInvalid())
6931 return nullptr;
6932
Richard Smith03a4aa32016-06-23 19:02:52 +00006933 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006934 }
6935
6936 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6937}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006938ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6939 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006940 if (!Op)
6941 return ExprError();
6942
6943 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6944 public:
6945 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006946 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006947 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6948 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006949 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6950 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006951 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6952 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006953 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6954 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006955 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6956 QualType T,
6957 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006958 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6959 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006960 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6961 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006962 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006963 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006964 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006965 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6966 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006967 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6968 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006969 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6970 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006971 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006972 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006973 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006974 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6975 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006976 llvm_unreachable("conversion functions are permitted");
6977 }
6978 } ConvertDiagnoser;
6979 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6980}
6981
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006982static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006983 OpenMPClauseKind CKind,
6984 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006985 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6986 !ValExpr->isInstantiationDependent()) {
6987 SourceLocation Loc = ValExpr->getExprLoc();
6988 ExprResult Value =
6989 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6990 if (Value.isInvalid())
6991 return false;
6992
6993 ValExpr = Value.get();
6994 // The expression must evaluate to a non-negative integer value.
6995 llvm::APSInt Result;
6996 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006997 Result.isSigned() &&
6998 !((!StrictlyPositive && Result.isNonNegative()) ||
6999 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007000 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007001 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7002 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007003 return false;
7004 }
7005 }
7006 return true;
7007}
7008
Alexey Bataev568a8332014-03-06 06:15:19 +00007009OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
7010 SourceLocation StartLoc,
7011 SourceLocation LParenLoc,
7012 SourceLocation EndLoc) {
7013 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007014 Stmt *HelperValStmt = nullptr;
7015 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev568a8332014-03-06 06:15:19 +00007016
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007017 // OpenMP [2.5, Restrictions]
7018 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00007019 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
7020 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007021 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00007022
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007023 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
7024 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
7025 if (CaptureRegion != OMPD_unknown) {
7026 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7027 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7028 HelperValStmt = buildPreInits(Context, Captures);
7029 }
7030
7031 return new (Context) OMPNumThreadsClause(
7032 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00007033}
7034
Alexey Bataev62c87d22014-03-21 04:51:18 +00007035ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007036 OpenMPClauseKind CKind,
7037 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007038 if (!E)
7039 return ExprError();
7040 if (E->isValueDependent() || E->isTypeDependent() ||
7041 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007042 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007043 llvm::APSInt Result;
7044 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
7045 if (ICE.isInvalid())
7046 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007047 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
7048 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00007049 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007050 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
7051 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00007052 return ExprError();
7053 }
Alexander Musman09184fe2014-09-30 05:29:28 +00007054 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
7055 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
7056 << E->getSourceRange();
7057 return ExprError();
7058 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007059 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
7060 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007061 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007062 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00007063 return ICE;
7064}
7065
7066OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
7067 SourceLocation LParenLoc,
7068 SourceLocation EndLoc) {
7069 // OpenMP [2.8.1, simd construct, Description]
7070 // The parameter of the safelen clause must be a constant
7071 // positive integer expression.
7072 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
7073 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007074 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007075 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007076 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00007077}
7078
Alexey Bataev66b15b52015-08-21 11:14:16 +00007079OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
7080 SourceLocation LParenLoc,
7081 SourceLocation EndLoc) {
7082 // OpenMP [2.8.1, simd construct, Description]
7083 // The parameter of the simdlen clause must be a constant
7084 // positive integer expression.
7085 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
7086 if (Simdlen.isInvalid())
7087 return nullptr;
7088 return new (Context)
7089 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
7090}
7091
Alexander Musman64d33f12014-06-04 07:53:32 +00007092OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
7093 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00007094 SourceLocation LParenLoc,
7095 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00007096 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007097 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00007098 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00007099 // The parameter of the collapse clause must be a constant
7100 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00007101 ExprResult NumForLoopsResult =
7102 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
7103 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00007104 return nullptr;
7105 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00007106 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00007107}
7108
Alexey Bataev10e775f2015-07-30 11:36:16 +00007109OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
7110 SourceLocation EndLoc,
7111 SourceLocation LParenLoc,
7112 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007113 // OpenMP [2.7.1, loop construct, Description]
7114 // OpenMP [2.8.1, simd construct, Description]
7115 // OpenMP [2.9.6, distribute construct, Description]
7116 // The parameter of the ordered clause must be a constant
7117 // positive integer expression if any.
7118 if (NumForLoops && LParenLoc.isValid()) {
7119 ExprResult NumForLoopsResult =
7120 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
7121 if (NumForLoopsResult.isInvalid())
7122 return nullptr;
7123 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00007124 } else
7125 NumForLoops = nullptr;
7126 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00007127 return new (Context)
7128 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
7129}
7130
Alexey Bataeved09d242014-05-28 05:53:51 +00007131OMPClause *Sema::ActOnOpenMPSimpleClause(
7132 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
7133 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007134 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007135 switch (Kind) {
7136 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007137 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007138 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7139 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007140 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007141 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007142 Res = ActOnOpenMPProcBindClause(
7143 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7144 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007145 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007146 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007147 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007148 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007149 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007150 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007151 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007152 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007153 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007154 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007155 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007156 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007157 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007158 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007159 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007160 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007161 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007162 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007163 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007164 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007165 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007166 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007167 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007168 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007169 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007170 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007171 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007172 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007173 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007174 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007175 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007176 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007177 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007178 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007179 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007180 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007181 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007182 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007183 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007184 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007185 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007186 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007187 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007188 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007189 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007190 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007191 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007192 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007193 llvm_unreachable("Clause is not allowed.");
7194 }
7195 return Res;
7196}
7197
Alexey Bataev6402bca2015-12-28 07:25:51 +00007198static std::string
7199getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7200 ArrayRef<unsigned> Exclude = llvm::None) {
7201 std::string Values;
7202 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7203 unsigned Skipped = Exclude.size();
7204 auto S = Exclude.begin(), E = Exclude.end();
7205 for (unsigned i = First; i < Last; ++i) {
7206 if (std::find(S, E, i) != E) {
7207 --Skipped;
7208 continue;
7209 }
7210 Values += "'";
7211 Values += getOpenMPSimpleClauseTypeName(K, i);
7212 Values += "'";
7213 if (i == Bound - Skipped)
7214 Values += " or ";
7215 else if (i != Bound + 1 - Skipped)
7216 Values += ", ";
7217 }
7218 return Values;
7219}
7220
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007221OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7222 SourceLocation KindKwLoc,
7223 SourceLocation StartLoc,
7224 SourceLocation LParenLoc,
7225 SourceLocation EndLoc) {
7226 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007227 static_assert(OMPC_DEFAULT_unknown > 0,
7228 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007229 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007230 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7231 /*Last=*/OMPC_DEFAULT_unknown)
7232 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007233 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007234 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007235 switch (Kind) {
7236 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007237 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007238 break;
7239 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007240 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007241 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007242 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007243 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007244 break;
7245 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007246 return new (Context)
7247 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007248}
7249
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007250OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7251 SourceLocation KindKwLoc,
7252 SourceLocation StartLoc,
7253 SourceLocation LParenLoc,
7254 SourceLocation EndLoc) {
7255 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007256 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007257 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7258 /*Last=*/OMPC_PROC_BIND_unknown)
7259 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007260 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007261 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007262 return new (Context)
7263 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007264}
7265
Alexey Bataev56dafe82014-06-20 07:16:17 +00007266OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007267 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007268 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007269 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007270 SourceLocation EndLoc) {
7271 OMPClause *Res = nullptr;
7272 switch (Kind) {
7273 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007274 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7275 assert(Argument.size() == NumberOfElements &&
7276 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007277 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007278 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7279 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7280 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7281 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7282 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007283 break;
7284 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007285 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7286 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7287 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7288 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007289 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007290 case OMPC_dist_schedule:
7291 Res = ActOnOpenMPDistScheduleClause(
7292 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7293 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7294 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007295 case OMPC_defaultmap:
7296 enum { Modifier, DefaultmapKind };
7297 Res = ActOnOpenMPDefaultmapClause(
7298 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7299 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007300 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7301 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007302 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007303 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007304 case OMPC_num_threads:
7305 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007306 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007307 case OMPC_collapse:
7308 case OMPC_default:
7309 case OMPC_proc_bind:
7310 case OMPC_private:
7311 case OMPC_firstprivate:
7312 case OMPC_lastprivate:
7313 case OMPC_shared:
7314 case OMPC_reduction:
7315 case OMPC_linear:
7316 case OMPC_aligned:
7317 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007318 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007319 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007320 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007321 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007322 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007323 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007324 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007325 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007326 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007327 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007328 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007329 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007330 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007331 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007332 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007333 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007334 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007335 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007336 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007337 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007338 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007339 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007340 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007341 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007342 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007343 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007344 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007345 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007346 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007347 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007348 llvm_unreachable("Clause is not allowed.");
7349 }
7350 return Res;
7351}
7352
Alexey Bataev6402bca2015-12-28 07:25:51 +00007353static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7354 OpenMPScheduleClauseModifier M2,
7355 SourceLocation M1Loc, SourceLocation M2Loc) {
7356 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7357 SmallVector<unsigned, 2> Excluded;
7358 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7359 Excluded.push_back(M2);
7360 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7361 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7362 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7363 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7364 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7365 << getListOfPossibleValues(OMPC_schedule,
7366 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7367 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7368 Excluded)
7369 << getOpenMPClauseName(OMPC_schedule);
7370 return true;
7371 }
7372 return false;
7373}
7374
Alexey Bataev56dafe82014-06-20 07:16:17 +00007375OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007376 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007377 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007378 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7379 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7380 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7381 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7382 return nullptr;
7383 // OpenMP, 2.7.1, Loop Construct, Restrictions
7384 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7385 // but not both.
7386 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7387 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7388 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7389 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7390 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7391 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7392 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7393 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7394 return nullptr;
7395 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007396 if (Kind == OMPC_SCHEDULE_unknown) {
7397 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007398 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7399 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7400 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7401 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7402 Exclude);
7403 } else {
7404 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7405 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007406 }
7407 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7408 << Values << getOpenMPClauseName(OMPC_schedule);
7409 return nullptr;
7410 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007411 // OpenMP, 2.7.1, Loop Construct, Restrictions
7412 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7413 // schedule(guided).
7414 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7415 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7416 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7417 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7418 diag::err_omp_schedule_nonmonotonic_static);
7419 return nullptr;
7420 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007421 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007422 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007423 if (ChunkSize) {
7424 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7425 !ChunkSize->isInstantiationDependent() &&
7426 !ChunkSize->containsUnexpandedParameterPack()) {
7427 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7428 ExprResult Val =
7429 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7430 if (Val.isInvalid())
7431 return nullptr;
7432
7433 ValExpr = Val.get();
7434
7435 // OpenMP [2.7.1, Restrictions]
7436 // chunk_size must be a loop invariant integer expression with a positive
7437 // value.
7438 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007439 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7440 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7441 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007442 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007443 return nullptr;
7444 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007445 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7446 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007447 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7448 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7449 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007450 }
7451 }
7452 }
7453
Alexey Bataev6402bca2015-12-28 07:25:51 +00007454 return new (Context)
7455 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007456 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007457}
7458
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007459OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7460 SourceLocation StartLoc,
7461 SourceLocation EndLoc) {
7462 OMPClause *Res = nullptr;
7463 switch (Kind) {
7464 case OMPC_ordered:
7465 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7466 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007467 case OMPC_nowait:
7468 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7469 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007470 case OMPC_untied:
7471 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7472 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007473 case OMPC_mergeable:
7474 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7475 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007476 case OMPC_read:
7477 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7478 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007479 case OMPC_write:
7480 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7481 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007482 case OMPC_update:
7483 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7484 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007485 case OMPC_capture:
7486 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7487 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007488 case OMPC_seq_cst:
7489 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7490 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007491 case OMPC_threads:
7492 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7493 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007494 case OMPC_simd:
7495 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7496 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007497 case OMPC_nogroup:
7498 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7499 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007500 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007501 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007502 case OMPC_num_threads:
7503 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007504 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007505 case OMPC_collapse:
7506 case OMPC_schedule:
7507 case OMPC_private:
7508 case OMPC_firstprivate:
7509 case OMPC_lastprivate:
7510 case OMPC_shared:
7511 case OMPC_reduction:
7512 case OMPC_linear:
7513 case OMPC_aligned:
7514 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007515 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007516 case OMPC_default:
7517 case OMPC_proc_bind:
7518 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007519 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007520 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007521 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007522 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007523 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007524 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007525 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007526 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007527 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007528 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007529 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007530 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007531 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007532 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007533 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007534 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007535 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007536 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007537 llvm_unreachable("Clause is not allowed.");
7538 }
7539 return Res;
7540}
7541
Alexey Bataev236070f2014-06-20 11:19:47 +00007542OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7543 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007544 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007545 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7546}
7547
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007548OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7549 SourceLocation EndLoc) {
7550 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7551}
7552
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007553OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7554 SourceLocation EndLoc) {
7555 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7556}
7557
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007558OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7559 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007560 return new (Context) OMPReadClause(StartLoc, EndLoc);
7561}
7562
Alexey Bataevdea47612014-07-23 07:46:59 +00007563OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7564 SourceLocation EndLoc) {
7565 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7566}
7567
Alexey Bataev67a4f222014-07-23 10:25:33 +00007568OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7569 SourceLocation EndLoc) {
7570 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7571}
7572
Alexey Bataev459dec02014-07-24 06:46:57 +00007573OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7574 SourceLocation EndLoc) {
7575 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7576}
7577
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007578OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7579 SourceLocation EndLoc) {
7580 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7581}
7582
Alexey Bataev346265e2015-09-25 10:37:12 +00007583OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7584 SourceLocation EndLoc) {
7585 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7586}
7587
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007588OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7589 SourceLocation EndLoc) {
7590 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7591}
7592
Alexey Bataevb825de12015-12-07 10:51:44 +00007593OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7594 SourceLocation EndLoc) {
7595 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7596}
7597
Alexey Bataevc5e02582014-06-16 07:08:35 +00007598OMPClause *Sema::ActOnOpenMPVarListClause(
7599 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7600 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7601 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007602 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007603 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7604 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7605 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007606 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007607 switch (Kind) {
7608 case OMPC_private:
7609 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7610 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007611 case OMPC_firstprivate:
7612 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7613 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007614 case OMPC_lastprivate:
7615 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7616 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007617 case OMPC_shared:
7618 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7619 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007620 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007621 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7622 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007623 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007624 case OMPC_linear:
7625 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007626 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007627 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007628 case OMPC_aligned:
7629 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7630 ColonLoc, EndLoc);
7631 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007632 case OMPC_copyin:
7633 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7634 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007635 case OMPC_copyprivate:
7636 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7637 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007638 case OMPC_flush:
7639 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7640 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007641 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007642 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007643 StartLoc, LParenLoc, EndLoc);
7644 break;
7645 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007646 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7647 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7648 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007649 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007650 case OMPC_to:
7651 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7652 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007653 case OMPC_from:
7654 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7655 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007656 case OMPC_use_device_ptr:
7657 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7658 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007659 case OMPC_is_device_ptr:
7660 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7661 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007662 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007663 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007664 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007665 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007666 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007667 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007668 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007669 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007670 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007671 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007672 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007673 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007674 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007675 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007676 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007677 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007678 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007679 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007680 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007681 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007682 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007683 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007684 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007685 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007686 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007687 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007688 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007689 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007690 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007691 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007692 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007693 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007694 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007695 llvm_unreachable("Clause is not allowed.");
7696 }
7697 return Res;
7698}
7699
Alexey Bataev90c228f2016-02-08 09:29:13 +00007700ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007701 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007702 ExprResult Res = BuildDeclRefExpr(
7703 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7704 if (!Res.isUsable())
7705 return ExprError();
7706 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7707 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7708 if (!Res.isUsable())
7709 return ExprError();
7710 }
7711 if (VK != VK_LValue && Res.get()->isGLValue()) {
7712 Res = DefaultLvalueConversion(Res.get());
7713 if (!Res.isUsable())
7714 return ExprError();
7715 }
7716 return Res;
7717}
7718
Alexey Bataev60da77e2016-02-29 05:54:20 +00007719static std::pair<ValueDecl *, bool>
7720getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7721 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007722 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7723 RefExpr->containsUnexpandedParameterPack())
7724 return std::make_pair(nullptr, true);
7725
Alexey Bataevd985eda2016-02-10 11:29:16 +00007726 // OpenMP [3.1, C/C++]
7727 // A list item is a variable name.
7728 // OpenMP [2.9.3.3, Restrictions, p.1]
7729 // A variable that is part of another variable (as an array or
7730 // structure element) cannot appear in a private clause.
7731 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007732 enum {
7733 NoArrayExpr = -1,
7734 ArraySubscript = 0,
7735 OMPArraySection = 1
7736 } IsArrayExpr = NoArrayExpr;
7737 if (AllowArraySection) {
7738 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7739 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7740 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7741 Base = TempASE->getBase()->IgnoreParenImpCasts();
7742 RefExpr = Base;
7743 IsArrayExpr = ArraySubscript;
7744 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7745 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7746 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7747 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7748 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7749 Base = TempASE->getBase()->IgnoreParenImpCasts();
7750 RefExpr = Base;
7751 IsArrayExpr = OMPArraySection;
7752 }
7753 }
7754 ELoc = RefExpr->getExprLoc();
7755 ERange = RefExpr->getSourceRange();
7756 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007757 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7758 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7759 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7760 (S.getCurrentThisType().isNull() || !ME ||
7761 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7762 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007763 if (IsArrayExpr != NoArrayExpr)
7764 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7765 << ERange;
7766 else {
7767 S.Diag(ELoc,
7768 AllowArraySection
7769 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7770 : diag::err_omp_expected_var_name_member_expr)
7771 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7772 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007773 return std::make_pair(nullptr, false);
7774 }
7775 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7776}
7777
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007778OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7779 SourceLocation StartLoc,
7780 SourceLocation LParenLoc,
7781 SourceLocation EndLoc) {
7782 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007783 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007784 for (auto &RefExpr : VarList) {
7785 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007786 SourceLocation ELoc;
7787 SourceRange ERange;
7788 Expr *SimpleRefExpr = RefExpr;
7789 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007790 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007791 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007792 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007793 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007794 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007795 ValueDecl *D = Res.first;
7796 if (!D)
7797 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007798
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007799 QualType Type = D->getType();
7800 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007801
7802 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7803 // A variable that appears in a private clause must not have an incomplete
7804 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007805 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007806 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007807 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007808
Alexey Bataev758e55e2013-09-06 18:03:48 +00007809 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7810 // in a Construct]
7811 // Variables with the predetermined data-sharing attributes may not be
7812 // listed in data-sharing attributes clauses, except for the cases
7813 // listed below. For these exceptions only, listing a predetermined
7814 // variable in a data-sharing attribute clause is allowed and overrides
7815 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007816 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007817 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007818 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7819 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007820 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007821 continue;
7822 }
7823
Kelvin Libf594a52016-12-17 05:48:59 +00007824 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007825 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007826 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007827 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007828 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7829 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007830 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007831 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007832 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007833 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007834 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007835 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007836 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007837 continue;
7838 }
7839
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007840 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7841 // A list item cannot appear in both a map clause and a data-sharing
7842 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007843 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007844 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007845 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007846 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007847 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007848 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007849 CurrDir == OMPD_target_parallel_for_simd ||
7850 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007851 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007852 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007853 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007854 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7855 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7856 ConflictKind = WhereFoundClauseKind;
7857 return true;
7858 })) {
7859 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007860 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007861 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007862 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007863 ReportOriginalDSA(*this, DSAStack, D, DVar);
7864 continue;
7865 }
7866 }
7867
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007868 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7869 // A variable of class type (or array thereof) that appears in a private
7870 // clause requires an accessible, unambiguous default constructor for the
7871 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007872 // Generate helper private variable and initialize it with the default
7873 // value. The address of the original variable is replaced by the address of
7874 // the new private variable in CodeGen. This new variable is not added to
7875 // IdResolver, so the code in the OpenMP region uses original variable for
7876 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007877 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007878 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7879 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00007880 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007881 if (VDPrivate->isInvalidDecl())
7882 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007883 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007884 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007885
Alexey Bataev90c228f2016-02-08 09:29:13 +00007886 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007887 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007888 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007889 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007890 Vars.push_back((VD || CurContext->isDependentContext())
7891 ? RefExpr->IgnoreParens()
7892 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007893 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007894 }
7895
Alexey Bataeved09d242014-05-28 05:53:51 +00007896 if (Vars.empty())
7897 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007898
Alexey Bataev03b340a2014-10-21 03:16:40 +00007899 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7900 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007901}
7902
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007903namespace {
7904class DiagsUninitializedSeveretyRAII {
7905private:
7906 DiagnosticsEngine &Diags;
7907 SourceLocation SavedLoc;
7908 bool IsIgnored;
7909
7910public:
7911 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7912 bool IsIgnored)
7913 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7914 if (!IsIgnored) {
7915 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7916 /*Map*/ diag::Severity::Ignored, Loc);
7917 }
7918 }
7919 ~DiagsUninitializedSeveretyRAII() {
7920 if (!IsIgnored)
7921 Diags.popMappings(SavedLoc);
7922 }
7923};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007924}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007925
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007926OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7927 SourceLocation StartLoc,
7928 SourceLocation LParenLoc,
7929 SourceLocation EndLoc) {
7930 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007931 SmallVector<Expr *, 8> PrivateCopies;
7932 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007933 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007934 bool IsImplicitClause =
7935 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7936 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7937
Alexey Bataeved09d242014-05-28 05:53:51 +00007938 for (auto &RefExpr : VarList) {
7939 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007940 SourceLocation ELoc;
7941 SourceRange ERange;
7942 Expr *SimpleRefExpr = RefExpr;
7943 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007944 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007945 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007946 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007947 PrivateCopies.push_back(nullptr);
7948 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007949 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007950 ValueDecl *D = Res.first;
7951 if (!D)
7952 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007953
Alexey Bataev60da77e2016-02-29 05:54:20 +00007954 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007955 QualType Type = D->getType();
7956 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007957
7958 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7959 // A variable that appears in a private clause must not have an incomplete
7960 // type or a reference type.
7961 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007962 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007963 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007964 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007965
7966 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7967 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007968 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007969 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007970 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007971
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007972 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007973 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007974 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007975 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007976 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007977 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007978 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7979 // A list item that specifies a given variable may not appear in more
7980 // than one clause on the same directive, except that a variable may be
7981 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007982 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007983 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007984 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007985 << getOpenMPClauseName(DVar.CKind)
7986 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007987 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007988 continue;
7989 }
7990
7991 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7992 // in a Construct]
7993 // Variables with the predetermined data-sharing attributes may not be
7994 // listed in data-sharing attributes clauses, except for the cases
7995 // listed below. For these exceptions only, listing a predetermined
7996 // variable in a data-sharing attribute clause is allowed and overrides
7997 // the variable's predetermined data-sharing attributes.
7998 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7999 // in a Construct, C/C++, p.2]
8000 // Variables with const-qualified type having no mutable member may be
8001 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00008002 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008003 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
8004 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00008005 << getOpenMPClauseName(DVar.CKind)
8006 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008007 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008008 continue;
8009 }
8010
Alexey Bataevf29276e2014-06-18 04:14:57 +00008011 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008012 // OpenMP [2.9.3.4, Restrictions, p.2]
8013 // A list item that is private within a parallel region must not appear
8014 // in a firstprivate clause on a worksharing construct if any of the
8015 // worksharing regions arising from the worksharing construct ever bind
8016 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00008017 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008018 !isOpenMPParallelDirective(CurrDir) &&
8019 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008020 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008021 if (DVar.CKind != OMPC_shared &&
8022 (isOpenMPParallelDirective(DVar.DKind) ||
8023 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00008024 Diag(ELoc, diag::err_omp_required_access)
8025 << getOpenMPClauseName(OMPC_firstprivate)
8026 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008027 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008028 continue;
8029 }
8030 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008031 // OpenMP [2.9.3.4, Restrictions, p.3]
8032 // A list item that appears in a reduction clause of a parallel construct
8033 // must not appear in a firstprivate clause on a worksharing or task
8034 // construct if any of the worksharing or task regions arising from the
8035 // worksharing or task construct ever bind to any of the parallel regions
8036 // arising from the parallel construct.
8037 // OpenMP [2.9.3.4, Restrictions, p.4]
8038 // A list item that appears in a reduction clause in worksharing
8039 // construct must not appear in a firstprivate clause in a task construct
8040 // encountered during execution of any of the worksharing regions arising
8041 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00008042 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008043 DVar = DSAStack->hasInnermostDSA(
8044 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8045 [](OpenMPDirectiveKind K) -> bool {
8046 return isOpenMPParallelDirective(K) ||
8047 isOpenMPWorksharingDirective(K);
8048 },
8049 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008050 if (DVar.CKind == OMPC_reduction &&
8051 (isOpenMPParallelDirective(DVar.DKind) ||
8052 isOpenMPWorksharingDirective(DVar.DKind))) {
8053 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
8054 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008055 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008056 continue;
8057 }
8058 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008059
8060 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8061 // A list item that is private within a teams region must not appear in a
8062 // firstprivate clause on a distribute construct if any of the distribute
8063 // regions arising from the distribute construct ever bind to any of the
8064 // teams regions arising from the teams construct.
8065 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
8066 // A list item that appears in a reduction clause of a teams construct
8067 // must not appear in a firstprivate clause on a distribute construct if
8068 // any of the distribute regions arising from the distribute construct
8069 // ever bind to any of the teams regions arising from the teams construct.
8070 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8071 // A list item may appear in a firstprivate or lastprivate clause but not
8072 // both.
8073 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008074 DVar = DSAStack->hasInnermostDSA(
8075 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
8076 [](OpenMPDirectiveKind K) -> bool {
8077 return isOpenMPTeamsDirective(K);
8078 },
8079 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008080 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
8081 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008082 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008083 continue;
8084 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008085 DVar = DSAStack->hasInnermostDSA(
8086 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
8087 [](OpenMPDirectiveKind K) -> bool {
8088 return isOpenMPTeamsDirective(K);
8089 },
8090 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008091 if (DVar.CKind == OMPC_reduction &&
8092 isOpenMPTeamsDirective(DVar.DKind)) {
8093 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008094 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008095 continue;
8096 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008097 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008098 if (DVar.CKind == OMPC_lastprivate) {
8099 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00008100 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008101 continue;
8102 }
8103 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008104 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
8105 // A list item cannot appear in both a map clause and a data-sharing
8106 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00008107 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00008108 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00008109 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00008110 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00008111 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00008112 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00008113 CurrDir == OMPD_target_parallel_for_simd ||
8114 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00008115 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00008116 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00008117 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00008118 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
8119 OpenMPClauseKind WhereFoundClauseKind) -> bool {
8120 ConflictKind = WhereFoundClauseKind;
8121 return true;
8122 })) {
8123 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008124 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00008125 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00008126 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8127 ReportOriginalDSA(*this, DSAStack, D, DVar);
8128 continue;
8129 }
8130 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008131 }
8132
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008133 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00008134 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00008135 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008136 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
8137 << getOpenMPClauseName(OMPC_firstprivate) << Type
8138 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8139 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008140 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008141 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008142 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008143 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008144 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008145 continue;
8146 }
8147
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008148 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008149 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8150 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008151 // Generate helper private variable and initialize it with the value of the
8152 // original variable. The address of the original variable is replaced by
8153 // the address of the new private variable in the CodeGen. This new variable
8154 // is not added to IdResolver, so the code in the OpenMP region uses
8155 // original variable for proper diagnostics and variable capturing.
8156 Expr *VDInitRefExpr = nullptr;
8157 // For arrays generate initializer for single element and replace it by the
8158 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008159 if (Type->isArrayType()) {
8160 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008161 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008162 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008163 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008164 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008165 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008166 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008167 InitializedEntity Entity =
8168 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008169 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8170
8171 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8172 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8173 if (Result.isInvalid())
8174 VDPrivate->setInvalidDecl();
8175 else
8176 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008177 // Remove temp variable declaration.
8178 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008179 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008180 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8181 ".firstprivate.temp");
8182 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8183 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008184 AddInitializerToDecl(VDPrivate,
8185 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008186 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008187 }
8188 if (VDPrivate->isInvalidDecl()) {
8189 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008190 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008191 diag::note_omp_task_predetermined_firstprivate_here);
8192 }
8193 continue;
8194 }
8195 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008196 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008197 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8198 RefExpr->getExprLoc());
8199 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008200 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008201 if (TopDVar.CKind == OMPC_lastprivate)
8202 Ref = TopDVar.PrivateCopy;
8203 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008204 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008205 if (!IsOpenMPCapturedDecl(D))
8206 ExprCaptures.push_back(Ref->getDecl());
8207 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008208 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008209 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008210 Vars.push_back((VD || CurContext->isDependentContext())
8211 ? RefExpr->IgnoreParens()
8212 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008213 PrivateCopies.push_back(VDPrivateRefExpr);
8214 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008215 }
8216
Alexey Bataeved09d242014-05-28 05:53:51 +00008217 if (Vars.empty())
8218 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008219
8220 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008221 Vars, PrivateCopies, Inits,
8222 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008223}
8224
Alexander Musman1bb328c2014-06-04 13:06:39 +00008225OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8226 SourceLocation StartLoc,
8227 SourceLocation LParenLoc,
8228 SourceLocation EndLoc) {
8229 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008230 SmallVector<Expr *, 8> SrcExprs;
8231 SmallVector<Expr *, 8> DstExprs;
8232 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008233 SmallVector<Decl *, 4> ExprCaptures;
8234 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008235 for (auto &RefExpr : VarList) {
8236 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008237 SourceLocation ELoc;
8238 SourceRange ERange;
8239 Expr *SimpleRefExpr = RefExpr;
8240 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008241 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008242 // It will be analyzed later.
8243 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008244 SrcExprs.push_back(nullptr);
8245 DstExprs.push_back(nullptr);
8246 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008247 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008248 ValueDecl *D = Res.first;
8249 if (!D)
8250 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008251
Alexey Bataev74caaf22016-02-20 04:09:36 +00008252 QualType Type = D->getType();
8253 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008254
8255 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8256 // A variable that appears in a lastprivate clause must not have an
8257 // incomplete type or a reference type.
8258 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008259 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008260 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008261 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008262
8263 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8264 // in a Construct]
8265 // Variables with the predetermined data-sharing attributes may not be
8266 // listed in data-sharing attributes clauses, except for the cases
8267 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008268 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008269 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8270 DVar.CKind != OMPC_firstprivate &&
8271 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8272 Diag(ELoc, diag::err_omp_wrong_dsa)
8273 << getOpenMPClauseName(DVar.CKind)
8274 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008275 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008276 continue;
8277 }
8278
Alexey Bataevf29276e2014-06-18 04:14:57 +00008279 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8280 // OpenMP [2.14.3.5, Restrictions, p.2]
8281 // A list item that is private within a parallel region, or that appears in
8282 // the reduction clause of a parallel construct, must not appear in a
8283 // lastprivate clause on a worksharing construct if any of the corresponding
8284 // worksharing regions ever binds to any of the corresponding parallel
8285 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008286 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008287 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008288 !isOpenMPParallelDirective(CurrDir) &&
8289 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008290 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008291 if (DVar.CKind != OMPC_shared) {
8292 Diag(ELoc, diag::err_omp_required_access)
8293 << getOpenMPClauseName(OMPC_lastprivate)
8294 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008295 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008296 continue;
8297 }
8298 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008299
8300 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8301 // A list item may appear in a firstprivate or lastprivate clause but not
8302 // both.
8303 if (CurrDir == OMPD_distribute) {
8304 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8305 if (DVar.CKind == OMPC_firstprivate) {
8306 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8307 ReportOriginalDSA(*this, DSAStack, D, DVar);
8308 continue;
8309 }
8310 }
8311
Alexander Musman1bb328c2014-06-04 13:06:39 +00008312 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008313 // A variable of class type (or array thereof) that appears in a
8314 // lastprivate clause requires an accessible, unambiguous default
8315 // constructor for the class type, unless the list item is also specified
8316 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008317 // A variable of class type (or array thereof) that appears in a
8318 // lastprivate clause requires an accessible, unambiguous copy assignment
8319 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008320 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008321 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008322 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008323 D->hasAttrs() ? &D->getAttrs() : nullptr);
8324 auto *PseudoSrcExpr =
8325 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008326 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008327 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008328 D->hasAttrs() ? &D->getAttrs() : nullptr);
8329 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008330 // For arrays generate assignment operation for single element and replace
8331 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008332 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008333 PseudoDstExpr, PseudoSrcExpr);
8334 if (AssignmentOp.isInvalid())
8335 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008336 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008337 /*DiscardedValue=*/true);
8338 if (AssignmentOp.isInvalid())
8339 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008340
Alexey Bataev74caaf22016-02-20 04:09:36 +00008341 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008342 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008343 if (TopDVar.CKind == OMPC_firstprivate)
8344 Ref = TopDVar.PrivateCopy;
8345 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008346 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008347 if (!IsOpenMPCapturedDecl(D))
8348 ExprCaptures.push_back(Ref->getDecl());
8349 }
8350 if (TopDVar.CKind == OMPC_firstprivate ||
8351 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008352 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008353 ExprResult RefRes = DefaultLvalueConversion(Ref);
8354 if (!RefRes.isUsable())
8355 continue;
8356 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008357 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8358 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008359 if (!PostUpdateRes.isUsable())
8360 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008361 ExprPostUpdates.push_back(
8362 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008363 }
8364 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008365 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008366 Vars.push_back((VD || CurContext->isDependentContext())
8367 ? RefExpr->IgnoreParens()
8368 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008369 SrcExprs.push_back(PseudoSrcExpr);
8370 DstExprs.push_back(PseudoDstExpr);
8371 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008372 }
8373
8374 if (Vars.empty())
8375 return nullptr;
8376
8377 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008378 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008379 buildPreInits(Context, ExprCaptures),
8380 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008381}
8382
Alexey Bataev758e55e2013-09-06 18:03:48 +00008383OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8384 SourceLocation StartLoc,
8385 SourceLocation LParenLoc,
8386 SourceLocation EndLoc) {
8387 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008388 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008389 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008390 SourceLocation ELoc;
8391 SourceRange ERange;
8392 Expr *SimpleRefExpr = RefExpr;
8393 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008394 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008395 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008396 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008397 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008398 ValueDecl *D = Res.first;
8399 if (!D)
8400 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008401
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008402 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008403 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8404 // in a Construct]
8405 // Variables with the predetermined data-sharing attributes may not be
8406 // listed in data-sharing attributes clauses, except for the cases
8407 // listed below. For these exceptions only, listing a predetermined
8408 // variable in a data-sharing attribute clause is allowed and overrides
8409 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008410 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008411 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8412 DVar.RefExpr) {
8413 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8414 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008415 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008416 continue;
8417 }
8418
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008419 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008420 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008421 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008422 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008423 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8424 ? RefExpr->IgnoreParens()
8425 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008426 }
8427
Alexey Bataeved09d242014-05-28 05:53:51 +00008428 if (Vars.empty())
8429 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008430
8431 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8432}
8433
Alexey Bataevc5e02582014-06-16 07:08:35 +00008434namespace {
8435class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8436 DSAStackTy *Stack;
8437
8438public:
8439 bool VisitDeclRefExpr(DeclRefExpr *E) {
8440 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008441 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008442 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8443 return false;
8444 if (DVar.CKind != OMPC_unknown)
8445 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008446 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8447 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8448 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008449 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008450 return true;
8451 return false;
8452 }
8453 return false;
8454 }
8455 bool VisitStmt(Stmt *S) {
8456 for (auto Child : S->children()) {
8457 if (Child && Visit(Child))
8458 return true;
8459 }
8460 return false;
8461 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008462 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008463};
Alexey Bataev23b69422014-06-18 07:08:49 +00008464} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008465
Alexey Bataev60da77e2016-02-29 05:54:20 +00008466namespace {
8467// Transform MemberExpression for specified FieldDecl of current class to
8468// DeclRefExpr to specified OMPCapturedExprDecl.
8469class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8470 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8471 ValueDecl *Field;
8472 DeclRefExpr *CapturedExpr;
8473
8474public:
8475 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8476 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8477
8478 ExprResult TransformMemberExpr(MemberExpr *E) {
8479 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8480 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008481 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008482 return CapturedExpr;
8483 }
8484 return BaseTransform::TransformMemberExpr(E);
8485 }
8486 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8487};
8488} // namespace
8489
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008490template <typename T>
8491static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8492 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8493 for (auto &Set : Lookups) {
8494 for (auto *D : Set) {
8495 if (auto Res = Gen(cast<ValueDecl>(D)))
8496 return Res;
8497 }
8498 }
8499 return T();
8500}
8501
8502static ExprResult
8503buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8504 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8505 const DeclarationNameInfo &ReductionId, QualType Ty,
8506 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8507 if (ReductionIdScopeSpec.isInvalid())
8508 return ExprError();
8509 SmallVector<UnresolvedSet<8>, 4> Lookups;
8510 if (S) {
8511 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8512 Lookup.suppressDiagnostics();
8513 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8514 auto *D = Lookup.getRepresentativeDecl();
8515 do {
8516 S = S->getParent();
8517 } while (S && !S->isDeclScope(D));
8518 if (S)
8519 S = S->getParent();
8520 Lookups.push_back(UnresolvedSet<8>());
8521 Lookups.back().append(Lookup.begin(), Lookup.end());
8522 Lookup.clear();
8523 }
8524 } else if (auto *ULE =
8525 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8526 Lookups.push_back(UnresolvedSet<8>());
8527 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008528 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008529 if (D == PrevD)
8530 Lookups.push_back(UnresolvedSet<8>());
8531 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8532 Lookups.back().addDecl(DRD);
8533 PrevD = D;
8534 }
8535 }
8536 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8537 Ty->containsUnexpandedParameterPack() ||
8538 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8539 return !D->isInvalidDecl() &&
8540 (D->getType()->isDependentType() ||
8541 D->getType()->isInstantiationDependentType() ||
8542 D->getType()->containsUnexpandedParameterPack());
8543 })) {
8544 UnresolvedSet<8> ResSet;
8545 for (auto &Set : Lookups) {
8546 ResSet.append(Set.begin(), Set.end());
8547 // The last item marks the end of all declarations at the specified scope.
8548 ResSet.addDecl(Set[Set.size() - 1]);
8549 }
8550 return UnresolvedLookupExpr::Create(
8551 SemaRef.Context, /*NamingClass=*/nullptr,
8552 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8553 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8554 }
8555 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8556 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8557 if (!D->isInvalidDecl() &&
8558 SemaRef.Context.hasSameType(D->getType(), Ty))
8559 return D;
8560 return nullptr;
8561 }))
8562 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8563 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8564 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8565 if (!D->isInvalidDecl() &&
8566 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8567 !Ty.isMoreQualifiedThan(D->getType()))
8568 return D;
8569 return nullptr;
8570 })) {
8571 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8572 /*DetectVirtual=*/false);
8573 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8574 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8575 VD->getType().getUnqualifiedType()))) {
8576 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8577 /*DiagID=*/0) !=
8578 Sema::AR_inaccessible) {
8579 SemaRef.BuildBasePathArray(Paths, BasePath);
8580 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8581 }
8582 }
8583 }
8584 }
8585 if (ReductionIdScopeSpec.isSet()) {
8586 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8587 return ExprError();
8588 }
8589 return ExprEmpty();
8590}
8591
Alexey Bataevc5e02582014-06-16 07:08:35 +00008592OMPClause *Sema::ActOnOpenMPReductionClause(
8593 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8594 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008595 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8596 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008597 auto DN = ReductionId.getName();
8598 auto OOK = DN.getCXXOverloadedOperator();
8599 BinaryOperatorKind BOK = BO_Comma;
8600
8601 // OpenMP [2.14.3.6, reduction clause]
8602 // C
8603 // reduction-identifier is either an identifier or one of the following
8604 // operators: +, -, *, &, |, ^, && and ||
8605 // C++
8606 // reduction-identifier is either an id-expression or one of the following
8607 // operators: +, -, *, &, |, ^, && and ||
8608 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8609 switch (OOK) {
8610 case OO_Plus:
8611 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008612 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008613 break;
8614 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008615 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008616 break;
8617 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008618 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008619 break;
8620 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008621 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008622 break;
8623 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008624 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008625 break;
8626 case OO_AmpAmp:
8627 BOK = BO_LAnd;
8628 break;
8629 case OO_PipePipe:
8630 BOK = BO_LOr;
8631 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008632 case OO_New:
8633 case OO_Delete:
8634 case OO_Array_New:
8635 case OO_Array_Delete:
8636 case OO_Slash:
8637 case OO_Percent:
8638 case OO_Tilde:
8639 case OO_Exclaim:
8640 case OO_Equal:
8641 case OO_Less:
8642 case OO_Greater:
8643 case OO_LessEqual:
8644 case OO_GreaterEqual:
8645 case OO_PlusEqual:
8646 case OO_MinusEqual:
8647 case OO_StarEqual:
8648 case OO_SlashEqual:
8649 case OO_PercentEqual:
8650 case OO_CaretEqual:
8651 case OO_AmpEqual:
8652 case OO_PipeEqual:
8653 case OO_LessLess:
8654 case OO_GreaterGreater:
8655 case OO_LessLessEqual:
8656 case OO_GreaterGreaterEqual:
8657 case OO_EqualEqual:
8658 case OO_ExclaimEqual:
8659 case OO_PlusPlus:
8660 case OO_MinusMinus:
8661 case OO_Comma:
8662 case OO_ArrowStar:
8663 case OO_Arrow:
8664 case OO_Call:
8665 case OO_Subscript:
8666 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008667 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008668 case NUM_OVERLOADED_OPERATORS:
8669 llvm_unreachable("Unexpected reduction identifier");
8670 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008671 if (auto II = DN.getAsIdentifierInfo()) {
8672 if (II->isStr("max"))
8673 BOK = BO_GT;
8674 else if (II->isStr("min"))
8675 BOK = BO_LT;
8676 }
8677 break;
8678 }
8679 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008680 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008681 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008682 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008683
8684 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008685 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008686 SmallVector<Expr *, 8> LHSs;
8687 SmallVector<Expr *, 8> RHSs;
8688 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008689 SmallVector<Decl *, 4> ExprCaptures;
8690 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008691 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8692 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008693 for (auto RefExpr : VarList) {
8694 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008695 // OpenMP [2.1, C/C++]
8696 // A list item is a variable or array section, subject to the restrictions
8697 // specified in Section 2.4 on page 42 and in each of the sections
8698 // describing clauses and directives for which a list appears.
8699 // OpenMP [2.14.3.3, Restrictions, p.1]
8700 // A variable that is part of another variable (as an array or
8701 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008702 if (!FirstIter && IR != ER)
8703 ++IR;
8704 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008705 SourceLocation ELoc;
8706 SourceRange ERange;
8707 Expr *SimpleRefExpr = RefExpr;
8708 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8709 /*AllowArraySection=*/true);
8710 if (Res.second) {
8711 // It will be analyzed later.
8712 Vars.push_back(RefExpr);
8713 Privates.push_back(nullptr);
8714 LHSs.push_back(nullptr);
8715 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008716 // Try to find 'declare reduction' corresponding construct before using
8717 // builtin/overloaded operators.
8718 QualType Type = Context.DependentTy;
8719 CXXCastPath BasePath;
8720 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8721 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8722 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8723 if (CurContext->isDependentContext() &&
8724 (DeclareReductionRef.isUnset() ||
8725 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8726 ReductionOps.push_back(DeclareReductionRef.get());
8727 else
8728 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008729 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008730 ValueDecl *D = Res.first;
8731 if (!D)
8732 continue;
8733
Alexey Bataeva1764212015-09-30 09:22:36 +00008734 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008735 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8736 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8737 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008738 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008739 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008740 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8741 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8742 Type = ATy->getElementType();
8743 else
8744 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008745 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008746 } else
8747 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8748 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008749
Alexey Bataevc5e02582014-06-16 07:08:35 +00008750 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8751 // A variable that appears in a private clause must not have an incomplete
8752 // type or a reference type.
8753 if (RequireCompleteType(ELoc, Type,
8754 diag::err_omp_reduction_incomplete_type))
8755 continue;
8756 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008757 // A list item that appears in a reduction clause must not be
8758 // const-qualified.
8759 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008760 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008761 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008762 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008763 bool IsDecl = !VD ||
8764 VD->isThisDeclarationADefinition(Context) ==
8765 VarDecl::DeclarationOnly;
8766 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008767 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008768 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008769 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008770 continue;
8771 }
8772 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8773 // If a list-item is a reference type then it must bind to the same object
8774 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008775 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008776 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008777 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008778 DSARefChecker Check(DSAStack);
8779 if (Check.Visit(VDDef->getInit())) {
8780 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8781 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8782 continue;
8783 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008784 }
8785 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008786
Alexey Bataevc5e02582014-06-16 07:08:35 +00008787 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8788 // in a Construct]
8789 // Variables with the predetermined data-sharing attributes may not be
8790 // listed in data-sharing attributes clauses, except for the cases
8791 // listed below. For these exceptions only, listing a predetermined
8792 // variable in a data-sharing attribute clause is allowed and overrides
8793 // the variable's predetermined data-sharing attributes.
8794 // OpenMP [2.14.3.6, Restrictions, p.3]
8795 // Any number of reduction clauses can be specified on the directive,
8796 // but a list item can appear only once in the reduction clauses for that
8797 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008798 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008799 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008800 if (DVar.CKind == OMPC_reduction) {
8801 Diag(ELoc, diag::err_omp_once_referenced)
8802 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008803 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008804 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008805 } else if (DVar.CKind != OMPC_unknown) {
8806 Diag(ELoc, diag::err_omp_wrong_dsa)
8807 << getOpenMPClauseName(DVar.CKind)
8808 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008809 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008810 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008811 }
8812
8813 // OpenMP [2.14.3.6, Restrictions, p.1]
8814 // A list item that appears in a reduction clause of a worksharing
8815 // construct must be shared in the parallel regions to which any of the
8816 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008817 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8818 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008819 !isOpenMPParallelDirective(CurrDir) &&
8820 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008821 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008822 if (DVar.CKind != OMPC_shared) {
8823 Diag(ELoc, diag::err_omp_required_access)
8824 << getOpenMPClauseName(OMPC_reduction)
8825 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008826 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008827 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008828 }
8829 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008830
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008831 // Try to find 'declare reduction' corresponding construct before using
8832 // builtin/overloaded operators.
8833 CXXCastPath BasePath;
8834 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8835 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8836 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8837 if (DeclareReductionRef.isInvalid())
8838 continue;
8839 if (CurContext->isDependentContext() &&
8840 (DeclareReductionRef.isUnset() ||
8841 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8842 Vars.push_back(RefExpr);
8843 Privates.push_back(nullptr);
8844 LHSs.push_back(nullptr);
8845 RHSs.push_back(nullptr);
8846 ReductionOps.push_back(DeclareReductionRef.get());
8847 continue;
8848 }
8849 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8850 // Not allowed reduction identifier is found.
8851 Diag(ReductionId.getLocStart(),
8852 diag::err_omp_unknown_reduction_identifier)
8853 << Type << ReductionIdRange;
8854 continue;
8855 }
8856
8857 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8858 // The type of a list item that appears in a reduction clause must be valid
8859 // for the reduction-identifier. For a max or min reduction in C, the type
8860 // of the list item must be an allowed arithmetic data type: char, int,
8861 // float, double, or _Bool, possibly modified with long, short, signed, or
8862 // unsigned. For a max or min reduction in C++, the type of the list item
8863 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8864 // double, or bool, possibly modified with long, short, signed, or unsigned.
8865 if (DeclareReductionRef.isUnset()) {
8866 if ((BOK == BO_GT || BOK == BO_LT) &&
8867 !(Type->isScalarType() ||
8868 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8869 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8870 << getLangOpts().CPlusPlus;
8871 if (!ASE && !OASE) {
8872 bool IsDecl = !VD ||
8873 VD->isThisDeclarationADefinition(Context) ==
8874 VarDecl::DeclarationOnly;
8875 Diag(D->getLocation(),
8876 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8877 << D;
8878 }
8879 continue;
8880 }
8881 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8882 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8883 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8884 if (!ASE && !OASE) {
8885 bool IsDecl = !VD ||
8886 VD->isThisDeclarationADefinition(Context) ==
8887 VarDecl::DeclarationOnly;
8888 Diag(D->getLocation(),
8889 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8890 << D;
8891 }
8892 continue;
8893 }
8894 }
8895
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008896 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008897 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008898 D->hasAttrs() ? &D->getAttrs() : nullptr);
8899 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8900 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008901 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008902 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008903 (!ASE &&
8904 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008905 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008906 // Create pseudo array type for private copy. The size for this array will
8907 // be generated during codegen.
8908 // For array subscripts or single variables Private Ty is the same as Type
8909 // (type of the variable or single array element).
8910 PrivateTy = Context.getVariableArrayType(
8911 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8912 Context.getSizeType(), VK_RValue),
8913 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008914 } else if (!ASE && !OASE &&
8915 Context.getAsArrayType(D->getType().getNonReferenceType()))
8916 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008917 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008918 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8919 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008920 // Add initializer for private variable.
8921 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008922 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8923 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8924 if (DeclareReductionRef.isUsable()) {
8925 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8926 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8927 if (DRD->getInitializer()) {
8928 Init = DRDRef;
8929 RHSVD->setInit(DRDRef);
8930 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008931 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008932 } else {
8933 switch (BOK) {
8934 case BO_Add:
8935 case BO_Xor:
8936 case BO_Or:
8937 case BO_LOr:
8938 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8939 if (Type->isScalarType() || Type->isAnyComplexType())
8940 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8941 break;
8942 case BO_Mul:
8943 case BO_LAnd:
8944 if (Type->isScalarType() || Type->isAnyComplexType()) {
8945 // '*' and '&&' reduction ops - initializer is '1'.
8946 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008947 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008948 break;
8949 case BO_And: {
8950 // '&' reduction op - initializer is '~0'.
8951 QualType OrigType = Type;
8952 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8953 Type = ComplexTy->getElementType();
8954 if (Type->isRealFloatingType()) {
8955 llvm::APFloat InitValue =
8956 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8957 /*isIEEE=*/true);
8958 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8959 Type, ELoc);
8960 } else if (Type->isScalarType()) {
8961 auto Size = Context.getTypeSize(Type);
8962 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8963 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8964 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8965 }
8966 if (Init && OrigType->isAnyComplexType()) {
8967 // Init = 0xFFFF + 0xFFFFi;
8968 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8969 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8970 }
8971 Type = OrigType;
8972 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008973 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008974 case BO_LT:
8975 case BO_GT: {
8976 // 'min' reduction op - initializer is 'Largest representable number in
8977 // the reduction list item type'.
8978 // 'max' reduction op - initializer is 'Least representable number in
8979 // the reduction list item type'.
8980 if (Type->isIntegerType() || Type->isPointerType()) {
8981 bool IsSigned = Type->hasSignedIntegerRepresentation();
8982 auto Size = Context.getTypeSize(Type);
8983 QualType IntTy =
8984 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8985 llvm::APInt InitValue =
8986 (BOK != BO_LT)
8987 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8988 : llvm::APInt::getMinValue(Size)
8989 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8990 : llvm::APInt::getMaxValue(Size);
8991 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8992 if (Type->isPointerType()) {
8993 // Cast to pointer type.
8994 auto CastExpr = BuildCStyleCastExpr(
8995 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8996 SourceLocation(), Init);
8997 if (CastExpr.isInvalid())
8998 continue;
8999 Init = CastExpr.get();
9000 }
9001 } else if (Type->isRealFloatingType()) {
9002 llvm::APFloat InitValue = llvm::APFloat::getLargest(
9003 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
9004 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
9005 Type, ELoc);
9006 }
9007 break;
9008 }
9009 case BO_PtrMemD:
9010 case BO_PtrMemI:
9011 case BO_MulAssign:
9012 case BO_Div:
9013 case BO_Rem:
9014 case BO_Sub:
9015 case BO_Shl:
9016 case BO_Shr:
9017 case BO_LE:
9018 case BO_GE:
9019 case BO_EQ:
9020 case BO_NE:
9021 case BO_AndAssign:
9022 case BO_XorAssign:
9023 case BO_OrAssign:
9024 case BO_Assign:
9025 case BO_AddAssign:
9026 case BO_SubAssign:
9027 case BO_DivAssign:
9028 case BO_RemAssign:
9029 case BO_ShlAssign:
9030 case BO_ShrAssign:
9031 case BO_Comma:
9032 llvm_unreachable("Unexpected reduction operation");
9033 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009034 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009035 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00009036 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009037 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00009038 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009039 if (RHSVD->isInvalidDecl())
9040 continue;
9041 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009042 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
9043 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00009044 bool IsDecl =
9045 !VD ||
9046 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9047 Diag(D->getLocation(),
9048 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9049 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009050 continue;
9051 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009052 // Store initializer for single element in private copy. Will be used during
9053 // codegen.
9054 PrivateVD->setInit(RHSVD->getInit());
9055 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009056 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009057 ExprResult ReductionOp;
9058 if (DeclareReductionRef.isUsable()) {
9059 QualType RedTy = DeclareReductionRef.get()->getType();
9060 QualType PtrRedTy = Context.getPointerType(RedTy);
9061 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
9062 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
9063 if (!BasePath.empty()) {
9064 LHS = DefaultLvalueConversion(LHS.get());
9065 RHS = DefaultLvalueConversion(RHS.get());
9066 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9067 CK_UncheckedDerivedToBase, LHS.get(),
9068 &BasePath, LHS.get()->getValueKind());
9069 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
9070 CK_UncheckedDerivedToBase, RHS.get(),
9071 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009072 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009073 FunctionProtoType::ExtProtoInfo EPI;
9074 QualType Params[] = {PtrRedTy, PtrRedTy};
9075 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
9076 auto *OVE = new (Context) OpaqueValueExpr(
9077 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
9078 DefaultLvalueConversion(DeclareReductionRef.get()).get());
9079 Expr *Args[] = {LHS.get(), RHS.get()};
9080 ReductionOp = new (Context)
9081 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
9082 } else {
9083 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
9084 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
9085 if (ReductionOp.isUsable()) {
9086 if (BOK != BO_LT && BOK != BO_GT) {
9087 ReductionOp =
9088 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9089 BO_Assign, LHSDRE, ReductionOp.get());
9090 } else {
9091 auto *ConditionalOp = new (Context) ConditionalOperator(
9092 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
9093 RHSDRE, Type, VK_LValue, OK_Ordinary);
9094 ReductionOp =
9095 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
9096 BO_Assign, LHSDRE, ConditionalOp);
9097 }
9098 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
9099 }
9100 if (ReductionOp.isInvalid())
9101 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009102 }
9103
Alexey Bataev60da77e2016-02-29 05:54:20 +00009104 DeclRefExpr *Ref = nullptr;
9105 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009106 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009107 if (ASE || OASE) {
9108 TransformExprToCaptures RebuildToCapture(*this, D);
9109 VarsExpr =
9110 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
9111 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00009112 } else {
9113 VarsExpr = Ref =
9114 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00009115 }
9116 if (!IsOpenMPCapturedDecl(D)) {
9117 ExprCaptures.push_back(Ref->getDecl());
9118 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9119 ExprResult RefRes = DefaultLvalueConversion(Ref);
9120 if (!RefRes.isUsable())
9121 continue;
9122 ExprResult PostUpdateRes =
9123 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9124 SimpleRefExpr, RefRes.get());
9125 if (!PostUpdateRes.isUsable())
9126 continue;
9127 ExprPostUpdates.push_back(
9128 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00009129 }
9130 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00009131 }
9132 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
9133 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009134 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00009135 LHSs.push_back(LHSDRE);
9136 RHSs.push_back(RHSDRE);
9137 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009138 }
9139
9140 if (Vars.empty())
9141 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009142
Alexey Bataevc5e02582014-06-16 07:08:35 +00009143 return OMPReductionClause::Create(
9144 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009145 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009146 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9147 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009148}
9149
Alexey Bataevecba70f2016-04-12 11:02:11 +00009150bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9151 SourceLocation LinLoc) {
9152 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9153 LinKind == OMPC_LINEAR_unknown) {
9154 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9155 return true;
9156 }
9157 return false;
9158}
9159
9160bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9161 OpenMPLinearClauseKind LinKind,
9162 QualType Type) {
9163 auto *VD = dyn_cast_or_null<VarDecl>(D);
9164 // A variable must not have an incomplete type or a reference type.
9165 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9166 return true;
9167 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9168 !Type->isReferenceType()) {
9169 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9170 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9171 return true;
9172 }
9173 Type = Type.getNonReferenceType();
9174
9175 // A list item must not be const-qualified.
9176 if (Type.isConstant(Context)) {
9177 Diag(ELoc, diag::err_omp_const_variable)
9178 << getOpenMPClauseName(OMPC_linear);
9179 if (D) {
9180 bool IsDecl =
9181 !VD ||
9182 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9183 Diag(D->getLocation(),
9184 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9185 << D;
9186 }
9187 return true;
9188 }
9189
9190 // A list item must be of integral or pointer type.
9191 Type = Type.getUnqualifiedType().getCanonicalType();
9192 const auto *Ty = Type.getTypePtrOrNull();
9193 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9194 !Ty->isPointerType())) {
9195 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9196 if (D) {
9197 bool IsDecl =
9198 !VD ||
9199 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9200 Diag(D->getLocation(),
9201 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9202 << D;
9203 }
9204 return true;
9205 }
9206 return false;
9207}
9208
Alexey Bataev182227b2015-08-20 10:54:39 +00009209OMPClause *Sema::ActOnOpenMPLinearClause(
9210 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9211 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9212 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009213 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009214 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009215 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009216 SmallVector<Decl *, 4> ExprCaptures;
9217 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009218 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009219 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009220 for (auto &RefExpr : VarList) {
9221 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009222 SourceLocation ELoc;
9223 SourceRange ERange;
9224 Expr *SimpleRefExpr = RefExpr;
9225 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9226 /*AllowArraySection=*/false);
9227 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009228 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009229 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009230 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009231 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009232 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009233 ValueDecl *D = Res.first;
9234 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009235 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009236
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009237 QualType Type = D->getType();
9238 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009239
9240 // OpenMP [2.14.3.7, linear clause]
9241 // A list-item cannot appear in more than one linear clause.
9242 // A list-item that appears in a linear clause cannot appear in any
9243 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009244 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009245 if (DVar.RefExpr) {
9246 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9247 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009248 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009249 continue;
9250 }
9251
Alexey Bataevecba70f2016-04-12 11:02:11 +00009252 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009253 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009254 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009255
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009256 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009257 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9258 D->hasAttrs() ? &D->getAttrs() : nullptr);
9259 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009260 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009261 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009262 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009263 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009264 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009265 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9266 if (!IsOpenMPCapturedDecl(D)) {
9267 ExprCaptures.push_back(Ref->getDecl());
9268 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9269 ExprResult RefRes = DefaultLvalueConversion(Ref);
9270 if (!RefRes.isUsable())
9271 continue;
9272 ExprResult PostUpdateRes =
9273 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9274 SimpleRefExpr, RefRes.get());
9275 if (!PostUpdateRes.isUsable())
9276 continue;
9277 ExprPostUpdates.push_back(
9278 IgnoredValueConversions(PostUpdateRes.get()).get());
9279 }
9280 }
9281 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009282 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009283 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009284 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009285 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009286 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009287 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009288 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9289
9290 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009291 Vars.push_back((VD || CurContext->isDependentContext())
9292 ? RefExpr->IgnoreParens()
9293 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009294 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009295 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009296 }
9297
9298 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009299 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009300
9301 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009302 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009303 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9304 !Step->isInstantiationDependent() &&
9305 !Step->containsUnexpandedParameterPack()) {
9306 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009307 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009308 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009309 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009310 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009311
Alexander Musman3276a272015-03-21 10:12:56 +00009312 // Build var to save the step value.
9313 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009314 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009315 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009316 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009317 ExprResult CalcStep =
9318 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009319 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009320
Alexander Musman8dba6642014-04-22 13:09:42 +00009321 // Warn about zero linear step (it would be probably better specified as
9322 // making corresponding variables 'const').
9323 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009324 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9325 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009326 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9327 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009328 if (!IsConstant && CalcStep.isUsable()) {
9329 // Calculate the step beforehand instead of doing this on each iteration.
9330 // (This is not used if the number of iterations may be kfold-ed).
9331 CalcStepExpr = CalcStep.get();
9332 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009333 }
9334
Alexey Bataev182227b2015-08-20 10:54:39 +00009335 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9336 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009337 StepExpr, CalcStepExpr,
9338 buildPreInits(Context, ExprCaptures),
9339 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009340}
9341
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009342static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9343 Expr *NumIterations, Sema &SemaRef,
9344 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009345 // Walk the vars and build update/final expressions for the CodeGen.
9346 SmallVector<Expr *, 8> Updates;
9347 SmallVector<Expr *, 8> Finals;
9348 Expr *Step = Clause.getStep();
9349 Expr *CalcStep = Clause.getCalcStep();
9350 // OpenMP [2.14.3.7, linear clause]
9351 // If linear-step is not specified it is assumed to be 1.
9352 if (Step == nullptr)
9353 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009354 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009355 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009356 }
Alexander Musman3276a272015-03-21 10:12:56 +00009357 bool HasErrors = false;
9358 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009359 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009360 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009361 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009362 SourceLocation ELoc;
9363 SourceRange ERange;
9364 Expr *SimpleRefExpr = RefExpr;
9365 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9366 /*AllowArraySection=*/false);
9367 ValueDecl *D = Res.first;
9368 if (Res.second || !D) {
9369 Updates.push_back(nullptr);
9370 Finals.push_back(nullptr);
9371 HasErrors = true;
9372 continue;
9373 }
9374 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9375 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9376 ->getMemberDecl();
9377 }
9378 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009379 Expr *InitExpr = *CurInit;
9380
9381 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009382 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009383 Expr *CapturedRef;
9384 if (LinKind == OMPC_LINEAR_uval)
9385 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9386 else
9387 CapturedRef =
9388 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9389 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9390 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009391
9392 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009393 ExprResult Update;
9394 if (!Info.first) {
9395 Update =
9396 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9397 InitExpr, IV, Step, /* Subtract */ false);
9398 } else
9399 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009400 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9401 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009402
9403 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009404 ExprResult Final;
9405 if (!Info.first) {
9406 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9407 InitExpr, NumIterations, Step,
9408 /* Subtract */ false);
9409 } else
9410 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009411 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9412 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009413
Alexander Musman3276a272015-03-21 10:12:56 +00009414 if (!Update.isUsable() || !Final.isUsable()) {
9415 Updates.push_back(nullptr);
9416 Finals.push_back(nullptr);
9417 HasErrors = true;
9418 } else {
9419 Updates.push_back(Update.get());
9420 Finals.push_back(Final.get());
9421 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009422 ++CurInit;
9423 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009424 }
9425 Clause.setUpdates(Updates);
9426 Clause.setFinals(Finals);
9427 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009428}
9429
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009430OMPClause *Sema::ActOnOpenMPAlignedClause(
9431 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9432 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9433
9434 SmallVector<Expr *, 8> Vars;
9435 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009436 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9437 SourceLocation ELoc;
9438 SourceRange ERange;
9439 Expr *SimpleRefExpr = RefExpr;
9440 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9441 /*AllowArraySection=*/false);
9442 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009443 // It will be analyzed later.
9444 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009445 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009446 ValueDecl *D = Res.first;
9447 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009448 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009449
Alexey Bataev1efd1662016-03-29 10:59:56 +00009450 QualType QType = D->getType();
9451 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009452
9453 // OpenMP [2.8.1, simd construct, Restrictions]
9454 // The type of list items appearing in the aligned clause must be
9455 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009456 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009457 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009458 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009459 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009460 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009461 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009462 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009463 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009464 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009465 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009466 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009467 continue;
9468 }
9469
9470 // OpenMP [2.8.1, simd construct, Restrictions]
9471 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009472 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009473 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009474 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9475 << getOpenMPClauseName(OMPC_aligned);
9476 continue;
9477 }
9478
Alexey Bataev1efd1662016-03-29 10:59:56 +00009479 DeclRefExpr *Ref = nullptr;
9480 if (!VD && IsOpenMPCapturedDecl(D))
9481 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9482 Vars.push_back(DefaultFunctionArrayConversion(
9483 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9484 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009485 }
9486
9487 // OpenMP [2.8.1, simd construct, Description]
9488 // The parameter of the aligned clause, alignment, must be a constant
9489 // positive integer expression.
9490 // If no optional parameter is specified, implementation-defined default
9491 // alignments for SIMD instructions on the target platforms are assumed.
9492 if (Alignment != nullptr) {
9493 ExprResult AlignResult =
9494 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9495 if (AlignResult.isInvalid())
9496 return nullptr;
9497 Alignment = AlignResult.get();
9498 }
9499 if (Vars.empty())
9500 return nullptr;
9501
9502 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9503 EndLoc, Vars, Alignment);
9504}
9505
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009506OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9507 SourceLocation StartLoc,
9508 SourceLocation LParenLoc,
9509 SourceLocation EndLoc) {
9510 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009511 SmallVector<Expr *, 8> SrcExprs;
9512 SmallVector<Expr *, 8> DstExprs;
9513 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009514 for (auto &RefExpr : VarList) {
9515 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9516 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009517 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009518 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009519 SrcExprs.push_back(nullptr);
9520 DstExprs.push_back(nullptr);
9521 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009522 continue;
9523 }
9524
Alexey Bataeved09d242014-05-28 05:53:51 +00009525 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009526 // OpenMP [2.1, C/C++]
9527 // A list item is a variable name.
9528 // OpenMP [2.14.4.1, Restrictions, p.1]
9529 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009530 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009531 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009532 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9533 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009534 continue;
9535 }
9536
9537 Decl *D = DE->getDecl();
9538 VarDecl *VD = cast<VarDecl>(D);
9539
9540 QualType Type = VD->getType();
9541 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9542 // It will be analyzed later.
9543 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009544 SrcExprs.push_back(nullptr);
9545 DstExprs.push_back(nullptr);
9546 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009547 continue;
9548 }
9549
9550 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9551 // A list item that appears in a copyin clause must be threadprivate.
9552 if (!DSAStack->isThreadPrivate(VD)) {
9553 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009554 << getOpenMPClauseName(OMPC_copyin)
9555 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009556 continue;
9557 }
9558
9559 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9560 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009561 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009562 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009563 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009564 auto *SrcVD =
9565 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9566 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009567 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009568 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9569 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009570 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9571 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009572 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009573 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009574 // For arrays generate assignment operation for single element and replace
9575 // it by the original array element in CodeGen.
9576 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9577 PseudoDstExpr, PseudoSrcExpr);
9578 if (AssignmentOp.isInvalid())
9579 continue;
9580 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9581 /*DiscardedValue=*/true);
9582 if (AssignmentOp.isInvalid())
9583 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009584
9585 DSAStack->addDSA(VD, DE, OMPC_copyin);
9586 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009587 SrcExprs.push_back(PseudoSrcExpr);
9588 DstExprs.push_back(PseudoDstExpr);
9589 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009590 }
9591
Alexey Bataeved09d242014-05-28 05:53:51 +00009592 if (Vars.empty())
9593 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009594
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009595 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9596 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009597}
9598
Alexey Bataevbae9a792014-06-27 10:37:06 +00009599OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9600 SourceLocation StartLoc,
9601 SourceLocation LParenLoc,
9602 SourceLocation EndLoc) {
9603 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009604 SmallVector<Expr *, 8> SrcExprs;
9605 SmallVector<Expr *, 8> DstExprs;
9606 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009607 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009608 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9609 SourceLocation ELoc;
9610 SourceRange ERange;
9611 Expr *SimpleRefExpr = RefExpr;
9612 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9613 /*AllowArraySection=*/false);
9614 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009615 // It will be analyzed later.
9616 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009617 SrcExprs.push_back(nullptr);
9618 DstExprs.push_back(nullptr);
9619 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009620 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009621 ValueDecl *D = Res.first;
9622 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009623 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009624
Alexey Bataeve122da12016-03-17 10:50:17 +00009625 QualType Type = D->getType();
9626 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009627
9628 // OpenMP [2.14.4.2, Restrictions, p.2]
9629 // A list item that appears in a copyprivate clause may not appear in a
9630 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009631 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9632 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009633 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9634 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009635 Diag(ELoc, diag::err_omp_wrong_dsa)
9636 << getOpenMPClauseName(DVar.CKind)
9637 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009638 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009639 continue;
9640 }
9641
9642 // OpenMP [2.11.4.2, Restrictions, p.1]
9643 // All list items that appear in a copyprivate clause must be either
9644 // threadprivate or private in the enclosing context.
9645 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009646 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009647 if (DVar.CKind == OMPC_shared) {
9648 Diag(ELoc, diag::err_omp_required_access)
9649 << getOpenMPClauseName(OMPC_copyprivate)
9650 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009651 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009652 continue;
9653 }
9654 }
9655 }
9656
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009657 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009658 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009659 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009660 << getOpenMPClauseName(OMPC_copyprivate) << Type
9661 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009662 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009663 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009664 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009665 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009666 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009667 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009668 continue;
9669 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009670
Alexey Bataevbae9a792014-06-27 10:37:06 +00009671 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9672 // A variable of class type (or array thereof) that appears in a
9673 // copyin clause requires an accessible, unambiguous copy assignment
9674 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009675 Type = Context.getBaseElementType(Type.getNonReferenceType())
9676 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009677 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009678 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9679 D->hasAttrs() ? &D->getAttrs() : nullptr);
9680 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009681 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009682 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9683 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009684 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009685 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009686 PseudoDstExpr, PseudoSrcExpr);
9687 if (AssignmentOp.isInvalid())
9688 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009689 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009690 /*DiscardedValue=*/true);
9691 if (AssignmentOp.isInvalid())
9692 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009693
9694 // No need to mark vars as copyprivate, they are already threadprivate or
9695 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009696 assert(VD || IsOpenMPCapturedDecl(D));
9697 Vars.push_back(
9698 VD ? RefExpr->IgnoreParens()
9699 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009700 SrcExprs.push_back(PseudoSrcExpr);
9701 DstExprs.push_back(PseudoDstExpr);
9702 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009703 }
9704
9705 if (Vars.empty())
9706 return nullptr;
9707
Alexey Bataeva63048e2015-03-23 06:18:07 +00009708 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9709 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009710}
9711
Alexey Bataev6125da92014-07-21 11:26:11 +00009712OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9713 SourceLocation StartLoc,
9714 SourceLocation LParenLoc,
9715 SourceLocation EndLoc) {
9716 if (VarList.empty())
9717 return nullptr;
9718
9719 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9720}
Alexey Bataevdea47612014-07-23 07:46:59 +00009721
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009722OMPClause *
9723Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9724 SourceLocation DepLoc, SourceLocation ColonLoc,
9725 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9726 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009727 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009728 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009729 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009730 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009731 return nullptr;
9732 }
9733 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009734 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9735 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009736 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009737 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009738 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9739 /*Last=*/OMPC_DEPEND_unknown, Except)
9740 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009741 return nullptr;
9742 }
9743 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009744 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009745 llvm::APSInt DepCounter(/*BitWidth=*/32);
9746 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9747 if (DepKind == OMPC_DEPEND_sink) {
9748 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9749 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9750 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009751 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009752 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009753 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9754 DSAStack->getParentOrderedRegionParam()) {
9755 for (auto &RefExpr : VarList) {
9756 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009757 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009758 // It will be analyzed later.
9759 Vars.push_back(RefExpr);
9760 continue;
9761 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009762
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009763 SourceLocation ELoc = RefExpr->getExprLoc();
9764 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9765 if (DepKind == OMPC_DEPEND_sink) {
9766 if (DepCounter >= TotalDepCount) {
9767 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9768 continue;
9769 }
9770 ++DepCounter;
9771 // OpenMP [2.13.9, Summary]
9772 // depend(dependence-type : vec), where dependence-type is:
9773 // 'sink' and where vec is the iteration vector, which has the form:
9774 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9775 // where n is the value specified by the ordered clause in the loop
9776 // directive, xi denotes the loop iteration variable of the i-th nested
9777 // loop associated with the loop directive, and di is a constant
9778 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009779 if (CurContext->isDependentContext()) {
9780 // It will be analyzed later.
9781 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009782 continue;
9783 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009784 SimpleExpr = SimpleExpr->IgnoreImplicit();
9785 OverloadedOperatorKind OOK = OO_None;
9786 SourceLocation OOLoc;
9787 Expr *LHS = SimpleExpr;
9788 Expr *RHS = nullptr;
9789 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9790 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9791 OOLoc = BO->getOperatorLoc();
9792 LHS = BO->getLHS()->IgnoreParenImpCasts();
9793 RHS = BO->getRHS()->IgnoreParenImpCasts();
9794 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9795 OOK = OCE->getOperator();
9796 OOLoc = OCE->getOperatorLoc();
9797 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9798 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9799 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9800 OOK = MCE->getMethodDecl()
9801 ->getNameInfo()
9802 .getName()
9803 .getCXXOverloadedOperator();
9804 OOLoc = MCE->getCallee()->getExprLoc();
9805 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9806 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9807 }
9808 SourceLocation ELoc;
9809 SourceRange ERange;
9810 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9811 /*AllowArraySection=*/false);
9812 if (Res.second) {
9813 // It will be analyzed later.
9814 Vars.push_back(RefExpr);
9815 }
9816 ValueDecl *D = Res.first;
9817 if (!D)
9818 continue;
9819
9820 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9821 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9822 continue;
9823 }
9824 if (RHS) {
9825 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9826 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9827 if (RHSRes.isInvalid())
9828 continue;
9829 }
9830 if (!CurContext->isDependentContext() &&
9831 DSAStack->getParentOrderedRegionParam() &&
9832 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9833 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9834 << DSAStack->getParentLoopControlVariable(
9835 DepCounter.getZExtValue());
9836 continue;
9837 }
9838 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009839 } else {
9840 // OpenMP [2.11.1.1, Restrictions, p.3]
9841 // A variable that is part of another variable (such as a field of a
9842 // structure) but is not an array element or an array section cannot
9843 // appear in a depend clause.
9844 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9845 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9846 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9847 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9848 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009849 (ASE &&
9850 !ASE->getBase()
9851 ->getType()
9852 .getNonReferenceType()
9853 ->isPointerType() &&
9854 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009855 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9856 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009857 continue;
9858 }
9859 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009860 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9861 }
9862
9863 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9864 TotalDepCount > VarList.size() &&
9865 DSAStack->getParentOrderedRegionParam()) {
9866 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9867 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9868 }
9869 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9870 Vars.empty())
9871 return nullptr;
9872 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009873 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9874 DepKind, DepLoc, ColonLoc, Vars);
9875 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9876 DSAStack->addDoacrossDependClause(C, OpsOffs);
9877 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009878}
Michael Wonge710d542015-08-07 16:16:36 +00009879
9880OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9881 SourceLocation LParenLoc,
9882 SourceLocation EndLoc) {
9883 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009884
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009885 // OpenMP [2.9.1, Restrictions]
9886 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009887 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9888 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009889 return nullptr;
9890
Michael Wonge710d542015-08-07 16:16:36 +00009891 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9892}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009893
9894static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9895 DSAStackTy *Stack, CXXRecordDecl *RD) {
9896 if (!RD || RD->isInvalidDecl())
9897 return true;
9898
9899 auto QTy = SemaRef.Context.getRecordType(RD);
9900 if (RD->isDynamicClass()) {
9901 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9902 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9903 return false;
9904 }
9905 auto *DC = RD;
9906 bool IsCorrect = true;
9907 for (auto *I : DC->decls()) {
9908 if (I) {
9909 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9910 if (MD->isStatic()) {
9911 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9912 SemaRef.Diag(MD->getLocation(),
9913 diag::note_omp_static_member_in_target);
9914 IsCorrect = false;
9915 }
9916 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9917 if (VD->isStaticDataMember()) {
9918 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9919 SemaRef.Diag(VD->getLocation(),
9920 diag::note_omp_static_member_in_target);
9921 IsCorrect = false;
9922 }
9923 }
9924 }
9925 }
9926
9927 for (auto &I : RD->bases()) {
9928 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9929 I.getType()->getAsCXXRecordDecl()))
9930 IsCorrect = false;
9931 }
9932 return IsCorrect;
9933}
9934
9935static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9936 DSAStackTy *Stack, QualType QTy) {
9937 NamedDecl *ND;
9938 if (QTy->isIncompleteType(&ND)) {
9939 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9940 return false;
9941 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009942 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009943 return false;
9944 }
9945 return true;
9946}
9947
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009948/// \brief Return true if it can be proven that the provided array expression
9949/// (array section or array subscript) does NOT specify the whole size of the
9950/// array whose base type is \a BaseQTy.
9951static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9952 const Expr *E,
9953 QualType BaseQTy) {
9954 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9955
9956 // If this is an array subscript, it refers to the whole size if the size of
9957 // the dimension is constant and equals 1. Also, an array section assumes the
9958 // format of an array subscript if no colon is used.
9959 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9960 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9961 return ATy->getSize().getSExtValue() != 1;
9962 // Size can't be evaluated statically.
9963 return false;
9964 }
9965
9966 assert(OASE && "Expecting array section if not an array subscript.");
9967 auto *LowerBound = OASE->getLowerBound();
9968 auto *Length = OASE->getLength();
9969
9970 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009971 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009972 if (LowerBound) {
9973 llvm::APSInt ConstLowerBound;
9974 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9975 return false; // Can't get the integer value as a constant.
9976 if (ConstLowerBound.getSExtValue())
9977 return true;
9978 }
9979
9980 // If we don't have a length we covering the whole dimension.
9981 if (!Length)
9982 return false;
9983
9984 // If the base is a pointer, we don't have a way to get the size of the
9985 // pointee.
9986 if (BaseQTy->isPointerType())
9987 return false;
9988
9989 // We can only check if the length is the same as the size of the dimension
9990 // if we have a constant array.
9991 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9992 if (!CATy)
9993 return false;
9994
9995 llvm::APSInt ConstLength;
9996 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9997 return false; // Can't get the integer value as a constant.
9998
9999 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
10000}
10001
10002// Return true if it can be proven that the provided array expression (array
10003// section or array subscript) does NOT specify a single element of the array
10004// whose base type is \a BaseQTy.
10005static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000010006 const Expr *E,
10007 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010008 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
10009
10010 // An array subscript always refer to a single element. Also, an array section
10011 // assumes the format of an array subscript if no colon is used.
10012 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
10013 return false;
10014
10015 assert(OASE && "Expecting array section if not an array subscript.");
10016 auto *Length = OASE->getLength();
10017
10018 // If we don't have a length we have to check if the array has unitary size
10019 // for this dimension. Also, we should always expect a length if the base type
10020 // is pointer.
10021 if (!Length) {
10022 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
10023 return ATy->getSize().getSExtValue() != 1;
10024 // We cannot assume anything.
10025 return false;
10026 }
10027
10028 // Check if the length evaluates to 1.
10029 llvm::APSInt ConstLength;
10030 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
10031 return false; // Can't get the integer value as a constant.
10032
10033 return ConstLength.getSExtValue() != 1;
10034}
10035
Samuel Antao661c0902016-05-26 17:39:58 +000010036// Return the expression of the base of the mappable expression or null if it
10037// cannot be determined and do all the necessary checks to see if the expression
10038// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000010039// components of the expression.
10040static Expr *CheckMapClauseExpressionBase(
10041 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000010042 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
10043 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010044 SourceLocation ELoc = E->getExprLoc();
10045 SourceRange ERange = E->getSourceRange();
10046
10047 // The base of elements of list in a map clause have to be either:
10048 // - a reference to variable or field.
10049 // - a member expression.
10050 // - an array expression.
10051 //
10052 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
10053 // reference to 'r'.
10054 //
10055 // If we have:
10056 //
10057 // struct SS {
10058 // Bla S;
10059 // foo() {
10060 // #pragma omp target map (S.Arr[:12]);
10061 // }
10062 // }
10063 //
10064 // We want to retrieve the member expression 'this->S';
10065
10066 Expr *RelevantExpr = nullptr;
10067
Samuel Antao5de996e2016-01-22 20:21:36 +000010068 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
10069 // If a list item is an array section, it must specify contiguous storage.
10070 //
10071 // For this restriction it is sufficient that we make sure only references
10072 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010073 // exist except in the rightmost expression (unless they cover the whole
10074 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000010075 //
10076 // r.ArrS[3:5].Arr[6:7]
10077 //
10078 // r.ArrS[3:5].x
10079 //
10080 // but these would be valid:
10081 // r.ArrS[3].Arr[6:7]
10082 //
10083 // r.ArrS[3].x
10084
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010085 bool AllowUnitySizeArraySection = true;
10086 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000010087
Dmitry Polukhin644a9252016-03-11 07:58:34 +000010088 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010089 E = E->IgnoreParenImpCasts();
10090
10091 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
10092 if (!isa<VarDecl>(CurE->getDecl()))
10093 break;
10094
10095 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010096
10097 // If we got a reference to a declaration, we should not expect any array
10098 // section before that.
10099 AllowUnitySizeArraySection = false;
10100 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010101
10102 // Record the component.
10103 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
10104 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +000010105 continue;
10106 }
10107
10108 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
10109 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
10110
10111 if (isa<CXXThisExpr>(BaseE))
10112 // We found a base expression: this->Val.
10113 RelevantExpr = CurE;
10114 else
10115 E = BaseE;
10116
10117 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
10118 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
10119 << CurE->getSourceRange();
10120 break;
10121 }
10122
10123 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
10124
10125 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
10126 // A bit-field cannot appear in a map clause.
10127 //
10128 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010129 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
10130 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010131 break;
10132 }
10133
10134 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10135 // If the type of a list item is a reference to a type T then the type
10136 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010137 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010138
10139 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10140 // A list item cannot be a variable that is a member of a structure with
10141 // a union type.
10142 //
10143 if (auto *RT = CurType->getAs<RecordType>())
10144 if (RT->isUnionType()) {
10145 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10146 << CurE->getSourceRange();
10147 break;
10148 }
10149
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010150 // If we got a member expression, we should not expect any array section
10151 // before that:
10152 //
10153 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10154 // If a list item is an element of a structure, only the rightmost symbol
10155 // of the variable reference can be an array section.
10156 //
10157 AllowUnitySizeArraySection = false;
10158 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010159
10160 // Record the component.
10161 CurComponents.push_back(
10162 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010163 continue;
10164 }
10165
10166 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10167 E = CurE->getBase()->IgnoreParenImpCasts();
10168
10169 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10170 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10171 << 0 << CurE->getSourceRange();
10172 break;
10173 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010174
10175 // If we got an array subscript that express the whole dimension we
10176 // can have any array expressions before. If it only expressing part of
10177 // the dimension, we can only have unitary-size array expressions.
10178 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10179 E->getType()))
10180 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010181
10182 // Record the component - we don't have any declaration associated.
10183 CurComponents.push_back(
10184 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010185 continue;
10186 }
10187
10188 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010189 E = CurE->getBase()->IgnoreParenImpCasts();
10190
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010191 auto CurType =
10192 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10193
Samuel Antao5de996e2016-01-22 20:21:36 +000010194 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10195 // If the type of a list item is a reference to a type T then the type
10196 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010197 if (CurType->isReferenceType())
10198 CurType = CurType->getPointeeType();
10199
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010200 bool IsPointer = CurType->isAnyPointerType();
10201
10202 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010203 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10204 << 0 << CurE->getSourceRange();
10205 break;
10206 }
10207
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010208 bool NotWhole =
10209 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10210 bool NotUnity =
10211 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10212
Samuel Antaodab51bb2016-07-18 23:22:11 +000010213 if (AllowWholeSizeArraySection) {
10214 // Any array section is currently allowed. Allowing a whole size array
10215 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010216 //
10217 // If this array section refers to the whole dimension we can still
10218 // accept other array sections before this one, except if the base is a
10219 // pointer. Otherwise, only unitary sections are accepted.
10220 if (NotWhole || IsPointer)
10221 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010222 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010223 // A unity or whole array section is not allowed and that is not
10224 // compatible with the properties of the current array section.
10225 SemaRef.Diag(
10226 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10227 << CurE->getSourceRange();
10228 break;
10229 }
Samuel Antao90927002016-04-26 14:54:23 +000010230
10231 // Record the component - we don't have any declaration associated.
10232 CurComponents.push_back(
10233 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010234 continue;
10235 }
10236
10237 // If nothing else worked, this is not a valid map clause expression.
10238 SemaRef.Diag(ELoc,
10239 diag::err_omp_expected_named_var_member_or_array_expression)
10240 << ERange;
10241 break;
10242 }
10243
10244 return RelevantExpr;
10245}
10246
10247// Return true if expression E associated with value VD has conflicts with other
10248// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010249static bool CheckMapConflicts(
10250 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10251 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010252 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10253 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010254 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010255 SourceLocation ELoc = E->getExprLoc();
10256 SourceRange ERange = E->getSourceRange();
10257
10258 // In order to easily check the conflicts we need to match each component of
10259 // the expression under test with the components of the expressions that are
10260 // already in the stack.
10261
Samuel Antao5de996e2016-01-22 20:21:36 +000010262 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010263 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010264 "Map clause expression with unexpected base!");
10265
10266 // Variables to help detecting enclosing problems in data environment nests.
10267 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010268 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010269
Samuel Antao90927002016-04-26 14:54:23 +000010270 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10271 VD, CurrentRegionOnly,
10272 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010273 StackComponents,
10274 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010275
Samuel Antao5de996e2016-01-22 20:21:36 +000010276 assert(!StackComponents.empty() &&
10277 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010278 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010279 "Map clause expression with unexpected base!");
10280
Samuel Antao90927002016-04-26 14:54:23 +000010281 // The whole expression in the stack.
10282 auto *RE = StackComponents.front().getAssociatedExpression();
10283
Samuel Antao5de996e2016-01-22 20:21:36 +000010284 // Expressions must start from the same base. Here we detect at which
10285 // point both expressions diverge from each other and see if we can
10286 // detect if the memory referred to both expressions is contiguous and
10287 // do not overlap.
10288 auto CI = CurComponents.rbegin();
10289 auto CE = CurComponents.rend();
10290 auto SI = StackComponents.rbegin();
10291 auto SE = StackComponents.rend();
10292 for (; CI != CE && SI != SE; ++CI, ++SI) {
10293
10294 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10295 // At most one list item can be an array item derived from a given
10296 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010297 if (CurrentRegionOnly &&
10298 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10299 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10300 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10301 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10302 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010303 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010304 << CI->getAssociatedExpression()->getSourceRange();
10305 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10306 diag::note_used_here)
10307 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010308 return true;
10309 }
10310
10311 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010312 if (CI->getAssociatedExpression()->getStmtClass() !=
10313 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010314 break;
10315
10316 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010317 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010318 break;
10319 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010320 // Check if the extra components of the expressions in the enclosing
10321 // data environment are redundant for the current base declaration.
10322 // If they are, the maps completely overlap, which is legal.
10323 for (; SI != SE; ++SI) {
10324 QualType Type;
10325 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010326 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010327 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010328 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10329 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010330 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10331 Type =
10332 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10333 }
10334 if (Type.isNull() || Type->isAnyPointerType() ||
10335 CheckArrayExpressionDoesNotReferToWholeSize(
10336 SemaRef, SI->getAssociatedExpression(), Type))
10337 break;
10338 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010339
10340 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10341 // List items of map clauses in the same construct must not share
10342 // original storage.
10343 //
10344 // If the expressions are exactly the same or one is a subset of the
10345 // other, it means they are sharing storage.
10346 if (CI == CE && SI == SE) {
10347 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010348 if (CKind == OMPC_map)
10349 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10350 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010351 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010352 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10353 << ERange;
10354 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010355 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10356 << RE->getSourceRange();
10357 return true;
10358 } else {
10359 // If we find the same expression in the enclosing data environment,
10360 // that is legal.
10361 IsEnclosedByDataEnvironmentExpr = true;
10362 return false;
10363 }
10364 }
10365
Samuel Antao90927002016-04-26 14:54:23 +000010366 QualType DerivedType =
10367 std::prev(CI)->getAssociatedDeclaration()->getType();
10368 SourceLocation DerivedLoc =
10369 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010370
10371 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10372 // If the type of a list item is a reference to a type T then the type
10373 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010374 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010375
10376 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10377 // A variable for which the type is pointer and an array section
10378 // derived from that variable must not appear as list items of map
10379 // clauses of the same construct.
10380 //
10381 // Also, cover one of the cases in:
10382 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10383 // If any part of the original storage of a list item has corresponding
10384 // storage in the device data environment, all of the original storage
10385 // must have corresponding storage in the device data environment.
10386 //
10387 if (DerivedType->isAnyPointerType()) {
10388 if (CI == CE || SI == SE) {
10389 SemaRef.Diag(
10390 DerivedLoc,
10391 diag::err_omp_pointer_mapped_along_with_derived_section)
10392 << DerivedLoc;
10393 } else {
10394 assert(CI != CE && SI != SE);
10395 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10396 << DerivedLoc;
10397 }
10398 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10399 << RE->getSourceRange();
10400 return true;
10401 }
10402
10403 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10404 // List items of map clauses in the same construct must not share
10405 // original storage.
10406 //
10407 // An expression is a subset of the other.
10408 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010409 if (CKind == OMPC_map)
10410 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10411 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010412 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010413 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10414 << ERange;
10415 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010416 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10417 << RE->getSourceRange();
10418 return true;
10419 }
10420
10421 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010422 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010423 if (!CurrentRegionOnly && SI != SE)
10424 EnclosingExpr = RE;
10425
10426 // The current expression is a subset of the expression in the data
10427 // environment.
10428 IsEnclosedByDataEnvironmentExpr |=
10429 (!CurrentRegionOnly && CI != CE && SI == SE);
10430
10431 return false;
10432 });
10433
10434 if (CurrentRegionOnly)
10435 return FoundError;
10436
10437 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10438 // If any part of the original storage of a list item has corresponding
10439 // storage in the device data environment, all of the original storage must
10440 // have corresponding storage in the device data environment.
10441 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10442 // If a list item is an element of a structure, and a different element of
10443 // the structure has a corresponding list item in the device data environment
10444 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010445 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010446 // data environment prior to the task encountering the construct.
10447 //
10448 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10449 SemaRef.Diag(ELoc,
10450 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10451 << ERange;
10452 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10453 << EnclosingExpr->getSourceRange();
10454 return true;
10455 }
10456
10457 return FoundError;
10458}
10459
Samuel Antao661c0902016-05-26 17:39:58 +000010460namespace {
10461// Utility struct that gathers all the related lists associated with a mappable
10462// expression.
10463struct MappableVarListInfo final {
10464 // The list of expressions.
10465 ArrayRef<Expr *> VarList;
10466 // The list of processed expressions.
10467 SmallVector<Expr *, 16> ProcessedVarList;
10468 // The mappble components for each expression.
10469 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10470 // The base declaration of the variable.
10471 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10472
10473 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10474 // We have a list of components and base declarations for each entry in the
10475 // variable list.
10476 VarComponents.reserve(VarList.size());
10477 VarBaseDeclarations.reserve(VarList.size());
10478 }
10479};
10480}
10481
10482// Check the validity of the provided variable list for the provided clause kind
10483// \a CKind. In the check process the valid expressions, and mappable expression
10484// components and variables are extracted and used to fill \a Vars,
10485// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10486// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10487static void
10488checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10489 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10490 SourceLocation StartLoc,
10491 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10492 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010493 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10494 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010495 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010496
Samuel Antao90927002016-04-26 14:54:23 +000010497 // Keep track of the mappable components and base declarations in this clause.
10498 // Each entry in the list is going to have a list of components associated. We
10499 // record each set of the components so that we can build the clause later on.
10500 // In the end we should have the same amount of declarations and component
10501 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010502
Samuel Antao661c0902016-05-26 17:39:58 +000010503 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010504 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010505 SourceLocation ELoc = RE->getExprLoc();
10506
Kelvin Li0bff7af2015-11-23 05:32:03 +000010507 auto *VE = RE->IgnoreParenLValueCasts();
10508
10509 if (VE->isValueDependent() || VE->isTypeDependent() ||
10510 VE->isInstantiationDependent() ||
10511 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010512 // We can only analyze this information once the missing information is
10513 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010514 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010515 continue;
10516 }
10517
10518 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010519
Samuel Antao5de996e2016-01-22 20:21:36 +000010520 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010521 SemaRef.Diag(ELoc,
10522 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010523 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010524 continue;
10525 }
10526
Samuel Antao90927002016-04-26 14:54:23 +000010527 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10528 ValueDecl *CurDeclaration = nullptr;
10529
10530 // Obtain the array or member expression bases if required. Also, fill the
10531 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010532 auto *BE =
10533 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010534 if (!BE)
10535 continue;
10536
Samuel Antao90927002016-04-26 14:54:23 +000010537 assert(!CurComponents.empty() &&
10538 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010539
Samuel Antao90927002016-04-26 14:54:23 +000010540 // For the following checks, we rely on the base declaration which is
10541 // expected to be associated with the last component. The declaration is
10542 // expected to be a variable or a field (if 'this' is being mapped).
10543 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10544 assert(CurDeclaration && "Null decl on map clause.");
10545 assert(
10546 CurDeclaration->isCanonicalDecl() &&
10547 "Expecting components to have associated only canonical declarations.");
10548
10549 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10550 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010551
10552 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010553 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010554
10555 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010556 // threadprivate variables cannot appear in a map clause.
10557 // OpenMP 4.5 [2.10.5, target update Construct]
10558 // threadprivate variables cannot appear in a from clause.
10559 if (VD && DSAS->isThreadPrivate(VD)) {
10560 auto DVar = DSAS->getTopDSA(VD, false);
10561 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10562 << getOpenMPClauseName(CKind);
10563 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010564 continue;
10565 }
10566
Samuel Antao5de996e2016-01-22 20:21:36 +000010567 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10568 // A list item cannot appear in both a map clause and a data-sharing
10569 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010570
Samuel Antao5de996e2016-01-22 20:21:36 +000010571 // Check conflicts with other map clause expressions. We check the conflicts
10572 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010573 // environment, because the restrictions are different. We only have to
10574 // check conflicts across regions for the map clauses.
10575 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10576 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010577 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010578 if (CKind == OMPC_map &&
10579 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10580 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010581 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010582
Samuel Antao661c0902016-05-26 17:39:58 +000010583 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010584 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10585 // If the type of a list item is a reference to a type T then the type will
10586 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010587 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010588
Samuel Antao661c0902016-05-26 17:39:58 +000010589 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10590 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010591 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010592 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010593 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10594 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010595 continue;
10596
Samuel Antao661c0902016-05-26 17:39:58 +000010597 if (CKind == OMPC_map) {
10598 // target enter data
10599 // OpenMP [2.10.2, Restrictions, p. 99]
10600 // A map-type must be specified in all map clauses and must be either
10601 // to or alloc.
10602 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10603 if (DKind == OMPD_target_enter_data &&
10604 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10605 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10606 << (IsMapTypeImplicit ? 1 : 0)
10607 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10608 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010609 continue;
10610 }
Samuel Antao661c0902016-05-26 17:39:58 +000010611
10612 // target exit_data
10613 // OpenMP [2.10.3, Restrictions, p. 102]
10614 // A map-type must be specified in all map clauses and must be either
10615 // from, release, or delete.
10616 if (DKind == OMPD_target_exit_data &&
10617 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10618 MapType == OMPC_MAP_delete)) {
10619 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10620 << (IsMapTypeImplicit ? 1 : 0)
10621 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10622 << getOpenMPDirectiveName(DKind);
10623 continue;
10624 }
10625
10626 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10627 // A list item cannot appear in both a map clause and a data-sharing
10628 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010629 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010630 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010631 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010632 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10633 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010634 auto DVar = DSAS->getTopDSA(VD, false);
10635 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010636 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010637 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010638 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010639 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10640 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10641 continue;
10642 }
10643 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010644 }
10645
Samuel Antao90927002016-04-26 14:54:23 +000010646 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010647 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010648
10649 // Store the components in the stack so that they can be used to check
10650 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010651 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10652 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010653
10654 // Save the components and declaration to create the clause. For purposes of
10655 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010656 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010657 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10658 MVLI.VarComponents.back().append(CurComponents.begin(),
10659 CurComponents.end());
10660 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10661 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010662 }
Samuel Antao661c0902016-05-26 17:39:58 +000010663}
10664
10665OMPClause *
10666Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10667 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10668 SourceLocation MapLoc, SourceLocation ColonLoc,
10669 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10670 SourceLocation LParenLoc, SourceLocation EndLoc) {
10671 MappableVarListInfo MVLI(VarList);
10672 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10673 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010674
Samuel Antao5de996e2016-01-22 20:21:36 +000010675 // We need to produce a map clause even if we don't have variables so that
10676 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010677 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10678 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10679 MVLI.VarComponents, MapTypeModifier, MapType,
10680 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010681}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010682
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010683QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10684 TypeResult ParsedType) {
10685 assert(ParsedType.isUsable());
10686
10687 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10688 if (ReductionType.isNull())
10689 return QualType();
10690
10691 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10692 // A type name in a declare reduction directive cannot be a function type, an
10693 // array type, a reference type, or a type qualified with const, volatile or
10694 // restrict.
10695 if (ReductionType.hasQualifiers()) {
10696 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10697 return QualType();
10698 }
10699
10700 if (ReductionType->isFunctionType()) {
10701 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10702 return QualType();
10703 }
10704 if (ReductionType->isReferenceType()) {
10705 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10706 return QualType();
10707 }
10708 if (ReductionType->isArrayType()) {
10709 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10710 return QualType();
10711 }
10712 return ReductionType;
10713}
10714
10715Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10716 Scope *S, DeclContext *DC, DeclarationName Name,
10717 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10718 AccessSpecifier AS, Decl *PrevDeclInScope) {
10719 SmallVector<Decl *, 8> Decls;
10720 Decls.reserve(ReductionTypes.size());
10721
10722 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10723 ForRedeclaration);
10724 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10725 // A reduction-identifier may not be re-declared in the current scope for the
10726 // same type or for a type that is compatible according to the base language
10727 // rules.
10728 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10729 OMPDeclareReductionDecl *PrevDRD = nullptr;
10730 bool InCompoundScope = true;
10731 if (S != nullptr) {
10732 // Find previous declaration with the same name not referenced in other
10733 // declarations.
10734 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10735 InCompoundScope =
10736 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10737 LookupName(Lookup, S);
10738 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10739 /*AllowInlineNamespace=*/false);
10740 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10741 auto Filter = Lookup.makeFilter();
10742 while (Filter.hasNext()) {
10743 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10744 if (InCompoundScope) {
10745 auto I = UsedAsPrevious.find(PrevDecl);
10746 if (I == UsedAsPrevious.end())
10747 UsedAsPrevious[PrevDecl] = false;
10748 if (auto *D = PrevDecl->getPrevDeclInScope())
10749 UsedAsPrevious[D] = true;
10750 }
10751 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10752 PrevDecl->getLocation();
10753 }
10754 Filter.done();
10755 if (InCompoundScope) {
10756 for (auto &PrevData : UsedAsPrevious) {
10757 if (!PrevData.second) {
10758 PrevDRD = PrevData.first;
10759 break;
10760 }
10761 }
10762 }
10763 } else if (PrevDeclInScope != nullptr) {
10764 auto *PrevDRDInScope = PrevDRD =
10765 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10766 do {
10767 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10768 PrevDRDInScope->getLocation();
10769 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10770 } while (PrevDRDInScope != nullptr);
10771 }
10772 for (auto &TyData : ReductionTypes) {
10773 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10774 bool Invalid = false;
10775 if (I != PreviousRedeclTypes.end()) {
10776 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10777 << TyData.first;
10778 Diag(I->second, diag::note_previous_definition);
10779 Invalid = true;
10780 }
10781 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10782 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10783 Name, TyData.first, PrevDRD);
10784 DC->addDecl(DRD);
10785 DRD->setAccess(AS);
10786 Decls.push_back(DRD);
10787 if (Invalid)
10788 DRD->setInvalidDecl();
10789 else
10790 PrevDRD = DRD;
10791 }
10792
10793 return DeclGroupPtrTy::make(
10794 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10795}
10796
10797void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10798 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10799
10800 // Enter new function scope.
10801 PushFunctionScope();
10802 getCurFunction()->setHasBranchProtectedScope();
10803 getCurFunction()->setHasOMPDeclareReductionCombiner();
10804
10805 if (S != nullptr)
10806 PushDeclContext(S, DRD);
10807 else
10808 CurContext = DRD;
10809
10810 PushExpressionEvaluationContext(PotentiallyEvaluated);
10811
10812 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010813 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10814 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10815 // uses semantics of argument handles by value, but it should be passed by
10816 // reference. C lang does not support references, so pass all parameters as
10817 // pointers.
10818 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010819 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010820 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010821 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10822 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10823 // uses semantics of argument handles by value, but it should be passed by
10824 // reference. C lang does not support references, so pass all parameters as
10825 // pointers.
10826 // Create 'T omp_out;' variable.
10827 auto *OmpOutParm =
10828 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10829 if (S != nullptr) {
10830 PushOnScopeChains(OmpInParm, S);
10831 PushOnScopeChains(OmpOutParm, S);
10832 } else {
10833 DRD->addDecl(OmpInParm);
10834 DRD->addDecl(OmpOutParm);
10835 }
10836}
10837
10838void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10839 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10840 DiscardCleanupsInEvaluationContext();
10841 PopExpressionEvaluationContext();
10842
10843 PopDeclContext();
10844 PopFunctionScopeInfo();
10845
10846 if (Combiner != nullptr)
10847 DRD->setCombiner(Combiner);
10848 else
10849 DRD->setInvalidDecl();
10850}
10851
10852void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10853 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10854
10855 // Enter new function scope.
10856 PushFunctionScope();
10857 getCurFunction()->setHasBranchProtectedScope();
10858
10859 if (S != nullptr)
10860 PushDeclContext(S, DRD);
10861 else
10862 CurContext = DRD;
10863
10864 PushExpressionEvaluationContext(PotentiallyEvaluated);
10865
10866 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010867 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10868 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10869 // uses semantics of argument handles by value, but it should be passed by
10870 // reference. C lang does not support references, so pass all parameters as
10871 // pointers.
10872 // Create 'T omp_priv;' variable.
10873 auto *OmpPrivParm =
10874 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010875 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10876 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10877 // uses semantics of argument handles by value, but it should be passed by
10878 // reference. C lang does not support references, so pass all parameters as
10879 // pointers.
10880 // Create 'T omp_orig;' variable.
10881 auto *OmpOrigParm =
10882 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010883 if (S != nullptr) {
10884 PushOnScopeChains(OmpPrivParm, S);
10885 PushOnScopeChains(OmpOrigParm, S);
10886 } else {
10887 DRD->addDecl(OmpPrivParm);
10888 DRD->addDecl(OmpOrigParm);
10889 }
10890}
10891
10892void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10893 Expr *Initializer) {
10894 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10895 DiscardCleanupsInEvaluationContext();
10896 PopExpressionEvaluationContext();
10897
10898 PopDeclContext();
10899 PopFunctionScopeInfo();
10900
10901 if (Initializer != nullptr)
10902 DRD->setInitializer(Initializer);
10903 else
10904 DRD->setInvalidDecl();
10905}
10906
10907Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10908 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10909 for (auto *D : DeclReductions.get()) {
10910 if (IsValid) {
10911 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10912 if (S != nullptr)
10913 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10914 } else
10915 D->setInvalidDecl();
10916 }
10917 return DeclReductions;
10918}
10919
David Majnemer9d168222016-08-05 17:44:54 +000010920OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010921 SourceLocation StartLoc,
10922 SourceLocation LParenLoc,
10923 SourceLocation EndLoc) {
10924 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010925 Stmt *HelperValStmt = nullptr;
10926 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010927
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010928 // OpenMP [teams Constrcut, Restrictions]
10929 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010930 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10931 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010932 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010933
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010934 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10935 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
10936 if (CaptureRegion != OMPD_unknown) {
10937 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10938 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10939 HelperValStmt = buildPreInits(Context, Captures);
10940 }
10941
10942 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
10943 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000010944}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010945
10946OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10947 SourceLocation StartLoc,
10948 SourceLocation LParenLoc,
10949 SourceLocation EndLoc) {
10950 Expr *ValExpr = ThreadLimit;
10951
10952 // OpenMP [teams Constrcut, Restrictions]
10953 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010954 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10955 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010956 return nullptr;
10957
David Majnemer9d168222016-08-05 17:44:54 +000010958 return new (Context)
10959 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010960}
Alexey Bataeva0569352015-12-01 10:17:31 +000010961
10962OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10963 SourceLocation StartLoc,
10964 SourceLocation LParenLoc,
10965 SourceLocation EndLoc) {
10966 Expr *ValExpr = Priority;
10967
10968 // OpenMP [2.9.1, task Constrcut]
10969 // The priority-value is a non-negative numerical scalar expression.
10970 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10971 /*StrictlyPositive=*/false))
10972 return nullptr;
10973
10974 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10975}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010976
10977OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10978 SourceLocation StartLoc,
10979 SourceLocation LParenLoc,
10980 SourceLocation EndLoc) {
10981 Expr *ValExpr = Grainsize;
10982
10983 // OpenMP [2.9.2, taskloop Constrcut]
10984 // The parameter of the grainsize clause must be a positive integer
10985 // expression.
10986 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10987 /*StrictlyPositive=*/true))
10988 return nullptr;
10989
10990 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10991}
Alexey Bataev382967a2015-12-08 12:06:20 +000010992
10993OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10994 SourceLocation StartLoc,
10995 SourceLocation LParenLoc,
10996 SourceLocation EndLoc) {
10997 Expr *ValExpr = NumTasks;
10998
10999 // OpenMP [2.9.2, taskloop Constrcut]
11000 // The parameter of the num_tasks clause must be a positive integer
11001 // expression.
11002 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
11003 /*StrictlyPositive=*/true))
11004 return nullptr;
11005
11006 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
11007}
11008
Alexey Bataev28c75412015-12-15 08:19:24 +000011009OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11010 SourceLocation LParenLoc,
11011 SourceLocation EndLoc) {
11012 // OpenMP [2.13.2, critical construct, Description]
11013 // ... where hint-expression is an integer constant expression that evaluates
11014 // to a valid lock hint.
11015 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
11016 if (HintExpr.isInvalid())
11017 return nullptr;
11018 return new (Context)
11019 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
11020}
11021
Carlo Bertollib4adf552016-01-15 18:50:31 +000011022OMPClause *Sema::ActOnOpenMPDistScheduleClause(
11023 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11024 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
11025 SourceLocation EndLoc) {
11026 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
11027 std::string Values;
11028 Values += "'";
11029 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
11030 Values += "'";
11031 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11032 << Values << getOpenMPClauseName(OMPC_dist_schedule);
11033 return nullptr;
11034 }
11035 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011036 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011037 if (ChunkSize) {
11038 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11039 !ChunkSize->isInstantiationDependent() &&
11040 !ChunkSize->containsUnexpandedParameterPack()) {
11041 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
11042 ExprResult Val =
11043 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11044 if (Val.isInvalid())
11045 return nullptr;
11046
11047 ValExpr = Val.get();
11048
11049 // OpenMP [2.7.1, Restrictions]
11050 // chunk_size must be a loop invariant integer expression with a positive
11051 // value.
11052 llvm::APSInt Result;
11053 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11054 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11055 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11056 << "dist_schedule" << ChunkSize->getSourceRange();
11057 return nullptr;
11058 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011059 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
11060 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000011061 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11062 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11063 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011064 }
11065 }
11066 }
11067
11068 return new (Context)
11069 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000011070 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000011071}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011072
11073OMPClause *Sema::ActOnOpenMPDefaultmapClause(
11074 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11075 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11076 SourceLocation KindLoc, SourceLocation EndLoc) {
11077 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000011078 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011079 std::string Value;
11080 SourceLocation Loc;
11081 Value += "'";
11082 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
11083 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011084 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011085 Loc = MLoc;
11086 } else {
11087 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000011088 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011089 Loc = KindLoc;
11090 }
11091 Value += "'";
11092 Diag(Loc, diag::err_omp_unexpected_clause_value)
11093 << Value << getOpenMPClauseName(OMPC_defaultmap);
11094 return nullptr;
11095 }
11096
11097 return new (Context)
11098 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
11099}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011100
11101bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
11102 DeclContext *CurLexicalContext = getCurLexicalContext();
11103 if (!CurLexicalContext->isFileContext() &&
11104 !CurLexicalContext->isExternCContext() &&
11105 !CurLexicalContext->isExternCXXContext()) {
11106 Diag(Loc, diag::err_omp_region_not_file_context);
11107 return false;
11108 }
11109 if (IsInOpenMPDeclareTargetContext) {
11110 Diag(Loc, diag::err_omp_enclosed_declare_target);
11111 return false;
11112 }
11113
11114 IsInOpenMPDeclareTargetContext = true;
11115 return true;
11116}
11117
11118void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
11119 assert(IsInOpenMPDeclareTargetContext &&
11120 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
11121
11122 IsInOpenMPDeclareTargetContext = false;
11123}
11124
David Majnemer9d168222016-08-05 17:44:54 +000011125void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
11126 CXXScopeSpec &ScopeSpec,
11127 const DeclarationNameInfo &Id,
11128 OMPDeclareTargetDeclAttr::MapTypeTy MT,
11129 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011130 LookupResult Lookup(*this, Id, LookupOrdinaryName);
11131 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
11132
11133 if (Lookup.isAmbiguous())
11134 return;
11135 Lookup.suppressDiagnostics();
11136
11137 if (!Lookup.isSingleResult()) {
11138 if (TypoCorrection Corrected =
11139 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
11140 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
11141 CTK_ErrorRecovery)) {
11142 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
11143 << Id.getName());
11144 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
11145 return;
11146 }
11147
11148 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11149 return;
11150 }
11151
11152 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11153 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11154 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11155 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11156
11157 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11158 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11159 ND->addAttr(A);
11160 if (ASTMutationListener *ML = Context.getASTMutationListener())
11161 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11162 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11163 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11164 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11165 << Id.getName();
11166 }
11167 } else
11168 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11169}
11170
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011171static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11172 Sema &SemaRef, Decl *D) {
11173 if (!D)
11174 return;
11175 Decl *LD = nullptr;
11176 if (isa<TagDecl>(D)) {
11177 LD = cast<TagDecl>(D)->getDefinition();
11178 } else if (isa<VarDecl>(D)) {
11179 LD = cast<VarDecl>(D)->getDefinition();
11180
11181 // If this is an implicit variable that is legal and we do not need to do
11182 // anything.
11183 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011184 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11185 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11186 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011187 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011188 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011189 return;
11190 }
11191
11192 } else if (isa<FunctionDecl>(D)) {
11193 const FunctionDecl *FD = nullptr;
11194 if (cast<FunctionDecl>(D)->hasBody(FD))
11195 LD = const_cast<FunctionDecl *>(FD);
11196
11197 // If the definition is associated with the current declaration in the
11198 // target region (it can be e.g. a lambda) that is legal and we do not need
11199 // to do anything else.
11200 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011201 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11202 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11203 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011204 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011205 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011206 return;
11207 }
11208 }
11209 if (!LD)
11210 LD = D;
11211 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11212 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11213 // Outlined declaration is not declared target.
11214 if (LD->isOutOfLine()) {
11215 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11216 SemaRef.Diag(SL, diag::note_used_here) << SR;
11217 } else {
11218 DeclContext *DC = LD->getDeclContext();
11219 while (DC) {
11220 if (isa<FunctionDecl>(DC) &&
11221 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11222 break;
11223 DC = DC->getParent();
11224 }
11225 if (DC)
11226 return;
11227
11228 // Is not declared in target context.
11229 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11230 SemaRef.Diag(SL, diag::note_used_here) << SR;
11231 }
11232 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011233 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11234 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11235 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011236 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011237 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011238 }
11239}
11240
11241static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11242 Sema &SemaRef, DSAStackTy *Stack,
11243 ValueDecl *VD) {
11244 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11245 return true;
11246 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11247 return false;
11248 return true;
11249}
11250
11251void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11252 if (!D || D->isInvalidDecl())
11253 return;
11254 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11255 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11256 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11257 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11258 if (DSAStack->isThreadPrivate(VD)) {
11259 Diag(SL, diag::err_omp_threadprivate_in_target);
11260 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11261 return;
11262 }
11263 }
11264 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11265 // Problem if any with var declared with incomplete type will be reported
11266 // as normal, so no need to check it here.
11267 if ((E || !VD->getType()->isIncompleteType()) &&
11268 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11269 // Mark decl as declared target to prevent further diagnostic.
11270 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011271 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11272 Context, OMPDeclareTargetDeclAttr::MT_To);
11273 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011274 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011275 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011276 }
11277 return;
11278 }
11279 }
11280 if (!E) {
11281 // Checking declaration inside declare target region.
11282 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11283 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011284 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11285 Context, OMPDeclareTargetDeclAttr::MT_To);
11286 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011287 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011288 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011289 }
11290 return;
11291 }
11292 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11293}
Samuel Antao661c0902016-05-26 17:39:58 +000011294
11295OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11296 SourceLocation StartLoc,
11297 SourceLocation LParenLoc,
11298 SourceLocation EndLoc) {
11299 MappableVarListInfo MVLI(VarList);
11300 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11301 if (MVLI.ProcessedVarList.empty())
11302 return nullptr;
11303
11304 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11305 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11306 MVLI.VarComponents);
11307}
Samuel Antaoec172c62016-05-26 17:49:04 +000011308
11309OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11310 SourceLocation StartLoc,
11311 SourceLocation LParenLoc,
11312 SourceLocation EndLoc) {
11313 MappableVarListInfo MVLI(VarList);
11314 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11315 if (MVLI.ProcessedVarList.empty())
11316 return nullptr;
11317
11318 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11319 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11320 MVLI.VarComponents);
11321}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011322
11323OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11324 SourceLocation StartLoc,
11325 SourceLocation LParenLoc,
11326 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011327 MappableVarListInfo MVLI(VarList);
11328 SmallVector<Expr *, 8> PrivateCopies;
11329 SmallVector<Expr *, 8> Inits;
11330
Carlo Bertolli2404b172016-07-13 15:37:16 +000011331 for (auto &RefExpr : VarList) {
11332 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11333 SourceLocation ELoc;
11334 SourceRange ERange;
11335 Expr *SimpleRefExpr = RefExpr;
11336 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11337 if (Res.second) {
11338 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011339 MVLI.ProcessedVarList.push_back(RefExpr);
11340 PrivateCopies.push_back(nullptr);
11341 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011342 }
11343 ValueDecl *D = Res.first;
11344 if (!D)
11345 continue;
11346
11347 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011348 Type = Type.getNonReferenceType().getUnqualifiedType();
11349
11350 auto *VD = dyn_cast<VarDecl>(D);
11351
11352 // Item should be a pointer or reference to pointer.
11353 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011354 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11355 << 0 << RefExpr->getSourceRange();
11356 continue;
11357 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011358
11359 // Build the private variable and the expression that refers to it.
11360 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11361 D->hasAttrs() ? &D->getAttrs() : nullptr);
11362 if (VDPrivate->isInvalidDecl())
11363 continue;
11364
11365 CurContext->addDecl(VDPrivate);
11366 auto VDPrivateRefExpr = buildDeclRefExpr(
11367 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11368
11369 // Add temporary variable to initialize the private copy of the pointer.
11370 auto *VDInit =
11371 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11372 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11373 RefExpr->getExprLoc());
11374 AddInitializerToDecl(VDPrivate,
11375 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011376 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011377
11378 // If required, build a capture to implement the privatization initialized
11379 // with the current list item value.
11380 DeclRefExpr *Ref = nullptr;
11381 if (!VD)
11382 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11383 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11384 PrivateCopies.push_back(VDPrivateRefExpr);
11385 Inits.push_back(VDInitRefExpr);
11386
11387 // We need to add a data sharing attribute for this variable to make sure it
11388 // is correctly captured. A variable that shows up in a use_device_ptr has
11389 // similar properties of a first private variable.
11390 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11391
11392 // Create a mappable component for the list item. List items in this clause
11393 // only need a component.
11394 MVLI.VarBaseDeclarations.push_back(D);
11395 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11396 MVLI.VarComponents.back().push_back(
11397 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011398 }
11399
Samuel Antaocc10b852016-07-28 14:23:26 +000011400 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011401 return nullptr;
11402
Samuel Antaocc10b852016-07-28 14:23:26 +000011403 return OMPUseDevicePtrClause::Create(
11404 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11405 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011406}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011407
11408OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11409 SourceLocation StartLoc,
11410 SourceLocation LParenLoc,
11411 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011412 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011413 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011414 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011415 SourceLocation ELoc;
11416 SourceRange ERange;
11417 Expr *SimpleRefExpr = RefExpr;
11418 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11419 if (Res.second) {
11420 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011421 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011422 }
11423 ValueDecl *D = Res.first;
11424 if (!D)
11425 continue;
11426
11427 QualType Type = D->getType();
11428 // item should be a pointer or array or reference to pointer or array
11429 if (!Type.getNonReferenceType()->isPointerType() &&
11430 !Type.getNonReferenceType()->isArrayType()) {
11431 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11432 << 0 << RefExpr->getSourceRange();
11433 continue;
11434 }
Samuel Antao6890b092016-07-28 14:25:09 +000011435
11436 // Check if the declaration in the clause does not show up in any data
11437 // sharing attribute.
11438 auto DVar = DSAStack->getTopDSA(D, false);
11439 if (isOpenMPPrivate(DVar.CKind)) {
11440 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11441 << getOpenMPClauseName(DVar.CKind)
11442 << getOpenMPClauseName(OMPC_is_device_ptr)
11443 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11444 ReportOriginalDSA(*this, DSAStack, D, DVar);
11445 continue;
11446 }
11447
11448 Expr *ConflictExpr;
11449 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011450 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011451 [&ConflictExpr](
11452 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11453 OpenMPClauseKind) -> bool {
11454 ConflictExpr = R.front().getAssociatedExpression();
11455 return true;
11456 })) {
11457 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11458 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11459 << ConflictExpr->getSourceRange();
11460 continue;
11461 }
11462
11463 // Store the components in the stack so that they can be used to check
11464 // against other clauses later on.
11465 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11466 DSAStack->addMappableExpressionComponents(
11467 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11468
11469 // Record the expression we've just processed.
11470 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11471
11472 // Create a mappable component for the list item. List items in this clause
11473 // only need a component. We use a null declaration to signal fields in
11474 // 'this'.
11475 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11476 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11477 "Unexpected device pointer expression!");
11478 MVLI.VarBaseDeclarations.push_back(
11479 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11480 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11481 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011482 }
11483
Samuel Antao6890b092016-07-28 14:25:09 +000011484 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011485 return nullptr;
11486
Samuel Antao6890b092016-07-28 14:25:09 +000011487 return OMPIsDevicePtrClause::Create(
11488 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11489 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011490}