blob: a4622e1dfb3b7098a441ffe02cd87b6439a5f0c2 [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:
Kelvin Libf594a52016-12-17 05:48:59 +00001597 case OMPD_teams:
1598 case OMPD_target_teams: {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001600 QualType KmpInt32PtrTy =
1601 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001602 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001603 std::make_pair(".global_tid.", KmpInt32PtrTy),
1604 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1605 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00001606 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001607 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1608 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00001609 break;
1610 }
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();
1621 Sema::CapturedParamNameType ParamsParallel[] = {
1622 std::make_pair(".global_tid.", KmpInt32PtrTy),
1623 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1624 std::make_pair(StringRef(), QualType()) // __context with shared vars
1625 };
1626 // Start a captured region for 'parallel'.
1627 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1628 ParamsParallel);
1629 break;
1630 }
Kelvin Li70a12c52016-07-13 21:51:49 +00001631 case OMPD_simd:
1632 case OMPD_for:
1633 case OMPD_for_simd:
1634 case OMPD_sections:
1635 case OMPD_section:
1636 case OMPD_single:
1637 case OMPD_master:
1638 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00001639 case OMPD_taskgroup:
1640 case OMPD_distribute:
Kelvin Li70a12c52016-07-13 21:51:49 +00001641 case OMPD_ordered:
1642 case OMPD_atomic:
1643 case OMPD_target_data:
1644 case OMPD_target:
Kelvin Li70a12c52016-07-13 21:51:49 +00001645 case OMPD_target_parallel_for:
Kelvin Li986330c2016-07-20 22:57:10 +00001646 case OMPD_target_parallel_for_simd:
1647 case OMPD_target_simd: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00001648 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001649 std::make_pair(StringRef(), QualType()) // __context with shared vars
1650 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00001651 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1652 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001653 break;
1654 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001655 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001656 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00001657 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1658 FunctionProtoType::ExtProtoInfo EPI;
1659 EPI.Variadic = true;
1660 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001661 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001662 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00001663 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1664 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
1665 std::make_pair(".copy_fn.",
1666 Context.getPointerType(CopyFnType).withConst()),
1667 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001668 std::make_pair(StringRef(), QualType()) // __context with shared vars
1669 };
1670 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1671 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001672 // Mark this captured region as inlined, because we don't use outlined
1673 // function directly.
1674 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1675 AlwaysInlineAttr::CreateImplicit(
1676 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001677 break;
1678 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00001679 case OMPD_taskloop:
1680 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00001681 QualType KmpInt32Ty =
1682 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1683 QualType KmpUInt64Ty =
1684 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
1685 QualType KmpInt64Ty =
1686 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
1687 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
1688 FunctionProtoType::ExtProtoInfo EPI;
1689 EPI.Variadic = true;
1690 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00001691 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00001692 std::make_pair(".global_tid.", KmpInt32Ty),
1693 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
1694 std::make_pair(".privates.",
1695 Context.VoidPtrTy.withConst().withRestrict()),
1696 std::make_pair(
1697 ".copy_fn.",
1698 Context.getPointerType(CopyFnType).withConst().withRestrict()),
1699 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
1700 std::make_pair(".lb.", KmpUInt64Ty),
1701 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
1702 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataev49f6e782015-12-01 04:18:41 +00001703 std::make_pair(StringRef(), QualType()) // __context with shared vars
1704 };
1705 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1706 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00001707 // Mark this captured region as inlined, because we don't use outlined
1708 // function directly.
1709 getCurCapturedRegion()->TheCapturedDecl->addAttr(
1710 AlwaysInlineAttr::CreateImplicit(
1711 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00001712 break;
1713 }
Kelvin Li4a39add2016-07-05 05:00:15 +00001714 case OMPD_distribute_parallel_for_simd:
Kelvin Li787f3fc2016-07-06 04:45:38 +00001715 case OMPD_distribute_simd:
Kelvin Li02532872016-08-05 14:37:37 +00001716 case OMPD_distribute_parallel_for:
Kelvin Li4e325f72016-10-25 12:50:55 +00001717 case OMPD_teams_distribute:
Kelvin Li579e41c2016-11-30 23:51:03 +00001718 case OMPD_teams_distribute_simd:
Kelvin Li7ade93f2016-12-09 03:24:30 +00001719 case OMPD_teams_distribute_parallel_for_simd:
Kelvin Li83c451e2016-12-25 04:52:54 +00001720 case OMPD_teams_distribute_parallel_for:
Kelvin Li80e8f562016-12-29 22:16:30 +00001721 case OMPD_target_teams_distribute:
Kelvin Li1851df52017-01-03 05:23:48 +00001722 case OMPD_target_teams_distribute_parallel_for:
Kelvin Lida681182017-01-10 18:08:18 +00001723 case OMPD_target_teams_distribute_parallel_for_simd:
1724 case OMPD_target_teams_distribute_simd: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00001725 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
1726 QualType KmpInt32PtrTy =
1727 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
1728 Sema::CapturedParamNameType Params[] = {
1729 std::make_pair(".global_tid.", KmpInt32PtrTy),
1730 std::make_pair(".bound_tid.", KmpInt32PtrTy),
1731 std::make_pair(".previous.lb.", Context.getSizeType()),
1732 std::make_pair(".previous.ub.", Context.getSizeType()),
1733 std::make_pair(StringRef(), QualType()) // __context with shared vars
1734 };
1735 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
1736 Params);
1737 break;
1738 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001739 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00001740 case OMPD_taskyield:
1741 case OMPD_barrier:
1742 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001743 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00001744 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00001745 case OMPD_flush:
Samuel Antaodf67fc42016-01-19 19:15:56 +00001746 case OMPD_target_enter_data:
Samuel Antao72590762016-01-19 20:04:50 +00001747 case OMPD_target_exit_data:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001748 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00001749 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001750 case OMPD_declare_target:
1751 case OMPD_end_declare_target:
Samuel Antao686c70c2016-05-26 17:30:50 +00001752 case OMPD_target_update:
Alexey Bataev9959db52014-05-06 10:08:46 +00001753 llvm_unreachable("OpenMP Directive is not allowed");
1754 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00001755 llvm_unreachable("Unknown OpenMP directive");
1756 }
1757}
1758
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001759int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
1760 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1761 getOpenMPCaptureRegions(CaptureRegions, DKind);
1762 return CaptureRegions.size();
1763}
1764
Alexey Bataev3392d762016-02-16 11:18:12 +00001765static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00001766 Expr *CaptureExpr, bool WithInit,
1767 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001768 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00001769 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00001770 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00001771 QualType Ty = Init->getType();
1772 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
1773 if (S.getLangOpts().CPlusPlus)
1774 Ty = C.getLValueReferenceType(Ty);
1775 else {
1776 Ty = C.getPointerType(Ty);
1777 ExprResult Res =
1778 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
1779 if (!Res.isUsable())
1780 return nullptr;
1781 Init = Res.get();
1782 }
Alexey Bataev61205072016-03-02 04:57:40 +00001783 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00001784 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00001785 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
1786 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00001787 if (!WithInit)
1788 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00001789 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00001790 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001791 return CED;
1792}
1793
Alexey Bataev61205072016-03-02 04:57:40 +00001794static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
1795 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00001796 OMPCapturedExprDecl *CD;
1797 if (auto *VD = S.IsOpenMPCapturedDecl(D))
1798 CD = cast<OMPCapturedExprDecl>(VD);
1799 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00001800 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
1801 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001802 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00001803 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00001804}
1805
Alexey Bataev5a3af132016-03-29 08:58:54 +00001806static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
1807 if (!Ref) {
1808 auto *CD =
1809 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."),
1810 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true);
1811 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
1812 CaptureExpr->getExprLoc());
1813 }
1814 ExprResult Res = Ref;
1815 if (!S.getLangOpts().CPlusPlus &&
1816 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
1817 Ref->getType()->isPointerType())
1818 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
1819 if (!Res.isUsable())
1820 return ExprError();
1821 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00001822}
1823
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001824namespace {
1825// OpenMP directives parsed in this section are represented as a
1826// CapturedStatement with an associated statement. If a syntax error
1827// is detected during the parsing of the associated statement, the
1828// compiler must abort processing and close the CapturedStatement.
1829//
1830// Combined directives such as 'target parallel' have more than one
1831// nested CapturedStatements. This RAII ensures that we unwind out
1832// of all the nested CapturedStatements when an error is found.
1833class CaptureRegionUnwinderRAII {
1834private:
1835 Sema &S;
1836 bool &ErrorFound;
1837 OpenMPDirectiveKind DKind;
1838
1839public:
1840 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
1841 OpenMPDirectiveKind DKind)
1842 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
1843 ~CaptureRegionUnwinderRAII() {
1844 if (ErrorFound) {
1845 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
1846 while (--ThisCaptureLevel >= 0)
1847 S.ActOnCapturedRegionError();
1848 }
1849 }
1850};
1851} // namespace
1852
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001853StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
1854 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001855 bool ErrorFound = false;
1856 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
1857 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001858 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001859 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001860 return StmtError();
1861 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001862
1863 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00001864 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00001865 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001866 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00001867 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001868 for (auto *Clause : Clauses) {
Alexey Bataev16dc7b62015-05-20 03:46:04 +00001869 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001870 Clause->getClauseKind() == OMPC_copyprivate ||
1871 (getLangOpts().OpenMPUseTLS &&
1872 getASTContext().getTargetInfo().isTLSSupported() &&
1873 Clause->getClauseKind() == OMPC_copyin)) {
1874 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00001875 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001876 for (auto *VarRef : Clause->children()) {
1877 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00001878 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001879 }
1880 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001881 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00001882 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001883 if (auto *C = OMPClauseWithPreInit::get(Clause))
1884 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00001885 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
1886 if (auto *E = C->getPostUpdateExpr())
1887 MarkDeclarationsReferencedInExpr(E);
1888 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001889 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001890 if (Clause->getClauseKind() == OMPC_schedule)
1891 SC = cast<OMPScheduleClause>(Clause);
1892 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00001893 OC = cast<OMPOrderedClause>(Clause);
1894 else if (Clause->getClauseKind() == OMPC_linear)
1895 LCs.push_back(cast<OMPLinearClause>(Clause));
1896 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001897 // OpenMP, 2.7.1 Loop Construct, Restrictions
1898 // The nonmonotonic modifier cannot be specified if an ordered clause is
1899 // specified.
1900 if (SC &&
1901 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
1902 SC->getSecondScheduleModifier() ==
1903 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
1904 OC) {
1905 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
1906 ? SC->getFirstScheduleModifierLoc()
1907 : SC->getSecondScheduleModifierLoc(),
1908 diag::err_omp_schedule_nonmonotonic_ordered)
1909 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1910 ErrorFound = true;
1911 }
Alexey Bataev993d2802015-12-28 06:23:08 +00001912 if (!LCs.empty() && OC && OC->getNumForLoops()) {
1913 for (auto *C : LCs) {
1914 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
1915 << SourceRange(OC->getLocStart(), OC->getLocEnd());
1916 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001917 ErrorFound = true;
1918 }
Alexey Bataev113438c2015-12-30 12:06:23 +00001919 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
1920 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
1921 OC->getNumForLoops()) {
1922 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
1923 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
1924 ErrorFound = true;
1925 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00001926 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00001927 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001928 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001929 StmtResult SR = S;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001930 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
1931 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
1932 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
1933 // Mark all variables in private list clauses as used in inner region.
1934 // Required for proper codegen of combined directives.
1935 // TODO: add processing for other clauses.
1936 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
1937 for (auto *C : PICs) {
1938 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
1939 // Find the particular capture region for the clause if the
1940 // directive is a combined one with multiple capture regions.
1941 // If the directive is not a combined one, the capture region
1942 // associated with the clause is OMPD_unknown and is generated
1943 // only once.
1944 if (CaptureRegion == ThisCaptureRegion ||
1945 CaptureRegion == OMPD_unknown) {
1946 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
1947 for (auto *D : DS->decls())
1948 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
1949 }
1950 }
1951 }
1952 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001953 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00001954 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001955 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00001956}
1957
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001958static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
1959 OpenMPDirectiveKind CurrentRegion,
1960 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00001961 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001962 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001963 if (Stack->getCurScope()) {
1964 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001965 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00001966 bool NestingProhibited = false;
1967 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00001968 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001969 enum {
1970 NoRecommend,
1971 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00001972 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00001973 ShouldBeInTargetRegion,
1974 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00001975 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00001976 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00001977 // OpenMP [2.16, Nesting of Regions]
1978 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00001979 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00001980 // An ordered construct with the simd clause is the only OpenMP
1981 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00001982 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00001983 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
1984 // message.
1985 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
1986 ? diag::err_omp_prohibited_region_simd
1987 : diag::warn_omp_nesting_simd);
1988 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00001989 }
Alexey Bataev0162e452014-07-22 10:10:35 +00001990 if (ParentRegion == OMPD_atomic) {
1991 // OpenMP [2.16, Nesting of Regions]
1992 // OpenMP constructs may not be nested inside an atomic region.
1993 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
1994 return true;
1995 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00001996 if (CurrentRegion == OMPD_section) {
1997 // OpenMP [2.7.2, sections Construct, Restrictions]
1998 // Orphaned section directives are prohibited. That is, the section
1999 // directives must appear within the sections construct and must not be
2000 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002001 if (ParentRegion != OMPD_sections &&
2002 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002003 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2004 << (ParentRegion != OMPD_unknown)
2005 << getOpenMPDirectiveName(ParentRegion);
2006 return true;
2007 }
2008 return false;
2009 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002010 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002011 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002012 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002013 if (ParentRegion == OMPD_unknown &&
2014 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002015 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002016 if (CurrentRegion == OMPD_cancellation_point ||
2017 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002018 // OpenMP [2.16, Nesting of Regions]
2019 // A cancellation point construct for which construct-type-clause is
2020 // taskgroup must be nested inside a task construct. A cancellation
2021 // point construct for which construct-type-clause is not taskgroup must
2022 // be closely nested inside an OpenMP construct that matches the type
2023 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002024 // A cancel construct for which construct-type-clause is taskgroup must be
2025 // nested inside a task construct. A cancel construct for which
2026 // construct-type-clause is not taskgroup must be closely nested inside an
2027 // OpenMP construct that matches the type specified in
2028 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002029 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002030 !((CancelRegion == OMPD_parallel &&
2031 (ParentRegion == OMPD_parallel ||
2032 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002033 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002034 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
2035 ParentRegion == OMPD_target_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002036 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2037 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002038 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2039 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002040 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002041 // OpenMP [2.16, Nesting of Regions]
2042 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002043 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002044 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002045 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002046 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2047 // OpenMP [2.16, Nesting of Regions]
2048 // A critical region may not be nested (closely or otherwise) inside a
2049 // critical region with the same name. Note that this restriction is not
2050 // sufficient to prevent deadlock.
2051 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002052 bool DeadLock = Stack->hasDirective(
2053 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2054 const DeclarationNameInfo &DNI,
2055 SourceLocation Loc) -> bool {
2056 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2057 PreviousCriticalLoc = Loc;
2058 return true;
2059 } else
2060 return false;
2061 },
2062 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002063 if (DeadLock) {
2064 SemaRef.Diag(StartLoc,
2065 diag::err_omp_prohibited_region_critical_same_name)
2066 << CurrentName.getName();
2067 if (PreviousCriticalLoc.isValid())
2068 SemaRef.Diag(PreviousCriticalLoc,
2069 diag::note_omp_previous_critical_region);
2070 return true;
2071 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002072 } else if (CurrentRegion == OMPD_barrier) {
2073 // OpenMP [2.16, Nesting of Regions]
2074 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002075 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002076 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2077 isOpenMPTaskingDirective(ParentRegion) ||
2078 ParentRegion == OMPD_master ||
2079 ParentRegion == OMPD_critical ||
2080 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002081 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002082 !isOpenMPParallelDirective(CurrentRegion) &&
2083 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002084 // OpenMP [2.16, Nesting of Regions]
2085 // A worksharing region may not be closely nested inside a worksharing,
2086 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002087 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2088 isOpenMPTaskingDirective(ParentRegion) ||
2089 ParentRegion == OMPD_master ||
2090 ParentRegion == OMPD_critical ||
2091 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002092 Recommend = ShouldBeInParallelRegion;
2093 } else if (CurrentRegion == OMPD_ordered) {
2094 // OpenMP [2.16, Nesting of Regions]
2095 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002096 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002097 // An ordered region must be closely nested inside a loop region (or
2098 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002099 // OpenMP [2.8.1,simd Construct, Restrictions]
2100 // An ordered construct with the simd clause is the only OpenMP construct
2101 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002102 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002103 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002104 !(isOpenMPSimdDirective(ParentRegion) ||
2105 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002106 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002107 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002108 // OpenMP [2.16, Nesting of Regions]
2109 // If specified, a teams construct must be contained within a target
2110 // construct.
2111 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002112 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002113 Recommend = ShouldBeInTargetRegion;
2114 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
2115 }
Kelvin Libf594a52016-12-17 05:48:59 +00002116 if (!NestingProhibited &&
2117 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2118 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2119 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002120 // OpenMP [2.16, Nesting of Regions]
2121 // distribute, parallel, parallel sections, parallel workshare, and the
2122 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2123 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002124 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2125 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002126 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002127 }
David Majnemer9d168222016-08-05 17:44:54 +00002128 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002129 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002130 // OpenMP 4.5 [2.17 Nesting of Regions]
2131 // The region associated with the distribute construct must be strictly
2132 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002133 NestingProhibited =
2134 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002135 Recommend = ShouldBeInTeamsRegion;
2136 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002137 if (!NestingProhibited &&
2138 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2139 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2140 // OpenMP 4.5 [2.17 Nesting of Regions]
2141 // If a target, target update, target data, target enter data, or
2142 // target exit data construct is encountered during execution of a
2143 // target region, the behavior is unspecified.
2144 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002145 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2146 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002147 if (isOpenMPTargetExecutionDirective(K)) {
2148 OffendingRegion = K;
2149 return true;
2150 } else
2151 return false;
2152 },
2153 false /* don't skip top directive */);
2154 CloseNesting = false;
2155 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002156 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002157 if (OrphanSeen) {
2158 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2159 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2160 } else {
2161 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2162 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2163 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2164 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002165 return true;
2166 }
2167 }
2168 return false;
2169}
2170
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002171static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2172 ArrayRef<OMPClause *> Clauses,
2173 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2174 bool ErrorFound = false;
2175 unsigned NamedModifiersNumber = 0;
2176 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2177 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002178 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002179 for (const auto *C : Clauses) {
2180 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2181 // At most one if clause without a directive-name-modifier can appear on
2182 // the directive.
2183 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2184 if (FoundNameModifiers[CurNM]) {
2185 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2186 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2187 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2188 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002189 } else if (CurNM != OMPD_unknown) {
2190 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002191 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002192 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002193 FoundNameModifiers[CurNM] = IC;
2194 if (CurNM == OMPD_unknown)
2195 continue;
2196 // Check if the specified name modifier is allowed for the current
2197 // directive.
2198 // At most one if clause with the particular directive-name-modifier can
2199 // appear on the directive.
2200 bool MatchFound = false;
2201 for (auto NM : AllowedNameModifiers) {
2202 if (CurNM == NM) {
2203 MatchFound = true;
2204 break;
2205 }
2206 }
2207 if (!MatchFound) {
2208 S.Diag(IC->getNameModifierLoc(),
2209 diag::err_omp_wrong_if_directive_name_modifier)
2210 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2211 ErrorFound = true;
2212 }
2213 }
2214 }
2215 // If any if clause on the directive includes a directive-name-modifier then
2216 // all if clauses on the directive must include a directive-name-modifier.
2217 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2218 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2219 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2220 diag::err_omp_no_more_if_clause);
2221 } else {
2222 std::string Values;
2223 std::string Sep(", ");
2224 unsigned AllowedCnt = 0;
2225 unsigned TotalAllowedNum =
2226 AllowedNameModifiers.size() - NamedModifiersNumber;
2227 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2228 ++Cnt) {
2229 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2230 if (!FoundNameModifiers[NM]) {
2231 Values += "'";
2232 Values += getOpenMPDirectiveName(NM);
2233 Values += "'";
2234 if (AllowedCnt + 2 == TotalAllowedNum)
2235 Values += " or ";
2236 else if (AllowedCnt + 1 != TotalAllowedNum)
2237 Values += Sep;
2238 ++AllowedCnt;
2239 }
2240 }
2241 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2242 diag::err_omp_unnamed_if_clause)
2243 << (TotalAllowedNum > 1) << Values;
2244 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002245 for (auto Loc : NameModifierLoc) {
2246 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2247 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002248 ErrorFound = true;
2249 }
2250 return ErrorFound;
2251}
2252
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002253StmtResult Sema::ActOnOpenMPExecutableDirective(
2254 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2255 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2256 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002257 StmtResult Res = StmtError();
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002258 if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
2259 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002260 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002261
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002262 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002263 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002264 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002265 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev68446b72014-07-18 07:47:19 +00002266 if (AStmt) {
2267 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2268
2269 // Check default data sharing attributes for referenced variables.
2270 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
2271 DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
2272 if (DSAChecker.isErrorFound())
2273 return StmtError();
2274 // Generate list of implicitly defined firstprivate variables.
2275 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002276
2277 if (!DSAChecker.getImplicitFirstprivate().empty()) {
2278 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
2279 DSAChecker.getImplicitFirstprivate(), SourceLocation(),
2280 SourceLocation(), SourceLocation())) {
2281 ClausesWithImplicit.push_back(Implicit);
2282 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
2283 DSAChecker.getImplicitFirstprivate().size();
2284 } else
2285 ErrorFound = true;
2286 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002287 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002288
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002289 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002290 switch (Kind) {
2291 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00002292 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
2293 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002294 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002295 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002296 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002297 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2298 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00002299 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002300 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00002301 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
2302 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002303 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00002304 case OMPD_for_simd:
2305 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2306 EndLoc, VarsWithInheritedDSA);
2307 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00002308 case OMPD_sections:
2309 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
2310 EndLoc);
2311 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002312 case OMPD_section:
2313 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00002314 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002315 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
2316 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00002317 case OMPD_single:
2318 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
2319 EndLoc);
2320 break;
Alexander Musman80c22892014-07-17 08:54:58 +00002321 case OMPD_master:
2322 assert(ClausesWithImplicit.empty() &&
2323 "No clauses are allowed for 'omp master' directive");
2324 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
2325 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002326 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00002327 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
2328 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002329 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002330 case OMPD_parallel_for:
2331 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
2332 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002333 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00002334 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00002335 case OMPD_parallel_for_simd:
2336 Res = ActOnOpenMPParallelForSimdDirective(
2337 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002338 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00002339 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002340 case OMPD_parallel_sections:
2341 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
2342 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002343 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002344 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002345 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002346 Res =
2347 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002348 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002349 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00002350 case OMPD_taskyield:
2351 assert(ClausesWithImplicit.empty() &&
2352 "No clauses are allowed for 'omp taskyield' directive");
2353 assert(AStmt == nullptr &&
2354 "No associated statement allowed for 'omp taskyield' directive");
2355 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
2356 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002357 case OMPD_barrier:
2358 assert(ClausesWithImplicit.empty() &&
2359 "No clauses are allowed for 'omp barrier' directive");
2360 assert(AStmt == nullptr &&
2361 "No associated statement allowed for 'omp barrier' directive");
2362 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
2363 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00002364 case OMPD_taskwait:
2365 assert(ClausesWithImplicit.empty() &&
2366 "No clauses are allowed for 'omp taskwait' directive");
2367 assert(AStmt == nullptr &&
2368 "No associated statement allowed for 'omp taskwait' directive");
2369 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
2370 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002371 case OMPD_taskgroup:
2372 assert(ClausesWithImplicit.empty() &&
2373 "No clauses are allowed for 'omp taskgroup' directive");
2374 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
2375 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00002376 case OMPD_flush:
2377 assert(AStmt == nullptr &&
2378 "No associated statement allowed for 'omp flush' directive");
2379 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
2380 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002381 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00002382 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
2383 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002384 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00002385 case OMPD_atomic:
2386 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
2387 EndLoc);
2388 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002389 case OMPD_teams:
2390 Res =
2391 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
2392 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002393 case OMPD_target:
2394 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
2395 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002396 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00002397 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002398 case OMPD_target_parallel:
2399 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
2400 StartLoc, EndLoc);
2401 AllowedNameModifiers.push_back(OMPD_target);
2402 AllowedNameModifiers.push_back(OMPD_parallel);
2403 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002404 case OMPD_target_parallel_for:
2405 Res = ActOnOpenMPTargetParallelForDirective(
2406 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2407 AllowedNameModifiers.push_back(OMPD_target);
2408 AllowedNameModifiers.push_back(OMPD_parallel);
2409 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002410 case OMPD_cancellation_point:
2411 assert(ClausesWithImplicit.empty() &&
2412 "No clauses are allowed for 'omp cancellation point' directive");
2413 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
2414 "cancellation point' directive");
2415 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
2416 break;
Alexey Bataev80909872015-07-02 11:25:17 +00002417 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00002418 assert(AStmt == nullptr &&
2419 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00002420 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
2421 CancelRegion);
2422 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00002423 break;
Michael Wong65f367f2015-07-21 13:44:28 +00002424 case OMPD_target_data:
2425 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
2426 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002427 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00002428 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00002429 case OMPD_target_enter_data:
2430 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
2431 EndLoc);
2432 AllowedNameModifiers.push_back(OMPD_target_enter_data);
2433 break;
Samuel Antao72590762016-01-19 20:04:50 +00002434 case OMPD_target_exit_data:
2435 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
2436 EndLoc);
2437 AllowedNameModifiers.push_back(OMPD_target_exit_data);
2438 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00002439 case OMPD_taskloop:
2440 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
2441 EndLoc, VarsWithInheritedDSA);
2442 AllowedNameModifiers.push_back(OMPD_taskloop);
2443 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00002444 case OMPD_taskloop_simd:
2445 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2446 EndLoc, VarsWithInheritedDSA);
2447 AllowedNameModifiers.push_back(OMPD_taskloop);
2448 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002449 case OMPD_distribute:
2450 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
2451 EndLoc, VarsWithInheritedDSA);
2452 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00002453 case OMPD_target_update:
2454 assert(!AStmt && "Statement is not allowed for target update");
2455 Res =
2456 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc);
2457 AllowedNameModifiers.push_back(OMPD_target_update);
2458 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00002459 case OMPD_distribute_parallel_for:
2460 Res = ActOnOpenMPDistributeParallelForDirective(
2461 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2462 AllowedNameModifiers.push_back(OMPD_parallel);
2463 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00002464 case OMPD_distribute_parallel_for_simd:
2465 Res = ActOnOpenMPDistributeParallelForSimdDirective(
2466 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2467 AllowedNameModifiers.push_back(OMPD_parallel);
2468 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00002469 case OMPD_distribute_simd:
2470 Res = ActOnOpenMPDistributeSimdDirective(
2471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2472 break;
Kelvin Lia579b912016-07-14 02:54:56 +00002473 case OMPD_target_parallel_for_simd:
2474 Res = ActOnOpenMPTargetParallelForSimdDirective(
2475 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2476 AllowedNameModifiers.push_back(OMPD_target);
2477 AllowedNameModifiers.push_back(OMPD_parallel);
2478 break;
Kelvin Li986330c2016-07-20 22:57:10 +00002479 case OMPD_target_simd:
2480 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
2481 EndLoc, VarsWithInheritedDSA);
2482 AllowedNameModifiers.push_back(OMPD_target);
2483 break;
Kelvin Li02532872016-08-05 14:37:37 +00002484 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00002485 Res = ActOnOpenMPTeamsDistributeDirective(
2486 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00002487 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00002488 case OMPD_teams_distribute_simd:
2489 Res = ActOnOpenMPTeamsDistributeSimdDirective(
2490 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2491 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00002492 case OMPD_teams_distribute_parallel_for_simd:
2493 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
2494 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2495 AllowedNameModifiers.push_back(OMPD_parallel);
2496 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00002497 case OMPD_teams_distribute_parallel_for:
2498 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
2499 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2500 AllowedNameModifiers.push_back(OMPD_parallel);
2501 break;
Kelvin Libf594a52016-12-17 05:48:59 +00002502 case OMPD_target_teams:
2503 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
2504 EndLoc);
2505 AllowedNameModifiers.push_back(OMPD_target);
2506 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00002507 case OMPD_target_teams_distribute:
2508 Res = ActOnOpenMPTargetTeamsDistributeDirective(
2509 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2510 AllowedNameModifiers.push_back(OMPD_target);
2511 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00002512 case OMPD_target_teams_distribute_parallel_for:
2513 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
2514 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2515 AllowedNameModifiers.push_back(OMPD_target);
2516 AllowedNameModifiers.push_back(OMPD_parallel);
2517 break;
Kelvin Li1851df52017-01-03 05:23:48 +00002518 case OMPD_target_teams_distribute_parallel_for_simd:
2519 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
2520 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2521 AllowedNameModifiers.push_back(OMPD_target);
2522 AllowedNameModifiers.push_back(OMPD_parallel);
2523 break;
Kelvin Lida681182017-01-10 18:08:18 +00002524 case OMPD_target_teams_distribute_simd:
2525 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
2526 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
2527 AllowedNameModifiers.push_back(OMPD_target);
2528 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002529 case OMPD_declare_target:
2530 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002531 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002532 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002533 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002534 llvm_unreachable("OpenMP Directive is not allowed");
2535 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002536 llvm_unreachable("Unknown OpenMP directive");
2537 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002538
Alexey Bataev4acb8592014-07-07 13:01:15 +00002539 for (auto P : VarsWithInheritedDSA) {
2540 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
2541 << P.first << P.second->getSourceRange();
2542 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002543 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
2544
2545 if (!AllowedNameModifiers.empty())
2546 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
2547 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00002548
Alexey Bataeved09d242014-05-28 05:53:51 +00002549 if (ErrorFound)
2550 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002551 return Res;
2552}
2553
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002554Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
2555 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00002556 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00002557 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
2558 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00002559 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00002560 assert(Linears.size() == LinModifiers.size());
2561 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00002562 if (!DG || DG.get().isNull())
2563 return DeclGroupPtrTy();
2564
2565 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00002566 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002567 return DG;
2568 }
2569 auto *ADecl = DG.get().getSingleDecl();
2570 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
2571 ADecl = FTD->getTemplatedDecl();
2572
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002573 auto *FD = dyn_cast<FunctionDecl>(ADecl);
2574 if (!FD) {
2575 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002576 return DeclGroupPtrTy();
2577 }
2578
Alexey Bataev2af33e32016-04-07 12:45:37 +00002579 // OpenMP [2.8.2, declare simd construct, Description]
2580 // The parameter of the simdlen clause must be a constant positive integer
2581 // expression.
2582 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002583 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00002584 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002585 // OpenMP [2.8.2, declare simd construct, Description]
2586 // The special this pointer can be used as if was one of the arguments to the
2587 // function in any of the linear, aligned, or uniform clauses.
2588 // The uniform clause declares one or more arguments to have an invariant
2589 // value for all concurrent invocations of the function in the execution of a
2590 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00002591 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
2592 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002593 for (auto *E : Uniforms) {
2594 E = E->IgnoreParenImpCasts();
2595 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2596 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
2597 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2598 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00002599 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
2600 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002601 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002602 }
2603 if (isa<CXXThisExpr>(E)) {
2604 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002605 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00002606 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002607 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2608 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00002609 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00002610 // OpenMP [2.8.2, declare simd construct, Description]
2611 // The aligned clause declares that the object to which each list item points
2612 // is aligned to the number of bytes expressed in the optional parameter of
2613 // the aligned clause.
2614 // The special this pointer can be used as if was one of the arguments to the
2615 // function in any of the linear, aligned, or uniform clauses.
2616 // The type of list items appearing in the aligned clause must be array,
2617 // pointer, reference to array, or reference to pointer.
2618 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
2619 Expr *AlignedThis = nullptr;
2620 for (auto *E : Aligneds) {
2621 E = E->IgnoreParenImpCasts();
2622 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2623 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2624 auto *CanonPVD = PVD->getCanonicalDecl();
2625 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2626 FD->getParamDecl(PVD->getFunctionScopeIndex())
2627 ->getCanonicalDecl() == CanonPVD) {
2628 // OpenMP [2.8.1, simd construct, Restrictions]
2629 // A list-item cannot appear in more than one aligned clause.
2630 if (AlignedArgs.count(CanonPVD) > 0) {
2631 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2632 << 1 << E->getSourceRange();
2633 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
2634 diag::note_omp_explicit_dsa)
2635 << getOpenMPClauseName(OMPC_aligned);
2636 continue;
2637 }
2638 AlignedArgs[CanonPVD] = E;
2639 QualType QTy = PVD->getType()
2640 .getNonReferenceType()
2641 .getUnqualifiedType()
2642 .getCanonicalType();
2643 const Type *Ty = QTy.getTypePtrOrNull();
2644 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
2645 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
2646 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
2647 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
2648 }
2649 continue;
2650 }
2651 }
2652 if (isa<CXXThisExpr>(E)) {
2653 if (AlignedThis) {
2654 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
2655 << 2 << E->getSourceRange();
2656 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
2657 << getOpenMPClauseName(OMPC_aligned);
2658 }
2659 AlignedThis = E;
2660 continue;
2661 }
2662 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2663 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2664 }
2665 // The optional parameter of the aligned clause, alignment, must be a constant
2666 // positive integer expression. If no optional parameter is specified,
2667 // implementation-defined default alignments for SIMD instructions on the
2668 // target platforms are assumed.
2669 SmallVector<Expr *, 4> NewAligns;
2670 for (auto *E : Alignments) {
2671 ExprResult Align;
2672 if (E)
2673 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
2674 NewAligns.push_back(Align.get());
2675 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00002676 // OpenMP [2.8.2, declare simd construct, Description]
2677 // The linear clause declares one or more list items to be private to a SIMD
2678 // lane and to have a linear relationship with respect to the iteration space
2679 // of a loop.
2680 // The special this pointer can be used as if was one of the arguments to the
2681 // function in any of the linear, aligned, or uniform clauses.
2682 // When a linear-step expression is specified in a linear clause it must be
2683 // either a constant integer expression or an integer-typed parameter that is
2684 // specified in a uniform clause on the directive.
2685 llvm::DenseMap<Decl *, Expr *> LinearArgs;
2686 const bool IsUniformedThis = UniformedLinearThis != nullptr;
2687 auto MI = LinModifiers.begin();
2688 for (auto *E : Linears) {
2689 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
2690 ++MI;
2691 E = E->IgnoreParenImpCasts();
2692 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
2693 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2694 auto *CanonPVD = PVD->getCanonicalDecl();
2695 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
2696 FD->getParamDecl(PVD->getFunctionScopeIndex())
2697 ->getCanonicalDecl() == CanonPVD) {
2698 // OpenMP [2.15.3.7, linear Clause, Restrictions]
2699 // A list-item cannot appear in more than one linear clause.
2700 if (LinearArgs.count(CanonPVD) > 0) {
2701 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2702 << getOpenMPClauseName(OMPC_linear)
2703 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
2704 Diag(LinearArgs[CanonPVD]->getExprLoc(),
2705 diag::note_omp_explicit_dsa)
2706 << getOpenMPClauseName(OMPC_linear);
2707 continue;
2708 }
2709 // Each argument can appear in at most one uniform or linear clause.
2710 if (UniformedArgs.count(CanonPVD) > 0) {
2711 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2712 << getOpenMPClauseName(OMPC_linear)
2713 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
2714 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
2715 diag::note_omp_explicit_dsa)
2716 << getOpenMPClauseName(OMPC_uniform);
2717 continue;
2718 }
2719 LinearArgs[CanonPVD] = E;
2720 if (E->isValueDependent() || E->isTypeDependent() ||
2721 E->isInstantiationDependent() ||
2722 E->containsUnexpandedParameterPack())
2723 continue;
2724 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
2725 PVD->getOriginalType());
2726 continue;
2727 }
2728 }
2729 if (isa<CXXThisExpr>(E)) {
2730 if (UniformedLinearThis) {
2731 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
2732 << getOpenMPClauseName(OMPC_linear)
2733 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
2734 << E->getSourceRange();
2735 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
2736 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
2737 : OMPC_linear);
2738 continue;
2739 }
2740 UniformedLinearThis = E;
2741 if (E->isValueDependent() || E->isTypeDependent() ||
2742 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
2743 continue;
2744 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
2745 E->getType());
2746 continue;
2747 }
2748 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
2749 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
2750 }
2751 Expr *Step = nullptr;
2752 Expr *NewStep = nullptr;
2753 SmallVector<Expr *, 4> NewSteps;
2754 for (auto *E : Steps) {
2755 // Skip the same step expression, it was checked already.
2756 if (Step == E || !E) {
2757 NewSteps.push_back(E ? NewStep : nullptr);
2758 continue;
2759 }
2760 Step = E;
2761 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
2762 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2763 auto *CanonPVD = PVD->getCanonicalDecl();
2764 if (UniformedArgs.count(CanonPVD) == 0) {
2765 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
2766 << Step->getSourceRange();
2767 } else if (E->isValueDependent() || E->isTypeDependent() ||
2768 E->isInstantiationDependent() ||
2769 E->containsUnexpandedParameterPack() ||
2770 CanonPVD->getType()->hasIntegerRepresentation())
2771 NewSteps.push_back(Step);
2772 else {
2773 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
2774 << Step->getSourceRange();
2775 }
2776 continue;
2777 }
2778 NewStep = Step;
2779 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
2780 !Step->isInstantiationDependent() &&
2781 !Step->containsUnexpandedParameterPack()) {
2782 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
2783 .get();
2784 if (NewStep)
2785 NewStep = VerifyIntegerConstantExpression(NewStep).get();
2786 }
2787 NewSteps.push_back(NewStep);
2788 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00002789 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
2790 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00002791 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00002792 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
2793 const_cast<Expr **>(Linears.data()), Linears.size(),
2794 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
2795 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00002796 ADecl->addAttr(NewAttr);
2797 return ConvertDeclToDeclGroup(ADecl);
2798}
2799
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002800StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
2801 Stmt *AStmt,
2802 SourceLocation StartLoc,
2803 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002804 if (!AStmt)
2805 return StmtError();
2806
Alexey Bataev9959db52014-05-06 10:08:46 +00002807 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
2808 // 1.2.2 OpenMP Language Terminology
2809 // Structured block - An executable statement with a single entry at the
2810 // top and a single exit at the bottom.
2811 // The point of exit cannot be a branch out of the structured block.
2812 // longjmp() and throw() must not violate the entry/exit criteria.
2813 CS->getCapturedDecl()->setNothrow();
2814
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002815 getCurFunction()->setHasBranchProtectedScope();
2816
Alexey Bataev25e5b442015-09-15 12:52:43 +00002817 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
2818 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002819}
2820
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002821namespace {
2822/// \brief Helper class for checking canonical form of the OpenMP loops and
2823/// extracting iteration space of each loop in the loop nest, that will be used
2824/// for IR generation.
2825class OpenMPIterationSpaceChecker {
2826 /// \brief Reference to Sema.
2827 Sema &SemaRef;
2828 /// \brief A location for diagnostics (when there is no some better location).
2829 SourceLocation DefaultLoc;
2830 /// \brief A location for diagnostics (when increment is not compatible).
2831 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002832 /// \brief A source location for referring to loop init later.
2833 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002834 /// \brief A source location for referring to condition later.
2835 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002836 /// \brief A source location for referring to increment later.
2837 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002838 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002839 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002840 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002841 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002842 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002843 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002844 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002845 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002846 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002847 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002848 /// \brief This flag is true when condition is one of:
2849 /// Var < UB
2850 /// Var <= UB
2851 /// UB > Var
2852 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002853 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002854 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002855 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002856 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002857 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002858
2859public:
2860 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002861 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002862 /// \brief Check init-expr for canonical loop form and save loop counter
2863 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00002864 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002865 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
2866 /// for less/greater and for strict/non-strict comparison.
2867 bool CheckCond(Expr *S);
2868 /// \brief Check incr-expr for canonical loop form and return true if it
2869 /// does not conform, otherwise save loop step (#Step).
2870 bool CheckInc(Expr *S);
2871 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002872 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002873 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002874 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00002875 /// \brief Source range of the loop init.
2876 SourceRange GetInitSrcRange() const { return InitSrcRange; }
2877 /// \brief Source range of the loop condition.
2878 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
2879 /// \brief Source range of the loop increment.
2880 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
2881 /// \brief True if the step should be subtracted.
2882 bool ShouldSubtractStep() const { return SubtractStep; }
2883 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002884 Expr *
2885 BuildNumIterations(Scope *S, const bool LimitedType,
2886 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00002887 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00002888 Expr *BuildPreCond(Scope *S, Expr *Cond,
2889 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00002890 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002891 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
2892 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00002893 /// \brief Build reference expression to the private counter be used for
2894 /// codegen.
2895 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00002896 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00002897 Expr *BuildCounterInit() const;
2898 /// \brief Build step of the counter be used for codegen.
2899 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002900 /// \brief Return true if any expression is dependent.
2901 bool Dependent() const;
2902
2903private:
2904 /// \brief Check the right-hand side of an assignment in the increment
2905 /// expression.
2906 bool CheckIncRHS(Expr *RHS);
2907 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002908 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002909 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00002910 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00002911 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002912 /// \brief Helper to set loop increment.
2913 bool SetStep(Expr *NewStep, bool Subtract);
2914};
2915
2916bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002917 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002918 assert(!LB && !UB && !Step);
2919 return false;
2920 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002921 return LCDecl->getType()->isDependentType() ||
2922 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
2923 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002924}
2925
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002926static Expr *getExprAsWritten(Expr *E) {
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002927 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
2928 E = ExprTemp->getSubExpr();
2929
2930 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
2931 E = MTE->GetTemporaryExpr();
2932
2933 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
2934 E = Binder->getSubExpr();
2935
2936 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
2937 E = ICE->getSubExprAsWritten();
2938 return E->IgnoreParens();
2939}
2940
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002941bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
2942 Expr *NewLCRefExpr,
2943 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002944 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002945 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00002946 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002947 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002948 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002949 LCDecl = getCanonicalDecl(NewLCDecl);
2950 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002951 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
2952 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00002953 if ((Ctor->isCopyOrMoveConstructor() ||
2954 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
2955 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00002956 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002957 LB = NewLB;
2958 return false;
2959}
2960
2961bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00002962 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002963 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002964 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
2965 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002966 if (!NewUB)
2967 return true;
2968 UB = NewUB;
2969 TestIsLessOp = LessOp;
2970 TestIsStrictOp = StrictOp;
2971 ConditionSrcRange = SR;
2972 ConditionLoc = SL;
2973 return false;
2974}
2975
2976bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
2977 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002978 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00002979 if (!NewStep)
2980 return true;
2981 if (!NewStep->isValueDependent()) {
2982 // Check that the step is integer expression.
2983 SourceLocation StepLoc = NewStep->getLocStart();
2984 ExprResult Val =
2985 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
2986 if (Val.isInvalid())
2987 return true;
2988 NewStep = Val.get();
2989
2990 // OpenMP [2.6, Canonical Loop Form, Restrictions]
2991 // If test-expr is of form var relational-op b and relational-op is < or
2992 // <= then incr-expr must cause var to increase on each iteration of the
2993 // loop. If test-expr is of form var relational-op b and relational-op is
2994 // > or >= then incr-expr must cause var to decrease on each iteration of
2995 // the loop.
2996 // If test-expr is of form b relational-op var and relational-op is < or
2997 // <= then incr-expr must cause var to decrease on each iteration of the
2998 // loop. If test-expr is of form b relational-op var and relational-op is
2999 // > or >= then incr-expr must cause var to increase on each iteration of
3000 // the loop.
3001 llvm::APSInt Result;
3002 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3003 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3004 bool IsConstNeg =
3005 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003006 bool IsConstPos =
3007 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003008 bool IsConstZero = IsConstant && !Result.getBoolValue();
3009 if (UB && (IsConstZero ||
3010 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003011 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003012 SemaRef.Diag(NewStep->getExprLoc(),
3013 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003014 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003015 SemaRef.Diag(ConditionLoc,
3016 diag::note_omp_loop_cond_requres_compatible_incr)
3017 << TestIsLessOp << ConditionSrcRange;
3018 return true;
3019 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003020 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003021 NewStep =
3022 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3023 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003024 Subtract = !Subtract;
3025 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003026 }
3027
3028 Step = NewStep;
3029 SubtractStep = Subtract;
3030 return false;
3031}
3032
Alexey Bataev9c821032015-04-30 04:23:23 +00003033bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003034 // Check init-expr for canonical loop form and save loop counter
3035 // variable - #Var and its initialization value - #LB.
3036 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3037 // var = lb
3038 // integer-type var = lb
3039 // random-access-iterator-type var = lb
3040 // pointer-type var = lb
3041 //
3042 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003043 if (EmitDiags) {
3044 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3045 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003046 return true;
3047 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003048 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3049 if (!ExprTemp->cleanupsHaveSideEffects())
3050 S = ExprTemp->getSubExpr();
3051
Alexander Musmana5f070a2014-10-01 06:03:56 +00003052 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003053 if (Expr *E = dyn_cast<Expr>(S))
3054 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003055 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003056 if (BO->getOpcode() == BO_Assign) {
3057 auto *LHS = BO->getLHS()->IgnoreParens();
3058 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3059 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3060 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3061 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3062 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3063 }
3064 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3065 if (ME->isArrow() &&
3066 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3067 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3068 }
3069 }
David Majnemer9d168222016-08-05 17:44:54 +00003070 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003071 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003072 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003073 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003074 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003075 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003076 SemaRef.Diag(S->getLocStart(),
3077 diag::ext_omp_loop_not_canonical_init)
3078 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003079 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003080 }
3081 }
3082 }
David Majnemer9d168222016-08-05 17:44:54 +00003083 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003084 if (CE->getOperator() == OO_Equal) {
3085 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003086 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003087 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3088 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3089 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3090 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3091 }
3092 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3093 if (ME->isArrow() &&
3094 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3095 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3096 }
3097 }
3098 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003099
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003100 if (Dependent() || SemaRef.CurContext->isDependentContext())
3101 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003102 if (EmitDiags) {
3103 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3104 << S->getSourceRange();
3105 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003106 return true;
3107}
3108
Alexey Bataev23b69422014-06-18 07:08:49 +00003109/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003110/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003111static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003112 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003113 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003114 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003115 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3116 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003117 if ((Ctor->isCopyOrMoveConstructor() ||
3118 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3119 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003120 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003121 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
3122 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
3123 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3124 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3125 return getCanonicalDecl(ME->getMemberDecl());
3126 return getCanonicalDecl(VD);
3127 }
3128 }
3129 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3130 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3131 return getCanonicalDecl(ME->getMemberDecl());
3132 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003133}
3134
3135bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3136 // Check test-expr for canonical form, save upper-bound UB, flags for
3137 // less/greater and for strict/non-strict comparison.
3138 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3139 // var relational-op b
3140 // b relational-op var
3141 //
3142 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003143 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003144 return true;
3145 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003146 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003147 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003148 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003149 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003150 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003151 return SetUB(BO->getRHS(),
3152 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3153 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3154 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003155 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003156 return SetUB(BO->getLHS(),
3157 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3158 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3159 BO->getSourceRange(), BO->getOperatorLoc());
3160 }
David Majnemer9d168222016-08-05 17:44:54 +00003161 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003162 if (CE->getNumArgs() == 2) {
3163 auto Op = CE->getOperator();
3164 switch (Op) {
3165 case OO_Greater:
3166 case OO_GreaterEqual:
3167 case OO_Less:
3168 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003169 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003170 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3171 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3172 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003173 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003174 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3175 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3176 CE->getOperatorLoc());
3177 break;
3178 default:
3179 break;
3180 }
3181 }
3182 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003183 if (Dependent() || SemaRef.CurContext->isDependentContext())
3184 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003185 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003186 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003187 return true;
3188}
3189
3190bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3191 // RHS of canonical loop form increment can be:
3192 // var + incr
3193 // incr + var
3194 // var - incr
3195 //
3196 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003197 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003198 if (BO->isAdditiveOp()) {
3199 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003200 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003201 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003202 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003203 return SetStep(BO->getLHS(), false);
3204 }
David Majnemer9d168222016-08-05 17:44:54 +00003205 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003206 bool IsAdd = CE->getOperator() == OO_Plus;
3207 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003208 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003209 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003210 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003211 return SetStep(CE->getArg(0), false);
3212 }
3213 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003214 if (Dependent() || SemaRef.CurContext->isDependentContext())
3215 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003216 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003217 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003218 return true;
3219}
3220
3221bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3222 // Check incr-expr for canonical loop form and return true if it
3223 // does not conform.
3224 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3225 // ++var
3226 // var++
3227 // --var
3228 // var--
3229 // var += incr
3230 // var -= incr
3231 // var = var + incr
3232 // var = incr + var
3233 // var = var - incr
3234 //
3235 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003236 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003237 return true;
3238 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003239 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3240 if (!ExprTemp->cleanupsHaveSideEffects())
3241 S = ExprTemp->getSubExpr();
3242
Alexander Musmana5f070a2014-10-01 06:03:56 +00003243 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003244 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003245 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003246 if (UO->isIncrementDecrementOp() &&
3247 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003248 return SetStep(SemaRef
3249 .ActOnIntegerConstant(UO->getLocStart(),
3250 (UO->isDecrementOp() ? -1 : 1))
3251 .get(),
3252 false);
3253 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003254 switch (BO->getOpcode()) {
3255 case BO_AddAssign:
3256 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003257 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003258 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3259 break;
3260 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003261 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003262 return CheckIncRHS(BO->getRHS());
3263 break;
3264 default:
3265 break;
3266 }
David Majnemer9d168222016-08-05 17:44:54 +00003267 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003268 switch (CE->getOperator()) {
3269 case OO_PlusPlus:
3270 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003271 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003272 return SetStep(SemaRef
3273 .ActOnIntegerConstant(
3274 CE->getLocStart(),
3275 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3276 .get(),
3277 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003278 break;
3279 case OO_PlusEqual:
3280 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003281 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003282 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3283 break;
3284 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003285 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003286 return CheckIncRHS(CE->getArg(1));
3287 break;
3288 default:
3289 break;
3290 }
3291 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003292 if (Dependent() || SemaRef.CurContext->isDependentContext())
3293 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003294 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003295 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003296 return true;
3297}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003298
Alexey Bataev5a3af132016-03-29 08:58:54 +00003299static ExprResult
3300tryBuildCapture(Sema &SemaRef, Expr *Capture,
3301 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003302 if (SemaRef.CurContext->isDependentContext())
3303 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003304 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3305 return SemaRef.PerformImplicitConversion(
3306 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3307 /*AllowExplicit=*/true);
3308 auto I = Captures.find(Capture);
3309 if (I != Captures.end())
3310 return buildCapture(SemaRef, Capture, I->second);
3311 DeclRefExpr *Ref = nullptr;
3312 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
3313 Captures[Capture] = Ref;
3314 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003315}
3316
Alexander Musmana5f070a2014-10-01 06:03:56 +00003317/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003318Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
3319 Scope *S, const bool LimitedType,
3320 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003321 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003322 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003323 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003324 SemaRef.getLangOpts().CPlusPlus) {
3325 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003326 auto *UBExpr = TestIsLessOp ? UB : LB;
3327 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00003328 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
3329 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003330 if (!Upper || !Lower)
3331 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003332
3333 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
3334
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003335 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003336 // BuildBinOp already emitted error, this one is to point user to upper
3337 // and lower bound, and to tell what is passed to 'operator-'.
3338 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
3339 << Upper->getSourceRange() << Lower->getSourceRange();
3340 return nullptr;
3341 }
3342 }
3343
3344 if (!Diff.isUsable())
3345 return nullptr;
3346
3347 // Upper - Lower [- 1]
3348 if (TestIsStrictOp)
3349 Diff = SemaRef.BuildBinOp(
3350 S, DefaultLoc, BO_Sub, Diff.get(),
3351 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
3352 if (!Diff.isUsable())
3353 return nullptr;
3354
3355 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00003356 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
3357 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003358 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003359 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003360 if (!Diff.isUsable())
3361 return nullptr;
3362
3363 // Parentheses (for dumping/debugging purposes only).
3364 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
3365 if (!Diff.isUsable())
3366 return nullptr;
3367
3368 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003369 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003370 if (!Diff.isUsable())
3371 return nullptr;
3372
Alexander Musman174b3ca2014-10-06 11:16:29 +00003373 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003374 QualType Type = Diff.get()->getType();
3375 auto &C = SemaRef.Context;
3376 bool UseVarType = VarType->hasIntegerRepresentation() &&
3377 C.getTypeSize(Type) > C.getTypeSize(VarType);
3378 if (!Type->isIntegerType() || UseVarType) {
3379 unsigned NewSize =
3380 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
3381 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
3382 : Type->hasSignedIntegerRepresentation();
3383 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00003384 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
3385 Diff = SemaRef.PerformImplicitConversion(
3386 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
3387 if (!Diff.isUsable())
3388 return nullptr;
3389 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003390 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003391 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00003392 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
3393 if (NewSize != C.getTypeSize(Type)) {
3394 if (NewSize < C.getTypeSize(Type)) {
3395 assert(NewSize == 64 && "incorrect loop var size");
3396 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
3397 << InitSrcRange << ConditionSrcRange;
3398 }
3399 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003400 NewSize, Type->hasSignedIntegerRepresentation() ||
3401 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00003402 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
3403 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
3404 Sema::AA_Converting, true);
3405 if (!Diff.isUsable())
3406 return nullptr;
3407 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00003408 }
3409 }
3410
Alexander Musmana5f070a2014-10-01 06:03:56 +00003411 return Diff.get();
3412}
3413
Alexey Bataev5a3af132016-03-29 08:58:54 +00003414Expr *OpenMPIterationSpaceChecker::BuildPreCond(
3415 Scope *S, Expr *Cond,
3416 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003417 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
3418 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3419 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003420
Alexey Bataev5a3af132016-03-29 08:58:54 +00003421 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
3422 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
3423 if (!NewLB.isUsable() || !NewUB.isUsable())
3424 return nullptr;
3425
Alexey Bataev62dbb972015-04-22 11:59:37 +00003426 auto CondExpr = SemaRef.BuildBinOp(
3427 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
3428 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003429 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003430 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003431 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
3432 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00003433 CondExpr = SemaRef.PerformImplicitConversion(
3434 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
3435 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003436 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00003437 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3438 // Otherwise use original loop conditon and evaluate it in runtime.
3439 return CondExpr.isUsable() ? CondExpr.get() : Cond;
3440}
3441
Alexander Musmana5f070a2014-10-01 06:03:56 +00003442/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003443DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003444 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003445 auto *VD = dyn_cast<VarDecl>(LCDecl);
3446 if (!VD) {
3447 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
3448 auto *Ref = buildDeclRefExpr(
3449 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003450 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
3451 // If the loop control decl is explicitly marked as private, do not mark it
3452 // as captured again.
3453 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
3454 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003455 return Ref;
3456 }
3457 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00003458 DefaultLoc);
3459}
3460
3461Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003462 if (LCDecl && !LCDecl->isInvalidDecl()) {
3463 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00003464 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003465 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
3466 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00003467 if (PrivateVar->isInvalidDecl())
3468 return nullptr;
3469 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
3470 }
3471 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003472}
3473
Samuel Antao4c8035b2016-12-12 18:00:20 +00003474/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003475Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
3476
3477/// \brief Build step of the counter be used for codegen.
3478Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
3479
3480/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003481struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003482 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003483 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003484 /// \brief This expression calculates the number of iterations in the loop.
3485 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00003486 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003487 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003488 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00003489 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00003490 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003491 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00003492 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003493 /// \brief This is step for the #CounterVar used to generate its update:
3494 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00003495 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003496 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00003497 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003498 /// \brief Source range of the loop init.
3499 SourceRange InitSrcRange;
3500 /// \brief Source range of the loop condition.
3501 SourceRange CondSrcRange;
3502 /// \brief Source range of the loop increment.
3503 SourceRange IncSrcRange;
3504};
3505
Alexey Bataev23b69422014-06-18 07:08:49 +00003506} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003507
Alexey Bataev9c821032015-04-30 04:23:23 +00003508void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
3509 assert(getLangOpts().OpenMP && "OpenMP is not active.");
3510 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003511 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
3512 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00003513 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
3514 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003515 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
3516 if (auto *D = ISC.GetLoopDecl()) {
3517 auto *VD = dyn_cast<VarDecl>(D);
3518 if (!VD) {
3519 if (auto *Private = IsOpenMPCapturedDecl(D))
3520 VD = Private;
3521 else {
3522 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
3523 /*WithInit=*/false);
3524 VD = cast<VarDecl>(Ref->getDecl());
3525 }
3526 }
3527 DSAStack->addLoopControlVariable(D, VD);
3528 }
3529 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003530 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00003531 }
3532}
3533
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003534/// \brief Called on a for stmt to check and extract its iteration space
3535/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00003536static bool CheckOpenMPIterationSpace(
3537 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
3538 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003539 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003540 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003541 LoopIterationSpace &ResultIterSpace,
3542 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003543 // OpenMP [2.6, Canonical Loop Form]
3544 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00003545 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003546 if (!For) {
3547 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003548 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
3549 << getOpenMPDirectiveName(DKind) << NestedLoopCount
3550 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
3551 if (NestedLoopCount > 1) {
3552 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
3553 SemaRef.Diag(DSA.getConstructLoc(),
3554 diag::note_omp_collapse_ordered_expr)
3555 << 2 << CollapseLoopCountExpr->getSourceRange()
3556 << OrderedLoopCountExpr->getSourceRange();
3557 else if (CollapseLoopCountExpr)
3558 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3559 diag::note_omp_collapse_ordered_expr)
3560 << 0 << CollapseLoopCountExpr->getSourceRange();
3561 else
3562 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3563 diag::note_omp_collapse_ordered_expr)
3564 << 1 << OrderedLoopCountExpr->getSourceRange();
3565 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003566 return true;
3567 }
3568 assert(For->getBody());
3569
3570 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
3571
3572 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003573 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003574 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003575 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003576
3577 bool HasErrors = false;
3578
3579 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003580 if (auto *LCDecl = ISC.GetLoopDecl()) {
3581 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003582
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003583 // OpenMP [2.6, Canonical Loop Form]
3584 // Var is one of the following:
3585 // A variable of signed or unsigned integer type.
3586 // For C++, a variable of a random access iterator type.
3587 // For C, a variable of a pointer type.
3588 auto VarType = LCDecl->getType().getNonReferenceType();
3589 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
3590 !VarType->isPointerType() &&
3591 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
3592 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
3593 << SemaRef.getLangOpts().CPlusPlus;
3594 HasErrors = true;
3595 }
3596
3597 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
3598 // a Construct
3599 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3600 // parallel for construct is (are) private.
3601 // The loop iteration variable in the associated for-loop of a simd
3602 // construct with just one associated for-loop is linear with a
3603 // constant-linear-step that is the increment of the associated for-loop.
3604 // Exclude loop var from the list of variables with implicitly defined data
3605 // sharing attributes.
3606 VarsWithImplicitDSA.erase(LCDecl);
3607
3608 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
3609 // in a Construct, C/C++].
3610 // The loop iteration variable in the associated for-loop of a simd
3611 // construct with just one associated for-loop may be listed in a linear
3612 // clause with a constant-linear-step that is the increment of the
3613 // associated for-loop.
3614 // The loop iteration variable(s) in the associated for-loop(s) of a for or
3615 // parallel for construct may be listed in a private or lastprivate clause.
3616 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
3617 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
3618 // declared in the loop and it is predetermined as a private.
3619 auto PredeterminedCKind =
3620 isOpenMPSimdDirective(DKind)
3621 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
3622 : OMPC_private;
3623 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3624 DVar.CKind != PredeterminedCKind) ||
3625 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
3626 isOpenMPDistributeDirective(DKind)) &&
3627 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
3628 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
3629 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
3630 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
3631 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
3632 << getOpenMPClauseName(PredeterminedCKind);
3633 if (DVar.RefExpr == nullptr)
3634 DVar.CKind = PredeterminedCKind;
3635 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
3636 HasErrors = true;
3637 } else if (LoopDeclRefExpr != nullptr) {
3638 // Make the loop iteration variable private (for worksharing constructs),
3639 // linear (for simd directives with the only one associated loop) or
3640 // lastprivate (for simd directives with several collapsed or ordered
3641 // loops).
3642 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003643 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
3644 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003645 /*FromParent=*/false);
3646 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
3647 }
3648
3649 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
3650
3651 // Check test-expr.
3652 HasErrors |= ISC.CheckCond(For->getCond());
3653
3654 // Check incr-expr.
3655 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003656 }
3657
Alexander Musmana5f070a2014-10-01 06:03:56 +00003658 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003659 return HasErrors;
3660
Alexander Musmana5f070a2014-10-01 06:03:56 +00003661 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003662 ResultIterSpace.PreCond =
3663 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00003664 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00003665 DSA.getCurScope(),
3666 (isOpenMPWorksharingDirective(DKind) ||
3667 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
3668 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003669 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00003670 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003671 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
3672 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
3673 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
3674 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
3675 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
3676 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
3677
Alexey Bataev62dbb972015-04-22 11:59:37 +00003678 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
3679 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003680 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00003681 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00003682 ResultIterSpace.CounterInit == nullptr ||
3683 ResultIterSpace.CounterStep == nullptr);
3684
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003685 return HasErrors;
3686}
3687
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003688/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003689static ExprResult
3690BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
3691 ExprResult Start,
3692 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003693 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003694 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
3695 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003696 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00003697 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00003698 VarRef.get()->getType())) {
3699 NewStart = SemaRef.PerformImplicitConversion(
3700 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
3701 /*AllowExplicit=*/true);
3702 if (!NewStart.isUsable())
3703 return ExprError();
3704 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003705
3706 auto Init =
3707 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3708 return Init;
3709}
3710
Alexander Musmana5f070a2014-10-01 06:03:56 +00003711/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003712static ExprResult
3713BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
3714 ExprResult VarRef, ExprResult Start, ExprResult Iter,
3715 ExprResult Step, bool Subtract,
3716 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003717 // Add parentheses (for debugging purposes only).
3718 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
3719 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
3720 !Step.isUsable())
3721 return ExprError();
3722
Alexey Bataev5a3af132016-03-29 08:58:54 +00003723 ExprResult NewStep = Step;
3724 if (Captures)
3725 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003726 if (NewStep.isInvalid())
3727 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003728 ExprResult Update =
3729 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003730 if (!Update.isUsable())
3731 return ExprError();
3732
Alexey Bataevc0214e02016-02-16 12:13:49 +00003733 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
3734 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003735 ExprResult NewStart = Start;
3736 if (Captures)
3737 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003738 if (NewStart.isInvalid())
3739 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003740
Alexey Bataevc0214e02016-02-16 12:13:49 +00003741 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
3742 ExprResult SavedUpdate = Update;
3743 ExprResult UpdateVal;
3744 if (VarRef.get()->getType()->isOverloadableType() ||
3745 NewStart.get()->getType()->isOverloadableType() ||
3746 Update.get()->getType()->isOverloadableType()) {
3747 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
3748 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
3749 Update =
3750 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
3751 if (Update.isUsable()) {
3752 UpdateVal =
3753 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
3754 VarRef.get(), SavedUpdate.get());
3755 if (UpdateVal.isUsable()) {
3756 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
3757 UpdateVal.get());
3758 }
3759 }
3760 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
3761 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003762
Alexey Bataevc0214e02016-02-16 12:13:49 +00003763 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
3764 if (!Update.isUsable() || !UpdateVal.isUsable()) {
3765 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
3766 NewStart.get(), SavedUpdate.get());
3767 if (!Update.isUsable())
3768 return ExprError();
3769
Alexey Bataev11481f52016-02-17 10:29:05 +00003770 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
3771 VarRef.get()->getType())) {
3772 Update = SemaRef.PerformImplicitConversion(
3773 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
3774 if (!Update.isUsable())
3775 return ExprError();
3776 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00003777
3778 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
3779 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003780 return Update;
3781}
3782
3783/// \brief Convert integer expression \a E to make it have at least \a Bits
3784/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00003785static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00003786 if (E == nullptr)
3787 return ExprError();
3788 auto &C = SemaRef.Context;
3789 QualType OldType = E->getType();
3790 unsigned HasBits = C.getTypeSize(OldType);
3791 if (HasBits >= Bits)
3792 return ExprResult(E);
3793 // OK to convert to signed, because new type has more bits than old.
3794 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
3795 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
3796 true);
3797}
3798
3799/// \brief Check if the given expression \a E is a constant integer that fits
3800/// into \a Bits bits.
3801static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
3802 if (E == nullptr)
3803 return false;
3804 llvm::APSInt Result;
3805 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
3806 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
3807 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003808}
3809
Alexey Bataev5a3af132016-03-29 08:58:54 +00003810/// Build preinits statement for the given declarations.
3811static Stmt *buildPreInits(ASTContext &Context,
3812 SmallVectorImpl<Decl *> &PreInits) {
3813 if (!PreInits.empty()) {
3814 return new (Context) DeclStmt(
3815 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
3816 SourceLocation(), SourceLocation());
3817 }
3818 return nullptr;
3819}
3820
3821/// Build preinits statement for the given declarations.
3822static Stmt *buildPreInits(ASTContext &Context,
3823 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
3824 if (!Captures.empty()) {
3825 SmallVector<Decl *, 16> PreInits;
3826 for (auto &Pair : Captures)
3827 PreInits.push_back(Pair.second->getDecl());
3828 return buildPreInits(Context, PreInits);
3829 }
3830 return nullptr;
3831}
3832
3833/// Build postupdate expression for the given list of postupdates expressions.
3834static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
3835 Expr *PostUpdate = nullptr;
3836 if (!PostUpdates.empty()) {
3837 for (auto *E : PostUpdates) {
3838 Expr *ConvE = S.BuildCStyleCastExpr(
3839 E->getExprLoc(),
3840 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
3841 E->getExprLoc(), E)
3842 .get();
3843 PostUpdate = PostUpdate
3844 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
3845 PostUpdate, ConvE)
3846 .get()
3847 : ConvE;
3848 }
3849 }
3850 return PostUpdate;
3851}
3852
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003853/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00003854/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
3855/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00003856static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00003857CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
3858 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
3859 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003860 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00003861 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003862 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003863 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003864 // Found 'collapse' clause - calculate collapse number.
3865 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00003866 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003867 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00003868 }
3869 if (OrderedLoopCountExpr) {
3870 // Found 'ordered' clause - calculate collapse number.
3871 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00003872 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
3873 if (Result.getLimitedValue() < NestedLoopCount) {
3874 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
3875 diag::err_omp_wrong_ordered_loop_count)
3876 << OrderedLoopCountExpr->getSourceRange();
3877 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
3878 diag::note_collapse_loop_count)
3879 << CollapseLoopCountExpr->getSourceRange();
3880 }
3881 NestedLoopCount = Result.getLimitedValue();
3882 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003883 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003884 // This is helper routine for loop directives (e.g., 'for', 'simd',
3885 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00003886 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003887 SmallVector<LoopIterationSpace, 4> IterSpaces;
3888 IterSpaces.resize(NestedLoopCount);
3889 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003890 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00003891 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00003892 NestedLoopCount, CollapseLoopCountExpr,
3893 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003894 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00003895 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003896 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003897 // OpenMP [2.8.1, simd construct, Restrictions]
3898 // All loops associated with the construct must be perfectly nested; that
3899 // is, there must be no intervening code nor any OpenMP directive between
3900 // any two loops.
3901 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003902 }
3903
Alexander Musmana5f070a2014-10-01 06:03:56 +00003904 Built.clear(/* size */ NestedLoopCount);
3905
3906 if (SemaRef.CurContext->isDependentContext())
3907 return NestedLoopCount;
3908
3909 // An example of what is generated for the following code:
3910 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00003911 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00003912 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00003913 // for (k = 0; k < NK; ++k)
3914 // for (j = J0; j < NJ; j+=2) {
3915 // <loop body>
3916 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003917 //
3918 // We generate the code below.
3919 // Note: the loop body may be outlined in CodeGen.
3920 // Note: some counters may be C++ classes, operator- is used to find number of
3921 // iterations and operator+= to calculate counter value.
3922 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
3923 // or i64 is currently supported).
3924 //
3925 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
3926 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
3927 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
3928 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
3929 // // similar updates for vars in clauses (e.g. 'linear')
3930 // <loop body (using local i and j)>
3931 // }
3932 // i = NI; // assign final values of counters
3933 // j = NJ;
3934 //
3935
3936 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
3937 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00003938 // Precondition tests if there is at least one iteration (all conditions are
3939 // true).
3940 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003941 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003942 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003943 32 /* Bits */, SemaRef
3944 .PerformImplicitConversion(
3945 N0->IgnoreImpCasts(), N0->getType(),
3946 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003947 .get(),
3948 SemaRef);
3949 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00003950 64 /* Bits */, SemaRef
3951 .PerformImplicitConversion(
3952 N0->IgnoreImpCasts(), N0->getType(),
3953 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003954 .get(),
3955 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00003956
3957 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
3958 return NestedLoopCount;
3959
3960 auto &C = SemaRef.Context;
3961 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
3962
3963 Scope *CurScope = DSA.getCurScope();
3964 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00003965 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00003966 PreCond =
3967 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
3968 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00003969 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003970 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00003971 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003972 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
3973 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003974 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003975 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003976 SemaRef
3977 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3978 Sema::AA_Converting,
3979 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003980 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003981 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003982 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00003983 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00003984 SemaRef
3985 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
3986 Sema::AA_Converting,
3987 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00003988 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003989 }
3990
3991 // Choose either the 32-bit or 64-bit version.
3992 ExprResult LastIteration = LastIteration64;
3993 if (LastIteration32.isUsable() &&
3994 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
3995 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
3996 FitsInto(
3997 32 /* Bits */,
3998 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
3999 LastIteration64.get(), SemaRef)))
4000 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004001 QualType VType = LastIteration.get()->getType();
4002 QualType RealVType = VType;
4003 QualType StrideVType = VType;
4004 if (isOpenMPTaskLoopDirective(DKind)) {
4005 VType =
4006 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4007 StrideVType =
4008 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4009 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004010
4011 if (!LastIteration.isUsable())
4012 return 0;
4013
4014 // Save the number of iterations.
4015 ExprResult NumIterations = LastIteration;
4016 {
4017 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004018 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4019 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004020 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4021 if (!LastIteration.isUsable())
4022 return 0;
4023 }
4024
4025 // Calculate the last iteration number beforehand instead of doing this on
4026 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4027 llvm::APSInt Result;
4028 bool IsConstant =
4029 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4030 ExprResult CalcLastIteration;
4031 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004032 ExprResult SaveRef =
4033 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004034 LastIteration = SaveRef;
4035
4036 // Prepare SaveRef + 1.
4037 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004038 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004039 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4040 if (!NumIterations.isUsable())
4041 return 0;
4042 }
4043
4044 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4045
David Majnemer9d168222016-08-05 17:44:54 +00004046 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolli9925f152016-06-27 14:55:37 +00004047 ExprResult LB, UB, IL, ST, EUB, PrevLB, PrevUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004048 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4049 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004050 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004051 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4052 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004053 SemaRef.AddInitializerToDecl(LBDecl,
4054 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4055 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004056
4057 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004058 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4059 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004060 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004061 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004062
4063 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4064 // This will be used to implement clause 'lastprivate'.
4065 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004066 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4067 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004068 SemaRef.AddInitializerToDecl(ILDecl,
4069 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4070 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004071
4072 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004073 VarDecl *STDecl =
4074 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4075 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004076 SemaRef.AddInitializerToDecl(STDecl,
4077 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4078 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004079
4080 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004081 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004082 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4083 UB.get(), LastIteration.get());
4084 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4085 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4086 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4087 CondOp.get());
4088 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004089
4090 // If we have a combined directive that combines 'distribute', 'for' or
4091 // 'simd' we need to be able to access the bounds of the schedule of the
4092 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4093 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4094 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4095 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
4096
4097 // We expect to have at least 2 more parameters than the 'parallel'
4098 // directive does - the lower and upper bounds of the previous schedule.
4099 assert(CD->getNumParams() >= 4 &&
4100 "Unexpected number of parameters in loop combined directive");
4101
4102 // Set the proper type for the bounds given what we learned from the
4103 // enclosed loops.
4104 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4105 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4106
4107 // Previous lower and upper bounds are obtained from the region
4108 // parameters.
4109 PrevLB =
4110 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4111 PrevUB =
4112 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4113 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004114 }
4115
4116 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004117 ExprResult IV;
4118 ExprResult Init;
4119 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004120 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4121 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004122 Expr *RHS =
4123 (isOpenMPWorksharingDirective(DKind) ||
4124 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4125 ? LB.get()
4126 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004127 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4128 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004129 }
4130
Alexander Musmanc6388682014-12-15 07:07:06 +00004131 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004132 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004133 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004134 (isOpenMPWorksharingDirective(DKind) ||
4135 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004136 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4137 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4138 NumIterations.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004139
4140 // Loop increment (IV = IV + 1)
4141 SourceLocation IncLoc;
4142 ExprResult Inc =
4143 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4144 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4145 if (!Inc.isUsable())
4146 return 0;
4147 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004148 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4149 if (!Inc.isUsable())
4150 return 0;
4151
4152 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4153 // Used for directives with static scheduling.
4154 ExprResult NextLB, NextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004155 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4156 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004157 // LB + ST
4158 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4159 if (!NextLB.isUsable())
4160 return 0;
4161 // LB = LB + ST
4162 NextLB =
4163 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4164 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4165 if (!NextLB.isUsable())
4166 return 0;
4167 // UB + ST
4168 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4169 if (!NextUB.isUsable())
4170 return 0;
4171 // UB = UB + ST
4172 NextUB =
4173 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4174 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4175 if (!NextUB.isUsable())
4176 return 0;
4177 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004178
4179 // Build updates and final values of the loop counters.
4180 bool HasErrors = false;
4181 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004182 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004183 Built.Updates.resize(NestedLoopCount);
4184 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004185 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004186 {
4187 ExprResult Div;
4188 // Go from inner nested loop to outer.
4189 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4190 LoopIterationSpace &IS = IterSpaces[Cnt];
4191 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4192 // Build: Iter = (IV / Div) % IS.NumIters
4193 // where Div is product of previous iterations' IS.NumIters.
4194 ExprResult Iter;
4195 if (Div.isUsable()) {
4196 Iter =
4197 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4198 } else {
4199 Iter = IV;
4200 assert((Cnt == (int)NestedLoopCount - 1) &&
4201 "unusable div expected on first iteration only");
4202 }
4203
4204 if (Cnt != 0 && Iter.isUsable())
4205 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4206 IS.NumIterations);
4207 if (!Iter.isUsable()) {
4208 HasErrors = true;
4209 break;
4210 }
4211
Alexey Bataev39f915b82015-05-08 10:41:21 +00004212 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004213 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4214 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4215 IS.CounterVar->getExprLoc(),
4216 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004217 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004218 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004219 if (!Init.isUsable()) {
4220 HasErrors = true;
4221 break;
4222 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00004223 ExprResult Update = BuildCounterUpdate(
4224 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
4225 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004226 if (!Update.isUsable()) {
4227 HasErrors = true;
4228 break;
4229 }
4230
4231 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
4232 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00004233 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004234 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004235 if (!Final.isUsable()) {
4236 HasErrors = true;
4237 break;
4238 }
4239
4240 // Build Div for the next iteration: Div <- Div * IS.NumIters
4241 if (Cnt != 0) {
4242 if (Div.isUnset())
4243 Div = IS.NumIterations;
4244 else
4245 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
4246 IS.NumIterations);
4247
4248 // Add parentheses (for debugging purposes only).
4249 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00004250 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004251 if (!Div.isUsable()) {
4252 HasErrors = true;
4253 break;
4254 }
Alexey Bataev8b427062016-05-25 12:36:08 +00004255 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004256 }
4257 if (!Update.isUsable() || !Final.isUsable()) {
4258 HasErrors = true;
4259 break;
4260 }
4261 // Save results
4262 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00004263 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004264 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004265 Built.Updates[Cnt] = Update.get();
4266 Built.Finals[Cnt] = Final.get();
4267 }
4268 }
4269
4270 if (HasErrors)
4271 return 0;
4272
4273 // Save results
4274 Built.IterationVarRef = IV.get();
4275 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00004276 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004277 Built.CalcLastIteration =
4278 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004279 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00004280 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004281 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004282 Built.Init = Init.get();
4283 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004284 Built.LB = LB.get();
4285 Built.UB = UB.get();
4286 Built.IL = IL.get();
4287 Built.ST = ST.get();
4288 Built.EUB = EUB.get();
4289 Built.NLB = NextLB.get();
4290 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004291 Built.PrevLB = PrevLB.get();
4292 Built.PrevUB = PrevUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004293
Alexey Bataev8b427062016-05-25 12:36:08 +00004294 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
4295 // Fill data for doacross depend clauses.
4296 for (auto Pair : DSA.getDoacrossDependClauses()) {
4297 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4298 Pair.first->setCounterValue(CounterVal);
4299 else {
4300 if (NestedLoopCount != Pair.second.size() ||
4301 NestedLoopCount != LoopMultipliers.size() + 1) {
4302 // Erroneous case - clause has some problems.
4303 Pair.first->setCounterValue(CounterVal);
4304 continue;
4305 }
4306 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
4307 auto I = Pair.second.rbegin();
4308 auto IS = IterSpaces.rbegin();
4309 auto ILM = LoopMultipliers.rbegin();
4310 Expr *UpCounterVal = CounterVal;
4311 Expr *Multiplier = nullptr;
4312 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4313 if (I->first) {
4314 assert(IS->CounterStep);
4315 Expr *NormalizedOffset =
4316 SemaRef
4317 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
4318 I->first, IS->CounterStep)
4319 .get();
4320 if (Multiplier) {
4321 NormalizedOffset =
4322 SemaRef
4323 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
4324 NormalizedOffset, Multiplier)
4325 .get();
4326 }
4327 assert(I->second == OO_Plus || I->second == OO_Minus);
4328 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00004329 UpCounterVal = SemaRef
4330 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
4331 UpCounterVal, NormalizedOffset)
4332 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00004333 }
4334 Multiplier = *ILM;
4335 ++I;
4336 ++IS;
4337 ++ILM;
4338 }
4339 Pair.first->setCounterValue(UpCounterVal);
4340 }
4341 }
4342
Alexey Bataevabfc0692014-06-25 06:52:00 +00004343 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004344}
4345
Alexey Bataev10e775f2015-07-30 11:36:16 +00004346static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004347 auto CollapseClauses =
4348 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
4349 if (CollapseClauses.begin() != CollapseClauses.end())
4350 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004351 return nullptr;
4352}
4353
Alexey Bataev10e775f2015-07-30 11:36:16 +00004354static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00004355 auto OrderedClauses =
4356 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
4357 if (OrderedClauses.begin() != OrderedClauses.end())
4358 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004359 return nullptr;
4360}
4361
Kelvin Lic5609492016-07-15 04:39:07 +00004362static bool checkSimdlenSafelenSpecified(Sema &S,
4363 const ArrayRef<OMPClause *> Clauses) {
4364 OMPSafelenClause *Safelen = nullptr;
4365 OMPSimdlenClause *Simdlen = nullptr;
4366
4367 for (auto *Clause : Clauses) {
4368 if (Clause->getClauseKind() == OMPC_safelen)
4369 Safelen = cast<OMPSafelenClause>(Clause);
4370 else if (Clause->getClauseKind() == OMPC_simdlen)
4371 Simdlen = cast<OMPSimdlenClause>(Clause);
4372 if (Safelen && Simdlen)
4373 break;
4374 }
4375
4376 if (Simdlen && Safelen) {
4377 llvm::APSInt SimdlenRes, SafelenRes;
4378 auto SimdlenLength = Simdlen->getSimdlen();
4379 auto SafelenLength = Safelen->getSafelen();
4380 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
4381 SimdlenLength->isInstantiationDependent() ||
4382 SimdlenLength->containsUnexpandedParameterPack())
4383 return false;
4384 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
4385 SafelenLength->isInstantiationDependent() ||
4386 SafelenLength->containsUnexpandedParameterPack())
4387 return false;
4388 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
4389 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
4390 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
4391 // If both simdlen and safelen clauses are specified, the value of the
4392 // simdlen parameter must be less than or equal to the value of the safelen
4393 // parameter.
4394 if (SimdlenRes > SafelenRes) {
4395 S.Diag(SimdlenLength->getExprLoc(),
4396 diag::err_omp_wrong_simdlen_safelen_values)
4397 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
4398 return true;
4399 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00004400 }
4401 return false;
4402}
4403
Alexey Bataev4acb8592014-07-07 13:01:15 +00004404StmtResult Sema::ActOnOpenMPSimdDirective(
4405 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4406 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004407 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004408 if (!AStmt)
4409 return StmtError();
4410
4411 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004412 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004413 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4414 // define the nested loops number.
4415 unsigned NestedLoopCount = CheckOpenMPLoop(
4416 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4417 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004418 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004419 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004420
Alexander Musmana5f070a2014-10-01 06:03:56 +00004421 assert((CurContext->isDependentContext() || B.builtAll()) &&
4422 "omp simd loop exprs were not built");
4423
Alexander Musman3276a272015-03-21 10:12:56 +00004424 if (!CurContext->isDependentContext()) {
4425 // Finalize the clauses that need pre-built expressions for CodeGen.
4426 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004427 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00004428 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004429 B.NumIterations, *this, CurScope,
4430 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00004431 return StmtError();
4432 }
4433 }
4434
Kelvin Lic5609492016-07-15 04:39:07 +00004435 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004436 return StmtError();
4437
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004438 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004439 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4440 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004441}
4442
Alexey Bataev4acb8592014-07-07 13:01:15 +00004443StmtResult Sema::ActOnOpenMPForDirective(
4444 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4445 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004446 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004447 if (!AStmt)
4448 return StmtError();
4449
4450 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004451 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004452 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4453 // define the nested loops number.
4454 unsigned NestedLoopCount = CheckOpenMPLoop(
4455 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
4456 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00004457 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00004458 return StmtError();
4459
Alexander Musmana5f070a2014-10-01 06:03:56 +00004460 assert((CurContext->isDependentContext() || B.builtAll()) &&
4461 "omp for loop exprs were not built");
4462
Alexey Bataev54acd402015-08-04 11:18:19 +00004463 if (!CurContext->isDependentContext()) {
4464 // Finalize the clauses that need pre-built expressions for CodeGen.
4465 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004466 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004467 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004468 B.NumIterations, *this, CurScope,
4469 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004470 return StmtError();
4471 }
4472 }
4473
Alexey Bataevf29276e2014-06-18 04:14:57 +00004474 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004475 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004476 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00004477}
4478
Alexander Musmanf82886e2014-09-18 05:12:34 +00004479StmtResult Sema::ActOnOpenMPForSimdDirective(
4480 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4481 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004482 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004483 if (!AStmt)
4484 return StmtError();
4485
4486 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00004487 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004488 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4489 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00004490 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004491 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
4492 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4493 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004494 if (NestedLoopCount == 0)
4495 return StmtError();
4496
Alexander Musmanc6388682014-12-15 07:07:06 +00004497 assert((CurContext->isDependentContext() || B.builtAll()) &&
4498 "omp for simd loop exprs were not built");
4499
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004500 if (!CurContext->isDependentContext()) {
4501 // Finalize the clauses that need pre-built expressions for CodeGen.
4502 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004503 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004504 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004505 B.NumIterations, *this, CurScope,
4506 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00004507 return StmtError();
4508 }
4509 }
4510
Kelvin Lic5609492016-07-15 04:39:07 +00004511 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004512 return StmtError();
4513
Alexander Musmanf82886e2014-09-18 05:12:34 +00004514 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004515 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
4516 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004517}
4518
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004519StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
4520 Stmt *AStmt,
4521 SourceLocation StartLoc,
4522 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004523 if (!AStmt)
4524 return StmtError();
4525
4526 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004527 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004528 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004529 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004530 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004531 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004532 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004533 return StmtError();
4534 // All associated statements must be '#pragma omp section' except for
4535 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004536 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004537 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4538 if (SectionStmt)
4539 Diag(SectionStmt->getLocStart(),
4540 diag::err_omp_sections_substmt_not_section);
4541 return StmtError();
4542 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004543 cast<OMPSectionDirective>(SectionStmt)
4544 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004545 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004546 } else {
4547 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
4548 return StmtError();
4549 }
4550
4551 getCurFunction()->setHasBranchProtectedScope();
4552
Alexey Bataev25e5b442015-09-15 12:52:43 +00004553 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4554 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004555}
4556
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004557StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
4558 SourceLocation StartLoc,
4559 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004560 if (!AStmt)
4561 return StmtError();
4562
4563 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004564
4565 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004566 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004567
Alexey Bataev25e5b442015-09-15 12:52:43 +00004568 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
4569 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004570}
4571
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004572StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
4573 Stmt *AStmt,
4574 SourceLocation StartLoc,
4575 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004576 if (!AStmt)
4577 return StmtError();
4578
4579 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00004580
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004581 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00004582
Alexey Bataev3255bf32015-01-19 05:20:46 +00004583 // OpenMP [2.7.3, single Construct, Restrictions]
4584 // The copyprivate clause must not be used with the nowait clause.
4585 OMPClause *Nowait = nullptr;
4586 OMPClause *Copyprivate = nullptr;
4587 for (auto *Clause : Clauses) {
4588 if (Clause->getClauseKind() == OMPC_nowait)
4589 Nowait = Clause;
4590 else if (Clause->getClauseKind() == OMPC_copyprivate)
4591 Copyprivate = Clause;
4592 if (Copyprivate && Nowait) {
4593 Diag(Copyprivate->getLocStart(),
4594 diag::err_omp_single_copyprivate_with_nowait);
4595 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
4596 return StmtError();
4597 }
4598 }
4599
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004600 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
4601}
4602
Alexander Musman80c22892014-07-17 08:54:58 +00004603StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
4604 SourceLocation StartLoc,
4605 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004606 if (!AStmt)
4607 return StmtError();
4608
4609 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00004610
4611 getCurFunction()->setHasBranchProtectedScope();
4612
4613 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
4614}
4615
Alexey Bataev28c75412015-12-15 08:19:24 +00004616StmtResult Sema::ActOnOpenMPCriticalDirective(
4617 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
4618 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004619 if (!AStmt)
4620 return StmtError();
4621
4622 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004623
Alexey Bataev28c75412015-12-15 08:19:24 +00004624 bool ErrorFound = false;
4625 llvm::APSInt Hint;
4626 SourceLocation HintLoc;
4627 bool DependentHint = false;
4628 for (auto *C : Clauses) {
4629 if (C->getClauseKind() == OMPC_hint) {
4630 if (!DirName.getName()) {
4631 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
4632 ErrorFound = true;
4633 }
4634 Expr *E = cast<OMPHintClause>(C)->getHint();
4635 if (E->isTypeDependent() || E->isValueDependent() ||
4636 E->isInstantiationDependent())
4637 DependentHint = true;
4638 else {
4639 Hint = E->EvaluateKnownConstInt(Context);
4640 HintLoc = C->getLocStart();
4641 }
4642 }
4643 }
4644 if (ErrorFound)
4645 return StmtError();
4646 auto Pair = DSAStack->getCriticalWithHint(DirName);
4647 if (Pair.first && DirName.getName() && !DependentHint) {
4648 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
4649 Diag(StartLoc, diag::err_omp_critical_with_hint);
4650 if (HintLoc.isValid()) {
4651 Diag(HintLoc, diag::note_omp_critical_hint_here)
4652 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
4653 } else
4654 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
4655 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
4656 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
4657 << 1
4658 << C->getHint()->EvaluateKnownConstInt(Context).toString(
4659 /*Radix=*/10, /*Signed=*/false);
4660 } else
4661 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
4662 }
4663 }
4664
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004665 getCurFunction()->setHasBranchProtectedScope();
4666
Alexey Bataev28c75412015-12-15 08:19:24 +00004667 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
4668 Clauses, AStmt);
4669 if (!Pair.first && DirName.getName() && !DependentHint)
4670 DSAStack->addCriticalWithHint(Dir, Hint);
4671 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004672}
4673
Alexey Bataev4acb8592014-07-07 13:01:15 +00004674StmtResult Sema::ActOnOpenMPParallelForDirective(
4675 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4676 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004677 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004678 if (!AStmt)
4679 return StmtError();
4680
Alexey Bataev4acb8592014-07-07 13:01:15 +00004681 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4682 // 1.2.2 OpenMP Language Terminology
4683 // Structured block - An executable statement with a single entry at the
4684 // top and a single exit at the bottom.
4685 // The point of exit cannot be a branch out of the structured block.
4686 // longjmp() and throw() must not violate the entry/exit criteria.
4687 CS->getCapturedDecl()->setNothrow();
4688
Alexander Musmanc6388682014-12-15 07:07:06 +00004689 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004690 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4691 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004692 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004693 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
4694 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4695 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004696 if (NestedLoopCount == 0)
4697 return StmtError();
4698
Alexander Musmana5f070a2014-10-01 06:03:56 +00004699 assert((CurContext->isDependentContext() || B.builtAll()) &&
4700 "omp parallel for loop exprs were not built");
4701
Alexey Bataev54acd402015-08-04 11:18:19 +00004702 if (!CurContext->isDependentContext()) {
4703 // Finalize the clauses that need pre-built expressions for CodeGen.
4704 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004705 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00004706 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004707 B.NumIterations, *this, CurScope,
4708 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00004709 return StmtError();
4710 }
4711 }
4712
Alexey Bataev4acb8592014-07-07 13:01:15 +00004713 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00004714 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004715 NestedLoopCount, Clauses, AStmt, B,
4716 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00004717}
4718
Alexander Musmane4e893b2014-09-23 09:33:00 +00004719StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
4720 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
4721 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004722 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004723 if (!AStmt)
4724 return StmtError();
4725
Alexander Musmane4e893b2014-09-23 09:33:00 +00004726 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
4727 // 1.2.2 OpenMP Language Terminology
4728 // Structured block - An executable statement with a single entry at the
4729 // top and a single exit at the bottom.
4730 // The point of exit cannot be a branch out of the structured block.
4731 // longjmp() and throw() must not violate the entry/exit criteria.
4732 CS->getCapturedDecl()->setNothrow();
4733
Alexander Musmanc6388682014-12-15 07:07:06 +00004734 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004735 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
4736 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00004737 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00004738 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
4739 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
4740 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004741 if (NestedLoopCount == 0)
4742 return StmtError();
4743
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004744 if (!CurContext->isDependentContext()) {
4745 // Finalize the clauses that need pre-built expressions for CodeGen.
4746 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00004747 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004748 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004749 B.NumIterations, *this, CurScope,
4750 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00004751 return StmtError();
4752 }
4753 }
4754
Kelvin Lic5609492016-07-15 04:39:07 +00004755 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00004756 return StmtError();
4757
Alexander Musmane4e893b2014-09-23 09:33:00 +00004758 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004759 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00004760 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004761}
4762
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004763StmtResult
4764Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
4765 Stmt *AStmt, SourceLocation StartLoc,
4766 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004767 if (!AStmt)
4768 return StmtError();
4769
4770 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004771 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00004772 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004773 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00004774 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004775 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00004776 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004777 return StmtError();
4778 // All associated statements must be '#pragma omp section' except for
4779 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00004780 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004781 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
4782 if (SectionStmt)
4783 Diag(SectionStmt->getLocStart(),
4784 diag::err_omp_parallel_sections_substmt_not_section);
4785 return StmtError();
4786 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00004787 cast<OMPSectionDirective>(SectionStmt)
4788 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004789 }
4790 } else {
4791 Diag(AStmt->getLocStart(),
4792 diag::err_omp_parallel_sections_not_compound_stmt);
4793 return StmtError();
4794 }
4795
4796 getCurFunction()->setHasBranchProtectedScope();
4797
Alexey Bataev25e5b442015-09-15 12:52:43 +00004798 return OMPParallelSectionsDirective::Create(
4799 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004800}
4801
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004802StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
4803 Stmt *AStmt, SourceLocation StartLoc,
4804 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004805 if (!AStmt)
4806 return StmtError();
4807
David Majnemer9d168222016-08-05 17:44:54 +00004808 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004809 // 1.2.2 OpenMP Language Terminology
4810 // Structured block - An executable statement with a single entry at the
4811 // top and a single exit at the bottom.
4812 // The point of exit cannot be a branch out of the structured block.
4813 // longjmp() and throw() must not violate the entry/exit criteria.
4814 CS->getCapturedDecl()->setNothrow();
4815
4816 getCurFunction()->setHasBranchProtectedScope();
4817
Alexey Bataev25e5b442015-09-15 12:52:43 +00004818 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4819 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004820}
4821
Alexey Bataev68446b72014-07-18 07:47:19 +00004822StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
4823 SourceLocation EndLoc) {
4824 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
4825}
4826
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004827StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
4828 SourceLocation EndLoc) {
4829 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
4830}
4831
Alexey Bataev2df347a2014-07-18 10:17:07 +00004832StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
4833 SourceLocation EndLoc) {
4834 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
4835}
4836
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004837StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
4838 SourceLocation StartLoc,
4839 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004840 if (!AStmt)
4841 return StmtError();
4842
4843 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004844
4845 getCurFunction()->setHasBranchProtectedScope();
4846
4847 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
4848}
4849
Alexey Bataev6125da92014-07-21 11:26:11 +00004850StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
4851 SourceLocation StartLoc,
4852 SourceLocation EndLoc) {
4853 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
4854 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
4855}
4856
Alexey Bataev346265e2015-09-25 10:37:12 +00004857StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
4858 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004859 SourceLocation StartLoc,
4860 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00004861 OMPClause *DependFound = nullptr;
4862 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004863 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004864 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00004865 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004866 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00004867 for (auto *C : Clauses) {
4868 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
4869 DependFound = C;
4870 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
4871 if (DependSourceClause) {
4872 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
4873 << getOpenMPDirectiveName(OMPD_ordered)
4874 << getOpenMPClauseName(OMPC_depend) << 2;
4875 ErrorFound = true;
4876 } else
4877 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004878 if (DependSinkClause) {
4879 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4880 << 0;
4881 ErrorFound = true;
4882 }
4883 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
4884 if (DependSourceClause) {
4885 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
4886 << 1;
4887 ErrorFound = true;
4888 }
4889 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00004890 }
4891 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00004892 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004893 else if (C->getClauseKind() == OMPC_simd)
4894 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00004895 }
Alexey Bataeveb482352015-12-18 05:05:56 +00004896 if (!ErrorFound && !SC &&
4897 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004898 // OpenMP [2.8.1,simd Construct, Restrictions]
4899 // An ordered construct with the simd clause is the only OpenMP construct
4900 // that can appear in the simd region.
4901 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00004902 ErrorFound = true;
4903 } else if (DependFound && (TC || SC)) {
4904 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
4905 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
4906 ErrorFound = true;
4907 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
4908 Diag(DependFound->getLocStart(),
4909 diag::err_omp_ordered_directive_without_param);
4910 ErrorFound = true;
4911 } else if (TC || Clauses.empty()) {
4912 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
4913 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
4914 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
4915 << (TC != nullptr);
4916 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
4917 ErrorFound = true;
4918 }
4919 }
4920 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004921 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00004922
4923 if (AStmt) {
4924 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4925
4926 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004927 }
Alexey Bataev346265e2015-09-25 10:37:12 +00004928
4929 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004930}
4931
Alexey Bataev1d160b12015-03-13 12:27:31 +00004932namespace {
4933/// \brief Helper class for checking expression in 'omp atomic [update]'
4934/// construct.
4935class OpenMPAtomicUpdateChecker {
4936 /// \brief Error results for atomic update expressions.
4937 enum ExprAnalysisErrorCode {
4938 /// \brief A statement is not an expression statement.
4939 NotAnExpression,
4940 /// \brief Expression is not builtin binary or unary operation.
4941 NotABinaryOrUnaryExpression,
4942 /// \brief Unary operation is not post-/pre- increment/decrement operation.
4943 NotAnUnaryIncDecExpression,
4944 /// \brief An expression is not of scalar type.
4945 NotAScalarType,
4946 /// \brief A binary operation is not an assignment operation.
4947 NotAnAssignmentOp,
4948 /// \brief RHS part of the binary operation is not a binary expression.
4949 NotABinaryExpression,
4950 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
4951 /// expression.
4952 NotABinaryOperator,
4953 /// \brief RHS binary operation does not have reference to the updated LHS
4954 /// part.
4955 NotAnUpdateExpression,
4956 /// \brief No errors is found.
4957 NoError
4958 };
4959 /// \brief Reference to Sema.
4960 Sema &SemaRef;
4961 /// \brief A location for note diagnostics (when error is found).
4962 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004963 /// \brief 'x' lvalue part of the source atomic expression.
4964 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004965 /// \brief 'expr' rvalue part of the source atomic expression.
4966 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00004967 /// \brief Helper expression of the form
4968 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4969 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4970 Expr *UpdateExpr;
4971 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
4972 /// important for non-associative operations.
4973 bool IsXLHSInRHSPart;
4974 BinaryOperatorKind Op;
4975 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00004976 /// \brief true if the source expression is a postfix unary operation, false
4977 /// if it is a prefix unary operation.
4978 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00004979
4980public:
4981 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00004982 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00004983 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00004984 /// \brief Check specified statement that it is suitable for 'atomic update'
4985 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00004986 /// expression. If DiagId and NoteId == 0, then only check is performed
4987 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00004988 /// \param DiagId Diagnostic which should be emitted if error is found.
4989 /// \param NoteId Diagnostic note for the main error message.
4990 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00004991 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00004992 /// \brief Return the 'x' lvalue part of the source atomic expression.
4993 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00004994 /// \brief Return the 'expr' rvalue part of the source atomic expression.
4995 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00004996 /// \brief Return the update expression used in calculation of the updated
4997 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
4998 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
4999 Expr *getUpdateExpr() const { return UpdateExpr; }
5000 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5001 /// false otherwise.
5002 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5003
Alexey Bataevb78ca832015-04-01 03:33:17 +00005004 /// \brief true if the source expression is a postfix unary operation, false
5005 /// if it is a prefix unary operation.
5006 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5007
Alexey Bataev1d160b12015-03-13 12:27:31 +00005008private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005009 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5010 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005011};
5012} // namespace
5013
5014bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5015 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5016 ExprAnalysisErrorCode ErrorFound = NoError;
5017 SourceLocation ErrorLoc, NoteLoc;
5018 SourceRange ErrorRange, NoteRange;
5019 // Allowed constructs are:
5020 // x = x binop expr;
5021 // x = expr binop x;
5022 if (AtomicBinOp->getOpcode() == BO_Assign) {
5023 X = AtomicBinOp->getLHS();
5024 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5025 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5026 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5027 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5028 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005029 Op = AtomicInnerBinOp->getOpcode();
5030 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005031 auto *LHS = AtomicInnerBinOp->getLHS();
5032 auto *RHS = AtomicInnerBinOp->getRHS();
5033 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5034 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5035 /*Canonical=*/true);
5036 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5037 /*Canonical=*/true);
5038 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5039 /*Canonical=*/true);
5040 if (XId == LHSId) {
5041 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005042 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005043 } else if (XId == RHSId) {
5044 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005045 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005046 } else {
5047 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5048 ErrorRange = AtomicInnerBinOp->getSourceRange();
5049 NoteLoc = X->getExprLoc();
5050 NoteRange = X->getSourceRange();
5051 ErrorFound = NotAnUpdateExpression;
5052 }
5053 } else {
5054 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5055 ErrorRange = AtomicInnerBinOp->getSourceRange();
5056 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5057 NoteRange = SourceRange(NoteLoc, NoteLoc);
5058 ErrorFound = NotABinaryOperator;
5059 }
5060 } else {
5061 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5062 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5063 ErrorFound = NotABinaryExpression;
5064 }
5065 } else {
5066 ErrorLoc = AtomicBinOp->getExprLoc();
5067 ErrorRange = AtomicBinOp->getSourceRange();
5068 NoteLoc = AtomicBinOp->getOperatorLoc();
5069 NoteRange = SourceRange(NoteLoc, NoteLoc);
5070 ErrorFound = NotAnAssignmentOp;
5071 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005072 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005073 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5074 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5075 return true;
5076 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005077 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005078 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005079}
5080
5081bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5082 unsigned NoteId) {
5083 ExprAnalysisErrorCode ErrorFound = NoError;
5084 SourceLocation ErrorLoc, NoteLoc;
5085 SourceRange ErrorRange, NoteRange;
5086 // Allowed constructs are:
5087 // x++;
5088 // x--;
5089 // ++x;
5090 // --x;
5091 // x binop= expr;
5092 // x = x binop expr;
5093 // x = expr binop x;
5094 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5095 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5096 if (AtomicBody->getType()->isScalarType() ||
5097 AtomicBody->isInstantiationDependent()) {
5098 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5099 AtomicBody->IgnoreParenImpCasts())) {
5100 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005101 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005102 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005103 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005104 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005105 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005106 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005107 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5108 AtomicBody->IgnoreParenImpCasts())) {
5109 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005110 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005111 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005112 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5113 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005114 // Check for Unary Operation
5115 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005116 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005117 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5118 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005119 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005120 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5121 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005122 } else {
5123 ErrorFound = NotAnUnaryIncDecExpression;
5124 ErrorLoc = AtomicUnaryOp->getExprLoc();
5125 ErrorRange = AtomicUnaryOp->getSourceRange();
5126 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5127 NoteRange = SourceRange(NoteLoc, NoteLoc);
5128 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005129 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005130 ErrorFound = NotABinaryOrUnaryExpression;
5131 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5132 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5133 }
5134 } else {
5135 ErrorFound = NotAScalarType;
5136 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5137 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5138 }
5139 } else {
5140 ErrorFound = NotAnExpression;
5141 NoteLoc = ErrorLoc = S->getLocStart();
5142 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5143 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005144 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005145 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5146 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5147 return true;
5148 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005149 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005150 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005151 // Build an update expression of form 'OpaqueValueExpr(x) binop
5152 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5153 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5154 auto *OVEX = new (SemaRef.getASTContext())
5155 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5156 auto *OVEExpr = new (SemaRef.getASTContext())
5157 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5158 auto Update =
5159 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5160 IsXLHSInRHSPart ? OVEExpr : OVEX);
5161 if (Update.isInvalid())
5162 return true;
5163 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5164 Sema::AA_Casting);
5165 if (Update.isInvalid())
5166 return true;
5167 UpdateExpr = Update.get();
5168 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005169 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005170}
5171
Alexey Bataev0162e452014-07-22 10:10:35 +00005172StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5173 Stmt *AStmt,
5174 SourceLocation StartLoc,
5175 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005176 if (!AStmt)
5177 return StmtError();
5178
David Majnemer9d168222016-08-05 17:44:54 +00005179 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005180 // 1.2.2 OpenMP Language Terminology
5181 // Structured block - An executable statement with a single entry at the
5182 // top and a single exit at the bottom.
5183 // The point of exit cannot be a branch out of the structured block.
5184 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005185 OpenMPClauseKind AtomicKind = OMPC_unknown;
5186 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005187 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005188 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005189 C->getClauseKind() == OMPC_update ||
5190 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005191 if (AtomicKind != OMPC_unknown) {
5192 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5193 << SourceRange(C->getLocStart(), C->getLocEnd());
5194 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5195 << getOpenMPClauseName(AtomicKind);
5196 } else {
5197 AtomicKind = C->getClauseKind();
5198 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005199 }
5200 }
5201 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005202
Alexey Bataev459dec02014-07-24 06:46:57 +00005203 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005204 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
5205 Body = EWC->getSubExpr();
5206
Alexey Bataev62cec442014-11-18 10:14:22 +00005207 Expr *X = nullptr;
5208 Expr *V = nullptr;
5209 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005210 Expr *UE = nullptr;
5211 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005212 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00005213 // OpenMP [2.12.6, atomic Construct]
5214 // In the next expressions:
5215 // * x and v (as applicable) are both l-value expressions with scalar type.
5216 // * During the execution of an atomic region, multiple syntactic
5217 // occurrences of x must designate the same storage location.
5218 // * Neither of v and expr (as applicable) may access the storage location
5219 // designated by x.
5220 // * Neither of x and expr (as applicable) may access the storage location
5221 // designated by v.
5222 // * expr is an expression with scalar type.
5223 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
5224 // * binop, binop=, ++, and -- are not overloaded operators.
5225 // * The expression x binop expr must be numerically equivalent to x binop
5226 // (expr). This requirement is satisfied if the operators in expr have
5227 // precedence greater than binop, or by using parentheses around expr or
5228 // subexpressions of expr.
5229 // * The expression expr binop x must be numerically equivalent to (expr)
5230 // binop x. This requirement is satisfied if the operators in expr have
5231 // precedence equal to or greater than binop, or by using parentheses around
5232 // expr or subexpressions of expr.
5233 // * For forms that allow multiple occurrences of x, the number of times
5234 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00005235 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005236 enum {
5237 NotAnExpression,
5238 NotAnAssignmentOp,
5239 NotAScalarType,
5240 NotAnLValue,
5241 NoError
5242 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00005243 SourceLocation ErrorLoc, NoteLoc;
5244 SourceRange ErrorRange, NoteRange;
5245 // If clause is read:
5246 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00005247 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5248 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00005249 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5250 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5251 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5252 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
5253 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5254 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
5255 if (!X->isLValue() || !V->isLValue()) {
5256 auto NotLValueExpr = X->isLValue() ? V : X;
5257 ErrorFound = NotAnLValue;
5258 ErrorLoc = AtomicBinOp->getExprLoc();
5259 ErrorRange = AtomicBinOp->getSourceRange();
5260 NoteLoc = NotLValueExpr->getExprLoc();
5261 NoteRange = NotLValueExpr->getSourceRange();
5262 }
5263 } else if (!X->isInstantiationDependent() ||
5264 !V->isInstantiationDependent()) {
5265 auto NotScalarExpr =
5266 (X->isInstantiationDependent() || X->getType()->isScalarType())
5267 ? V
5268 : X;
5269 ErrorFound = NotAScalarType;
5270 ErrorLoc = AtomicBinOp->getExprLoc();
5271 ErrorRange = AtomicBinOp->getSourceRange();
5272 NoteLoc = NotScalarExpr->getExprLoc();
5273 NoteRange = NotScalarExpr->getSourceRange();
5274 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005275 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00005276 ErrorFound = NotAnAssignmentOp;
5277 ErrorLoc = AtomicBody->getExprLoc();
5278 ErrorRange = AtomicBody->getSourceRange();
5279 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5280 : AtomicBody->getExprLoc();
5281 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5282 : AtomicBody->getSourceRange();
5283 }
5284 } else {
5285 ErrorFound = NotAnExpression;
5286 NoteLoc = ErrorLoc = Body->getLocStart();
5287 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005288 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005289 if (ErrorFound != NoError) {
5290 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
5291 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005292 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5293 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00005294 return StmtError();
5295 } else if (CurContext->isDependentContext())
5296 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00005297 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005298 enum {
5299 NotAnExpression,
5300 NotAnAssignmentOp,
5301 NotAScalarType,
5302 NotAnLValue,
5303 NoError
5304 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00005305 SourceLocation ErrorLoc, NoteLoc;
5306 SourceRange ErrorRange, NoteRange;
5307 // If clause is write:
5308 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00005309 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5310 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00005311 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5312 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00005313 X = AtomicBinOp->getLHS();
5314 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00005315 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
5316 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
5317 if (!X->isLValue()) {
5318 ErrorFound = NotAnLValue;
5319 ErrorLoc = AtomicBinOp->getExprLoc();
5320 ErrorRange = AtomicBinOp->getSourceRange();
5321 NoteLoc = X->getExprLoc();
5322 NoteRange = X->getSourceRange();
5323 }
5324 } else if (!X->isInstantiationDependent() ||
5325 !E->isInstantiationDependent()) {
5326 auto NotScalarExpr =
5327 (X->isInstantiationDependent() || X->getType()->isScalarType())
5328 ? E
5329 : X;
5330 ErrorFound = NotAScalarType;
5331 ErrorLoc = AtomicBinOp->getExprLoc();
5332 ErrorRange = AtomicBinOp->getSourceRange();
5333 NoteLoc = NotScalarExpr->getExprLoc();
5334 NoteRange = NotScalarExpr->getSourceRange();
5335 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005336 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00005337 ErrorFound = NotAnAssignmentOp;
5338 ErrorLoc = AtomicBody->getExprLoc();
5339 ErrorRange = AtomicBody->getSourceRange();
5340 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5341 : AtomicBody->getExprLoc();
5342 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5343 : AtomicBody->getSourceRange();
5344 }
5345 } else {
5346 ErrorFound = NotAnExpression;
5347 NoteLoc = ErrorLoc = Body->getLocStart();
5348 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00005349 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00005350 if (ErrorFound != NoError) {
5351 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
5352 << ErrorRange;
5353 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
5354 << NoteRange;
5355 return StmtError();
5356 } else if (CurContext->isDependentContext())
5357 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00005358 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005359 // If clause is update:
5360 // x++;
5361 // x--;
5362 // ++x;
5363 // --x;
5364 // x binop= expr;
5365 // x = x binop expr;
5366 // x = expr binop x;
5367 OpenMPAtomicUpdateChecker Checker(*this);
5368 if (Checker.checkStatement(
5369 Body, (AtomicKind == OMPC_update)
5370 ? diag::err_omp_atomic_update_not_expression_statement
5371 : diag::err_omp_atomic_not_expression_statement,
5372 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00005373 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005374 if (!CurContext->isDependentContext()) {
5375 E = Checker.getExpr();
5376 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005377 UE = Checker.getUpdateExpr();
5378 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00005379 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005380 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005381 enum {
5382 NotAnAssignmentOp,
5383 NotACompoundStatement,
5384 NotTwoSubstatements,
5385 NotASpecificExpression,
5386 NoError
5387 } ErrorFound = NoError;
5388 SourceLocation ErrorLoc, NoteLoc;
5389 SourceRange ErrorRange, NoteRange;
5390 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
5391 // If clause is a capture:
5392 // v = x++;
5393 // v = x--;
5394 // v = ++x;
5395 // v = --x;
5396 // v = x binop= expr;
5397 // v = x = x binop expr;
5398 // v = x = expr binop x;
5399 auto *AtomicBinOp =
5400 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
5401 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
5402 V = AtomicBinOp->getLHS();
5403 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
5404 OpenMPAtomicUpdateChecker Checker(*this);
5405 if (Checker.checkStatement(
5406 Body, diag::err_omp_atomic_capture_not_expression_statement,
5407 diag::note_omp_atomic_update))
5408 return StmtError();
5409 E = Checker.getExpr();
5410 X = Checker.getX();
5411 UE = Checker.getUpdateExpr();
5412 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
5413 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00005414 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005415 ErrorLoc = AtomicBody->getExprLoc();
5416 ErrorRange = AtomicBody->getSourceRange();
5417 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
5418 : AtomicBody->getExprLoc();
5419 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
5420 : AtomicBody->getSourceRange();
5421 ErrorFound = NotAnAssignmentOp;
5422 }
5423 if (ErrorFound != NoError) {
5424 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
5425 << ErrorRange;
5426 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5427 return StmtError();
5428 } else if (CurContext->isDependentContext()) {
5429 UE = V = E = X = nullptr;
5430 }
5431 } else {
5432 // If clause is a capture:
5433 // { v = x; x = expr; }
5434 // { v = x; x++; }
5435 // { v = x; x--; }
5436 // { v = x; ++x; }
5437 // { v = x; --x; }
5438 // { v = x; x binop= expr; }
5439 // { v = x; x = x binop expr; }
5440 // { v = x; x = expr binop x; }
5441 // { x++; v = x; }
5442 // { x--; v = x; }
5443 // { ++x; v = x; }
5444 // { --x; v = x; }
5445 // { x binop= expr; v = x; }
5446 // { x = x binop expr; v = x; }
5447 // { x = expr binop x; v = x; }
5448 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
5449 // Check that this is { expr1; expr2; }
5450 if (CS->size() == 2) {
5451 auto *First = CS->body_front();
5452 auto *Second = CS->body_back();
5453 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
5454 First = EWC->getSubExpr()->IgnoreParenImpCasts();
5455 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
5456 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
5457 // Need to find what subexpression is 'v' and what is 'x'.
5458 OpenMPAtomicUpdateChecker Checker(*this);
5459 bool IsUpdateExprFound = !Checker.checkStatement(Second);
5460 BinaryOperator *BinOp = nullptr;
5461 if (IsUpdateExprFound) {
5462 BinOp = dyn_cast<BinaryOperator>(First);
5463 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5464 }
5465 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5466 // { v = x; x++; }
5467 // { v = x; x--; }
5468 // { v = x; ++x; }
5469 // { v = x; --x; }
5470 // { v = x; x binop= expr; }
5471 // { v = x; x = x binop expr; }
5472 // { v = x; x = expr binop x; }
5473 // Check that the first expression has form v = x.
5474 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5475 llvm::FoldingSetNodeID XId, PossibleXId;
5476 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5477 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5478 IsUpdateExprFound = XId == PossibleXId;
5479 if (IsUpdateExprFound) {
5480 V = BinOp->getLHS();
5481 X = Checker.getX();
5482 E = Checker.getExpr();
5483 UE = Checker.getUpdateExpr();
5484 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005485 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005486 }
5487 }
5488 if (!IsUpdateExprFound) {
5489 IsUpdateExprFound = !Checker.checkStatement(First);
5490 BinOp = nullptr;
5491 if (IsUpdateExprFound) {
5492 BinOp = dyn_cast<BinaryOperator>(Second);
5493 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
5494 }
5495 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
5496 // { x++; v = x; }
5497 // { x--; v = x; }
5498 // { ++x; v = x; }
5499 // { --x; v = x; }
5500 // { x binop= expr; v = x; }
5501 // { x = x binop expr; v = x; }
5502 // { x = expr binop x; v = x; }
5503 // Check that the second expression has form v = x.
5504 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
5505 llvm::FoldingSetNodeID XId, PossibleXId;
5506 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
5507 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
5508 IsUpdateExprFound = XId == PossibleXId;
5509 if (IsUpdateExprFound) {
5510 V = BinOp->getLHS();
5511 X = Checker.getX();
5512 E = Checker.getExpr();
5513 UE = Checker.getUpdateExpr();
5514 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00005515 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005516 }
5517 }
5518 }
5519 if (!IsUpdateExprFound) {
5520 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00005521 auto *FirstExpr = dyn_cast<Expr>(First);
5522 auto *SecondExpr = dyn_cast<Expr>(Second);
5523 if (!FirstExpr || !SecondExpr ||
5524 !(FirstExpr->isInstantiationDependent() ||
5525 SecondExpr->isInstantiationDependent())) {
5526 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
5527 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005528 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00005529 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
5530 : First->getLocStart();
5531 NoteRange = ErrorRange = FirstBinOp
5532 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00005533 : SourceRange(ErrorLoc, ErrorLoc);
5534 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005535 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
5536 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
5537 ErrorFound = NotAnAssignmentOp;
5538 NoteLoc = ErrorLoc = SecondBinOp
5539 ? SecondBinOp->getOperatorLoc()
5540 : Second->getLocStart();
5541 NoteRange = ErrorRange =
5542 SecondBinOp ? SecondBinOp->getSourceRange()
5543 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00005544 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00005545 auto *PossibleXRHSInFirst =
5546 FirstBinOp->getRHS()->IgnoreParenImpCasts();
5547 auto *PossibleXLHSInSecond =
5548 SecondBinOp->getLHS()->IgnoreParenImpCasts();
5549 llvm::FoldingSetNodeID X1Id, X2Id;
5550 PossibleXRHSInFirst->Profile(X1Id, Context,
5551 /*Canonical=*/true);
5552 PossibleXLHSInSecond->Profile(X2Id, Context,
5553 /*Canonical=*/true);
5554 IsUpdateExprFound = X1Id == X2Id;
5555 if (IsUpdateExprFound) {
5556 V = FirstBinOp->getLHS();
5557 X = SecondBinOp->getLHS();
5558 E = SecondBinOp->getRHS();
5559 UE = nullptr;
5560 IsXLHSInRHSPart = false;
5561 IsPostfixUpdate = true;
5562 } else {
5563 ErrorFound = NotASpecificExpression;
5564 ErrorLoc = FirstBinOp->getExprLoc();
5565 ErrorRange = FirstBinOp->getSourceRange();
5566 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
5567 NoteRange = SecondBinOp->getRHS()->getSourceRange();
5568 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005569 }
5570 }
5571 }
5572 }
5573 } else {
5574 NoteLoc = ErrorLoc = Body->getLocStart();
5575 NoteRange = ErrorRange =
5576 SourceRange(Body->getLocStart(), Body->getLocStart());
5577 ErrorFound = NotTwoSubstatements;
5578 }
5579 } else {
5580 NoteLoc = ErrorLoc = Body->getLocStart();
5581 NoteRange = ErrorRange =
5582 SourceRange(Body->getLocStart(), Body->getLocStart());
5583 ErrorFound = NotACompoundStatement;
5584 }
5585 if (ErrorFound != NoError) {
5586 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
5587 << ErrorRange;
5588 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
5589 return StmtError();
5590 } else if (CurContext->isDependentContext()) {
5591 UE = V = E = X = nullptr;
5592 }
Alexey Bataev459dec02014-07-24 06:46:57 +00005593 }
Alexey Bataevdea47612014-07-23 07:46:59 +00005594 }
Alexey Bataev0162e452014-07-22 10:10:35 +00005595
5596 getCurFunction()->setHasBranchProtectedScope();
5597
Alexey Bataev62cec442014-11-18 10:14:22 +00005598 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00005599 X, V, E, UE, IsXLHSInRHSPart,
5600 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00005601}
5602
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005603StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
5604 Stmt *AStmt,
5605 SourceLocation StartLoc,
5606 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005607 if (!AStmt)
5608 return StmtError();
5609
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005610 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5611 // 1.2.2 OpenMP Language Terminology
5612 // Structured block - An executable statement with a single entry at the
5613 // top and a single exit at the bottom.
5614 // The point of exit cannot be a branch out of the structured block.
5615 // longjmp() and throw() must not violate the entry/exit criteria.
5616 CS->getCapturedDecl()->setNothrow();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005617
Alexey Bataev13314bf2014-10-09 04:18:56 +00005618 // OpenMP [2.16, Nesting of Regions]
5619 // If specified, a teams construct must be contained within a target
5620 // construct. That target construct must contain no statements or directives
5621 // outside of the teams construct.
5622 if (DSAStack->hasInnerTeamsRegion()) {
5623 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
5624 bool OMPTeamsFound = true;
5625 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
5626 auto I = CS->body_begin();
5627 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00005628 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00005629 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
5630 OMPTeamsFound = false;
5631 break;
5632 }
5633 ++I;
5634 }
5635 assert(I != CS->body_end() && "Not found statement");
5636 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00005637 } else {
5638 auto *OED = dyn_cast<OMPExecutableDirective>(S);
5639 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00005640 }
5641 if (!OMPTeamsFound) {
5642 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
5643 Diag(DSAStack->getInnerTeamsRegionLoc(),
5644 diag::note_omp_nested_teams_construct_here);
5645 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
5646 << isa<OMPExecutableDirective>(S);
5647 return StmtError();
5648 }
5649 }
5650
Alexey Bataev0bd520b2014-09-19 08:19:49 +00005651 getCurFunction()->setHasBranchProtectedScope();
5652
5653 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5654}
5655
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00005656StmtResult
5657Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
5658 Stmt *AStmt, SourceLocation StartLoc,
5659 SourceLocation EndLoc) {
5660 if (!AStmt)
5661 return StmtError();
5662
5663 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5664 // 1.2.2 OpenMP Language Terminology
5665 // Structured block - An executable statement with a single entry at the
5666 // top and a single exit at the bottom.
5667 // The point of exit cannot be a branch out of the structured block.
5668 // longjmp() and throw() must not violate the entry/exit criteria.
5669 CS->getCapturedDecl()->setNothrow();
5670
5671 getCurFunction()->setHasBranchProtectedScope();
5672
5673 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5674 AStmt);
5675}
5676
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005677StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
5678 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5679 SourceLocation EndLoc,
5680 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5681 if (!AStmt)
5682 return StmtError();
5683
5684 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5685 // 1.2.2 OpenMP Language Terminology
5686 // Structured block - An executable statement with a single entry at the
5687 // top and a single exit at the bottom.
5688 // The point of exit cannot be a branch out of the structured block.
5689 // longjmp() and throw() must not violate the entry/exit criteria.
5690 CS->getCapturedDecl()->setNothrow();
5691
5692 OMPLoopDirective::HelperExprs B;
5693 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5694 // define the nested loops number.
5695 unsigned NestedLoopCount =
5696 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
5697 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5698 VarsWithImplicitDSA, B);
5699 if (NestedLoopCount == 0)
5700 return StmtError();
5701
5702 assert((CurContext->isDependentContext() || B.builtAll()) &&
5703 "omp target parallel for loop exprs were not built");
5704
5705 if (!CurContext->isDependentContext()) {
5706 // Finalize the clauses that need pre-built expressions for CodeGen.
5707 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005708 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005709 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005710 B.NumIterations, *this, CurScope,
5711 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00005712 return StmtError();
5713 }
5714 }
5715
5716 getCurFunction()->setHasBranchProtectedScope();
5717 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
5718 NestedLoopCount, Clauses, AStmt,
5719 B, DSAStack->isCancelRegion());
5720}
5721
Samuel Antaodf67fc42016-01-19 19:15:56 +00005722/// \brief Check for existence of a map clause in the list of clauses.
5723static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
5724 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
5725 I != E; ++I) {
5726 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
5727 return true;
5728 }
5729 }
5730
5731 return false;
5732}
5733
Michael Wong65f367f2015-07-21 13:44:28 +00005734StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
5735 Stmt *AStmt,
5736 SourceLocation StartLoc,
5737 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005738 if (!AStmt)
5739 return StmtError();
5740
5741 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5742
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005743 // OpenMP [2.10.1, Restrictions, p. 97]
5744 // At least one map clause must appear on the directive.
5745 if (!HasMapClause(Clauses)) {
David Majnemer9d168222016-08-05 17:44:54 +00005746 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5747 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00005748 return StmtError();
5749 }
5750
Michael Wong65f367f2015-07-21 13:44:28 +00005751 getCurFunction()->setHasBranchProtectedScope();
5752
5753 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
5754 AStmt);
5755}
5756
Samuel Antaodf67fc42016-01-19 19:15:56 +00005757StmtResult
5758Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
5759 SourceLocation StartLoc,
5760 SourceLocation EndLoc) {
5761 // OpenMP [2.10.2, Restrictions, p. 99]
5762 // At least one map clause must appear on the directive.
5763 if (!HasMapClause(Clauses)) {
5764 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5765 << getOpenMPDirectiveName(OMPD_target_enter_data);
5766 return StmtError();
5767 }
5768
5769 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
5770 Clauses);
5771}
5772
Samuel Antao72590762016-01-19 20:04:50 +00005773StmtResult
5774Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
5775 SourceLocation StartLoc,
5776 SourceLocation EndLoc) {
5777 // OpenMP [2.10.3, Restrictions, p. 102]
5778 // At least one map clause must appear on the directive.
5779 if (!HasMapClause(Clauses)) {
5780 Diag(StartLoc, diag::err_omp_no_map_for_directive)
5781 << getOpenMPDirectiveName(OMPD_target_exit_data);
5782 return StmtError();
5783 }
5784
5785 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
5786}
5787
Samuel Antao686c70c2016-05-26 17:30:50 +00005788StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
5789 SourceLocation StartLoc,
5790 SourceLocation EndLoc) {
Samuel Antao686c70c2016-05-26 17:30:50 +00005791 bool seenMotionClause = false;
Samuel Antao661c0902016-05-26 17:39:58 +00005792 for (auto *C : Clauses) {
Samuel Antaoec172c62016-05-26 17:49:04 +00005793 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from)
Samuel Antao661c0902016-05-26 17:39:58 +00005794 seenMotionClause = true;
5795 }
Samuel Antao686c70c2016-05-26 17:30:50 +00005796 if (!seenMotionClause) {
5797 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
5798 return StmtError();
5799 }
5800 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses);
5801}
5802
Alexey Bataev13314bf2014-10-09 04:18:56 +00005803StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
5804 Stmt *AStmt, SourceLocation StartLoc,
5805 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005806 if (!AStmt)
5807 return StmtError();
5808
Alexey Bataev13314bf2014-10-09 04:18:56 +00005809 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5810 // 1.2.2 OpenMP Language Terminology
5811 // Structured block - An executable statement with a single entry at the
5812 // top and a single exit at the bottom.
5813 // The point of exit cannot be a branch out of the structured block.
5814 // longjmp() and throw() must not violate the entry/exit criteria.
5815 CS->getCapturedDecl()->setNothrow();
5816
5817 getCurFunction()->setHasBranchProtectedScope();
5818
5819 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5820}
5821
Alexey Bataev6d4ed052015-07-01 06:57:41 +00005822StmtResult
5823Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
5824 SourceLocation EndLoc,
5825 OpenMPDirectiveKind CancelRegion) {
5826 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5827 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5828 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5829 << getOpenMPDirectiveName(CancelRegion);
5830 return StmtError();
5831 }
5832 if (DSAStack->isParentNowaitRegion()) {
5833 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
5834 return StmtError();
5835 }
5836 if (DSAStack->isParentOrderedRegion()) {
5837 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
5838 return StmtError();
5839 }
5840 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
5841 CancelRegion);
5842}
5843
Alexey Bataev87933c72015-09-18 08:07:34 +00005844StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
5845 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00005846 SourceLocation EndLoc,
5847 OpenMPDirectiveKind CancelRegion) {
5848 if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
5849 CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
5850 Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5851 << getOpenMPDirectiveName(CancelRegion);
5852 return StmtError();
5853 }
5854 if (DSAStack->isParentNowaitRegion()) {
5855 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
5856 return StmtError();
5857 }
5858 if (DSAStack->isParentOrderedRegion()) {
5859 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
5860 return StmtError();
5861 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005862 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00005863 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
5864 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00005865}
5866
Alexey Bataev382967a2015-12-08 12:06:20 +00005867static bool checkGrainsizeNumTasksClauses(Sema &S,
5868 ArrayRef<OMPClause *> Clauses) {
5869 OMPClause *PrevClause = nullptr;
5870 bool ErrorFound = false;
5871 for (auto *C : Clauses) {
5872 if (C->getClauseKind() == OMPC_grainsize ||
5873 C->getClauseKind() == OMPC_num_tasks) {
5874 if (!PrevClause)
5875 PrevClause = C;
5876 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
5877 S.Diag(C->getLocStart(),
5878 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
5879 << getOpenMPClauseName(C->getClauseKind())
5880 << getOpenMPClauseName(PrevClause->getClauseKind());
5881 S.Diag(PrevClause->getLocStart(),
5882 diag::note_omp_previous_grainsize_num_tasks)
5883 << getOpenMPClauseName(PrevClause->getClauseKind());
5884 ErrorFound = true;
5885 }
5886 }
5887 }
5888 return ErrorFound;
5889}
5890
Alexey Bataev49f6e782015-12-01 04:18:41 +00005891StmtResult Sema::ActOnOpenMPTaskLoopDirective(
5892 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5893 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005894 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00005895 if (!AStmt)
5896 return StmtError();
5897
5898 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5899 OMPLoopDirective::HelperExprs B;
5900 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5901 // define the nested loops number.
5902 unsigned NestedLoopCount =
5903 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005904 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00005905 VarsWithImplicitDSA, B);
5906 if (NestedLoopCount == 0)
5907 return StmtError();
5908
5909 assert((CurContext->isDependentContext() || B.builtAll()) &&
5910 "omp for loop exprs were not built");
5911
Alexey Bataev382967a2015-12-08 12:06:20 +00005912 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5913 // The grainsize clause and num_tasks clause are mutually exclusive and may
5914 // not appear on the same taskloop directive.
5915 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5916 return StmtError();
5917
Alexey Bataev49f6e782015-12-01 04:18:41 +00005918 getCurFunction()->setHasBranchProtectedScope();
5919 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
5920 NestedLoopCount, Clauses, AStmt, B);
5921}
5922
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005923StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
5924 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5925 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005926 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005927 if (!AStmt)
5928 return StmtError();
5929
5930 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5931 OMPLoopDirective::HelperExprs B;
5932 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5933 // define the nested loops number.
5934 unsigned NestedLoopCount =
5935 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
5936 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
5937 VarsWithImplicitDSA, B);
5938 if (NestedLoopCount == 0)
5939 return StmtError();
5940
5941 assert((CurContext->isDependentContext() || B.builtAll()) &&
5942 "omp for loop exprs were not built");
5943
Alexey Bataev5a3af132016-03-29 08:58:54 +00005944 if (!CurContext->isDependentContext()) {
5945 // Finalize the clauses that need pre-built expressions for CodeGen.
5946 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005947 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005948 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005949 B.NumIterations, *this, CurScope,
5950 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00005951 return StmtError();
5952 }
5953 }
5954
Alexey Bataev382967a2015-12-08 12:06:20 +00005955 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
5956 // The grainsize clause and num_tasks clause are mutually exclusive and may
5957 // not appear on the same taskloop directive.
5958 if (checkGrainsizeNumTasksClauses(*this, Clauses))
5959 return StmtError();
5960
Alexey Bataev0a6ed842015-12-03 09:40:15 +00005961 getCurFunction()->setHasBranchProtectedScope();
5962 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
5963 NestedLoopCount, Clauses, AStmt, B);
5964}
5965
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005966StmtResult Sema::ActOnOpenMPDistributeDirective(
5967 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5968 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005969 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005970 if (!AStmt)
5971 return StmtError();
5972
5973 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5974 OMPLoopDirective::HelperExprs B;
5975 // In presence of clause 'collapse' with number of loops, it will
5976 // define the nested loops number.
5977 unsigned NestedLoopCount =
5978 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
5979 nullptr /*ordered not a clause on distribute*/, AStmt,
5980 *this, *DSAStack, VarsWithImplicitDSA, B);
5981 if (NestedLoopCount == 0)
5982 return StmtError();
5983
5984 assert((CurContext->isDependentContext() || B.builtAll()) &&
5985 "omp for loop exprs were not built");
5986
5987 getCurFunction()->setHasBranchProtectedScope();
5988 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
5989 NestedLoopCount, Clauses, AStmt, B);
5990}
5991
Carlo Bertolli9925f152016-06-27 14:55:37 +00005992StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
5993 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5994 SourceLocation EndLoc,
5995 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
5996 if (!AStmt)
5997 return StmtError();
5998
5999 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6000 // 1.2.2 OpenMP Language Terminology
6001 // Structured block - An executable statement with a single entry at the
6002 // top and a single exit at the bottom.
6003 // The point of exit cannot be a branch out of the structured block.
6004 // longjmp() and throw() must not violate the entry/exit criteria.
6005 CS->getCapturedDecl()->setNothrow();
6006
6007 OMPLoopDirective::HelperExprs B;
6008 // In presence of clause 'collapse' with number of loops, it will
6009 // define the nested loops number.
6010 unsigned NestedLoopCount = CheckOpenMPLoop(
6011 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6012 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6013 VarsWithImplicitDSA, B);
6014 if (NestedLoopCount == 0)
6015 return StmtError();
6016
6017 assert((CurContext->isDependentContext() || B.builtAll()) &&
6018 "omp for loop exprs were not built");
6019
6020 getCurFunction()->setHasBranchProtectedScope();
6021 return OMPDistributeParallelForDirective::Create(
6022 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6023}
6024
Kelvin Li4a39add2016-07-05 05:00:15 +00006025StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6026 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6027 SourceLocation EndLoc,
6028 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6029 if (!AStmt)
6030 return StmtError();
6031
6032 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6033 // 1.2.2 OpenMP Language Terminology
6034 // Structured block - An executable statement with a single entry at the
6035 // top and a single exit at the bottom.
6036 // The point of exit cannot be a branch out of the structured block.
6037 // longjmp() and throw() must not violate the entry/exit criteria.
6038 CS->getCapturedDecl()->setNothrow();
6039
6040 OMPLoopDirective::HelperExprs B;
6041 // In presence of clause 'collapse' with number of loops, it will
6042 // define the nested loops number.
6043 unsigned NestedLoopCount = CheckOpenMPLoop(
6044 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6045 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6046 VarsWithImplicitDSA, B);
6047 if (NestedLoopCount == 0)
6048 return StmtError();
6049
6050 assert((CurContext->isDependentContext() || B.builtAll()) &&
6051 "omp for loop exprs were not built");
6052
Kelvin Lic5609492016-07-15 04:39:07 +00006053 if (checkSimdlenSafelenSpecified(*this, Clauses))
6054 return StmtError();
6055
Kelvin Li4a39add2016-07-05 05:00:15 +00006056 getCurFunction()->setHasBranchProtectedScope();
6057 return OMPDistributeParallelForSimdDirective::Create(
6058 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6059}
6060
Kelvin Li787f3fc2016-07-06 04:45:38 +00006061StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
6062 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6063 SourceLocation EndLoc,
6064 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6065 if (!AStmt)
6066 return StmtError();
6067
6068 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6069 // 1.2.2 OpenMP Language Terminology
6070 // Structured block - An executable statement with a single entry at the
6071 // top and a single exit at the bottom.
6072 // The point of exit cannot be a branch out of the structured block.
6073 // longjmp() and throw() must not violate the entry/exit criteria.
6074 CS->getCapturedDecl()->setNothrow();
6075
6076 OMPLoopDirective::HelperExprs B;
6077 // In presence of clause 'collapse' with number of loops, it will
6078 // define the nested loops number.
6079 unsigned NestedLoopCount =
6080 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
6081 nullptr /*ordered not a clause on distribute*/, AStmt,
6082 *this, *DSAStack, VarsWithImplicitDSA, B);
6083 if (NestedLoopCount == 0)
6084 return StmtError();
6085
6086 assert((CurContext->isDependentContext() || B.builtAll()) &&
6087 "omp for loop exprs were not built");
6088
Kelvin Lic5609492016-07-15 04:39:07 +00006089 if (checkSimdlenSafelenSpecified(*this, Clauses))
6090 return StmtError();
6091
Kelvin Li787f3fc2016-07-06 04:45:38 +00006092 getCurFunction()->setHasBranchProtectedScope();
6093 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
6094 NestedLoopCount, Clauses, AStmt, B);
6095}
6096
Kelvin Lia579b912016-07-14 02:54:56 +00006097StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
6098 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6099 SourceLocation EndLoc,
6100 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6101 if (!AStmt)
6102 return StmtError();
6103
6104 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6105 // 1.2.2 OpenMP Language Terminology
6106 // Structured block - An executable statement with a single entry at the
6107 // top and a single exit at the bottom.
6108 // The point of exit cannot be a branch out of the structured block.
6109 // longjmp() and throw() must not violate the entry/exit criteria.
6110 CS->getCapturedDecl()->setNothrow();
6111
6112 OMPLoopDirective::HelperExprs B;
6113 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6114 // define the nested loops number.
6115 unsigned NestedLoopCount = CheckOpenMPLoop(
6116 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
6117 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6118 VarsWithImplicitDSA, B);
6119 if (NestedLoopCount == 0)
6120 return StmtError();
6121
6122 assert((CurContext->isDependentContext() || B.builtAll()) &&
6123 "omp target parallel for simd loop exprs were not built");
6124
6125 if (!CurContext->isDependentContext()) {
6126 // Finalize the clauses that need pre-built expressions for CodeGen.
6127 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006128 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00006129 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6130 B.NumIterations, *this, CurScope,
6131 DSAStack))
6132 return StmtError();
6133 }
6134 }
Kelvin Lic5609492016-07-15 04:39:07 +00006135 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00006136 return StmtError();
6137
6138 getCurFunction()->setHasBranchProtectedScope();
6139 return OMPTargetParallelForSimdDirective::Create(
6140 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6141}
6142
Kelvin Li986330c2016-07-20 22:57:10 +00006143StmtResult Sema::ActOnOpenMPTargetSimdDirective(
6144 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6145 SourceLocation EndLoc,
6146 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6147 if (!AStmt)
6148 return StmtError();
6149
6150 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6151 // 1.2.2 OpenMP Language Terminology
6152 // Structured block - An executable statement with a single entry at the
6153 // top and a single exit at the bottom.
6154 // The point of exit cannot be a branch out of the structured block.
6155 // longjmp() and throw() must not violate the entry/exit criteria.
6156 CS->getCapturedDecl()->setNothrow();
6157
6158 OMPLoopDirective::HelperExprs B;
6159 // In presence of clause 'collapse' with number of loops, it will define the
6160 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00006161 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00006162 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
6163 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6164 VarsWithImplicitDSA, B);
6165 if (NestedLoopCount == 0)
6166 return StmtError();
6167
6168 assert((CurContext->isDependentContext() || B.builtAll()) &&
6169 "omp target simd loop exprs were not built");
6170
6171 if (!CurContext->isDependentContext()) {
6172 // Finalize the clauses that need pre-built expressions for CodeGen.
6173 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006174 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00006175 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6176 B.NumIterations, *this, CurScope,
6177 DSAStack))
6178 return StmtError();
6179 }
6180 }
6181
6182 if (checkSimdlenSafelenSpecified(*this, Clauses))
6183 return StmtError();
6184
6185 getCurFunction()->setHasBranchProtectedScope();
6186 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
6187 NestedLoopCount, Clauses, AStmt, B);
6188}
6189
Kelvin Li02532872016-08-05 14:37:37 +00006190StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
6191 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6192 SourceLocation EndLoc,
6193 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6194 if (!AStmt)
6195 return StmtError();
6196
6197 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6198 // 1.2.2 OpenMP Language Terminology
6199 // Structured block - An executable statement with a single entry at the
6200 // top and a single exit at the bottom.
6201 // The point of exit cannot be a branch out of the structured block.
6202 // longjmp() and throw() must not violate the entry/exit criteria.
6203 CS->getCapturedDecl()->setNothrow();
6204
6205 OMPLoopDirective::HelperExprs B;
6206 // In presence of clause 'collapse' with number of loops, it will
6207 // define the nested loops number.
6208 unsigned NestedLoopCount =
6209 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
6210 nullptr /*ordered not a clause on distribute*/, AStmt,
6211 *this, *DSAStack, VarsWithImplicitDSA, B);
6212 if (NestedLoopCount == 0)
6213 return StmtError();
6214
6215 assert((CurContext->isDependentContext() || B.builtAll()) &&
6216 "omp teams distribute loop exprs were not built");
6217
6218 getCurFunction()->setHasBranchProtectedScope();
David Majnemer9d168222016-08-05 17:44:54 +00006219 return OMPTeamsDistributeDirective::Create(
6220 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00006221}
6222
Kelvin Li4e325f72016-10-25 12:50:55 +00006223StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
6224 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6225 SourceLocation EndLoc,
6226 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6227 if (!AStmt)
6228 return StmtError();
6229
6230 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6231 // 1.2.2 OpenMP Language Terminology
6232 // Structured block - An executable statement with a single entry at the
6233 // top and a single exit at the bottom.
6234 // The point of exit cannot be a branch out of the structured block.
6235 // longjmp() and throw() must not violate the entry/exit criteria.
6236 CS->getCapturedDecl()->setNothrow();
6237
6238 OMPLoopDirective::HelperExprs B;
6239 // In presence of clause 'collapse' with number of loops, it will
6240 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00006241 unsigned NestedLoopCount = CheckOpenMPLoop(
6242 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6243 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6244 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00006245
6246 if (NestedLoopCount == 0)
6247 return StmtError();
6248
6249 assert((CurContext->isDependentContext() || B.builtAll()) &&
6250 "omp teams distribute simd loop exprs were not built");
6251
6252 if (!CurContext->isDependentContext()) {
6253 // Finalize the clauses that need pre-built expressions for CodeGen.
6254 for (auto C : Clauses) {
6255 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6256 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6257 B.NumIterations, *this, CurScope,
6258 DSAStack))
6259 return StmtError();
6260 }
6261 }
6262
6263 if (checkSimdlenSafelenSpecified(*this, Clauses))
6264 return StmtError();
6265
6266 getCurFunction()->setHasBranchProtectedScope();
6267 return OMPTeamsDistributeSimdDirective::Create(
6268 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6269}
6270
Kelvin Li579e41c2016-11-30 23:51:03 +00006271StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
6272 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6273 SourceLocation EndLoc,
6274 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6275 if (!AStmt)
6276 return StmtError();
6277
6278 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6279 // 1.2.2 OpenMP Language Terminology
6280 // Structured block - An executable statement with a single entry at the
6281 // top and a single exit at the bottom.
6282 // The point of exit cannot be a branch out of the structured block.
6283 // longjmp() and throw() must not violate the entry/exit criteria.
6284 CS->getCapturedDecl()->setNothrow();
6285
6286 OMPLoopDirective::HelperExprs B;
6287 // In presence of clause 'collapse' with number of loops, it will
6288 // define the nested loops number.
6289 auto NestedLoopCount = CheckOpenMPLoop(
6290 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
6291 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6292 VarsWithImplicitDSA, B);
6293
6294 if (NestedLoopCount == 0)
6295 return StmtError();
6296
6297 assert((CurContext->isDependentContext() || B.builtAll()) &&
6298 "omp for loop exprs were not built");
6299
6300 if (!CurContext->isDependentContext()) {
6301 // Finalize the clauses that need pre-built expressions for CodeGen.
6302 for (auto C : Clauses) {
6303 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6304 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6305 B.NumIterations, *this, CurScope,
6306 DSAStack))
6307 return StmtError();
6308 }
6309 }
6310
6311 if (checkSimdlenSafelenSpecified(*this, Clauses))
6312 return StmtError();
6313
6314 getCurFunction()->setHasBranchProtectedScope();
6315 return OMPTeamsDistributeParallelForSimdDirective::Create(
6316 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6317}
6318
Kelvin Li7ade93f2016-12-09 03:24:30 +00006319StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
6320 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6321 SourceLocation EndLoc,
6322 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6323 if (!AStmt)
6324 return StmtError();
6325
6326 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6327 // 1.2.2 OpenMP Language Terminology
6328 // Structured block - An executable statement with a single entry at the
6329 // top and a single exit at the bottom.
6330 // The point of exit cannot be a branch out of the structured block.
6331 // longjmp() and throw() must not violate the entry/exit criteria.
6332 CS->getCapturedDecl()->setNothrow();
6333
6334 OMPLoopDirective::HelperExprs B;
6335 // In presence of clause 'collapse' with number of loops, it will
6336 // define the nested loops number.
6337 unsigned NestedLoopCount = CheckOpenMPLoop(
6338 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
6339 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6340 VarsWithImplicitDSA, B);
6341
6342 if (NestedLoopCount == 0)
6343 return StmtError();
6344
6345 assert((CurContext->isDependentContext() || B.builtAll()) &&
6346 "omp for loop exprs were not built");
6347
6348 if (!CurContext->isDependentContext()) {
6349 // Finalize the clauses that need pre-built expressions for CodeGen.
6350 for (auto C : Clauses) {
6351 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6352 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6353 B.NumIterations, *this, CurScope,
6354 DSAStack))
6355 return StmtError();
6356 }
6357 }
6358
6359 getCurFunction()->setHasBranchProtectedScope();
6360 return OMPTeamsDistributeParallelForDirective::Create(
6361 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6362}
6363
Kelvin Libf594a52016-12-17 05:48:59 +00006364StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
6365 Stmt *AStmt,
6366 SourceLocation StartLoc,
6367 SourceLocation EndLoc) {
6368 if (!AStmt)
6369 return StmtError();
6370
6371 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6372 // 1.2.2 OpenMP Language Terminology
6373 // Structured block - An executable statement with a single entry at the
6374 // top and a single exit at the bottom.
6375 // The point of exit cannot be a branch out of the structured block.
6376 // longjmp() and throw() must not violate the entry/exit criteria.
6377 CS->getCapturedDecl()->setNothrow();
6378
6379 getCurFunction()->setHasBranchProtectedScope();
6380
6381 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
6382 AStmt);
6383}
6384
Kelvin Li83c451e2016-12-25 04:52:54 +00006385StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
6386 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6387 SourceLocation EndLoc,
6388 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6389 if (!AStmt)
6390 return StmtError();
6391
6392 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6393 // 1.2.2 OpenMP Language Terminology
6394 // Structured block - An executable statement with a single entry at the
6395 // top and a single exit at the bottom.
6396 // The point of exit cannot be a branch out of the structured block.
6397 // longjmp() and throw() must not violate the entry/exit criteria.
6398 CS->getCapturedDecl()->setNothrow();
6399
6400 OMPLoopDirective::HelperExprs B;
6401 // In presence of clause 'collapse' with number of loops, it will
6402 // define the nested loops number.
6403 auto NestedLoopCount = CheckOpenMPLoop(
6404 OMPD_target_teams_distribute,
6405 getCollapseNumberExpr(Clauses),
6406 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6407 VarsWithImplicitDSA, B);
6408 if (NestedLoopCount == 0)
6409 return StmtError();
6410
6411 assert((CurContext->isDependentContext() || B.builtAll()) &&
6412 "omp target teams distribute loop exprs were not built");
6413
6414 getCurFunction()->setHasBranchProtectedScope();
6415 return OMPTargetTeamsDistributeDirective::Create(
6416 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6417}
6418
Kelvin Li80e8f562016-12-29 22:16:30 +00006419StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
6420 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6421 SourceLocation EndLoc,
6422 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6423 if (!AStmt)
6424 return StmtError();
6425
6426 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6427 // 1.2.2 OpenMP Language Terminology
6428 // Structured block - An executable statement with a single entry at the
6429 // top and a single exit at the bottom.
6430 // The point of exit cannot be a branch out of the structured block.
6431 // longjmp() and throw() must not violate the entry/exit criteria.
6432 CS->getCapturedDecl()->setNothrow();
6433
6434 OMPLoopDirective::HelperExprs B;
6435 // In presence of clause 'collapse' with number of loops, it will
6436 // define the nested loops number.
6437 auto NestedLoopCount = CheckOpenMPLoop(
6438 OMPD_target_teams_distribute_parallel_for,
6439 getCollapseNumberExpr(Clauses),
6440 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6441 VarsWithImplicitDSA, B);
6442 if (NestedLoopCount == 0)
6443 return StmtError();
6444
6445 assert((CurContext->isDependentContext() || B.builtAll()) &&
6446 "omp target teams distribute parallel for loop exprs were not built");
6447
6448 if (!CurContext->isDependentContext()) {
6449 // Finalize the clauses that need pre-built expressions for CodeGen.
6450 for (auto C : Clauses) {
6451 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6452 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6453 B.NumIterations, *this, CurScope,
6454 DSAStack))
6455 return StmtError();
6456 }
6457 }
6458
6459 getCurFunction()->setHasBranchProtectedScope();
6460 return OMPTargetTeamsDistributeParallelForDirective::Create(
6461 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6462}
6463
Kelvin Li1851df52017-01-03 05:23:48 +00006464StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
6465 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6466 SourceLocation EndLoc,
6467 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6468 if (!AStmt)
6469 return StmtError();
6470
6471 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6472 // 1.2.2 OpenMP Language Terminology
6473 // Structured block - An executable statement with a single entry at the
6474 // top and a single exit at the bottom.
6475 // The point of exit cannot be a branch out of the structured block.
6476 // longjmp() and throw() must not violate the entry/exit criteria.
6477 CS->getCapturedDecl()->setNothrow();
6478
6479 OMPLoopDirective::HelperExprs B;
6480 // In presence of clause 'collapse' with number of loops, it will
6481 // define the nested loops number.
6482 auto NestedLoopCount = CheckOpenMPLoop(
6483 OMPD_target_teams_distribute_parallel_for_simd,
6484 getCollapseNumberExpr(Clauses),
6485 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6486 VarsWithImplicitDSA, B);
6487 if (NestedLoopCount == 0)
6488 return StmtError();
6489
6490 assert((CurContext->isDependentContext() || B.builtAll()) &&
6491 "omp target teams distribute parallel for simd loop exprs were not "
6492 "built");
6493
6494 if (!CurContext->isDependentContext()) {
6495 // Finalize the clauses that need pre-built expressions for CodeGen.
6496 for (auto C : Clauses) {
6497 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6498 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6499 B.NumIterations, *this, CurScope,
6500 DSAStack))
6501 return StmtError();
6502 }
6503 }
6504
6505 getCurFunction()->setHasBranchProtectedScope();
6506 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
6507 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6508}
6509
Kelvin Lida681182017-01-10 18:08:18 +00006510StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
6511 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6512 SourceLocation EndLoc,
6513 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6514 if (!AStmt)
6515 return StmtError();
6516
6517 auto *CS = cast<CapturedStmt>(AStmt);
6518 // 1.2.2 OpenMP Language Terminology
6519 // Structured block - An executable statement with a single entry at the
6520 // top and a single exit at the bottom.
6521 // The point of exit cannot be a branch out of the structured block.
6522 // longjmp() and throw() must not violate the entry/exit criteria.
6523 CS->getCapturedDecl()->setNothrow();
6524
6525 OMPLoopDirective::HelperExprs B;
6526 // In presence of clause 'collapse' with number of loops, it will
6527 // define the nested loops number.
6528 auto NestedLoopCount = CheckOpenMPLoop(
6529 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
6530 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack,
6531 VarsWithImplicitDSA, B);
6532 if (NestedLoopCount == 0)
6533 return StmtError();
6534
6535 assert((CurContext->isDependentContext() || B.builtAll()) &&
6536 "omp target teams distribute simd loop exprs were not built");
6537
6538 getCurFunction()->setHasBranchProtectedScope();
6539 return OMPTargetTeamsDistributeSimdDirective::Create(
6540 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6541}
6542
Alexey Bataeved09d242014-05-28 05:53:51 +00006543OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006544 SourceLocation StartLoc,
6545 SourceLocation LParenLoc,
6546 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006547 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006548 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00006549 case OMPC_final:
6550 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
6551 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00006552 case OMPC_num_threads:
6553 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
6554 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006555 case OMPC_safelen:
6556 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
6557 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00006558 case OMPC_simdlen:
6559 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
6560 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00006561 case OMPC_collapse:
6562 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
6563 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006564 case OMPC_ordered:
6565 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
6566 break;
Michael Wonge710d542015-08-07 16:16:36 +00006567 case OMPC_device:
6568 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
6569 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00006570 case OMPC_num_teams:
6571 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
6572 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006573 case OMPC_thread_limit:
6574 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
6575 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00006576 case OMPC_priority:
6577 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
6578 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00006579 case OMPC_grainsize:
6580 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
6581 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00006582 case OMPC_num_tasks:
6583 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
6584 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00006585 case OMPC_hint:
6586 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
6587 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006588 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006589 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00006590 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00006591 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006592 case OMPC_private:
6593 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00006594 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006595 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00006596 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00006597 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00006598 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00006599 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00006600 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00006601 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00006602 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00006603 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006604 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00006605 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006606 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00006607 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00006608 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00006609 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00006610 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00006611 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00006612 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006613 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00006614 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00006615 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00006616 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00006617 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006618 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00006619 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00006620 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00006621 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00006622 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00006623 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006624 llvm_unreachable("Clause is not allowed.");
6625 }
6626 return Res;
6627}
6628
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006629// An OpenMP directive such as 'target parallel' has two captured regions:
6630// for the 'target' and 'parallel' respectively. This function returns
6631// the region in which to capture expressions associated with a clause.
6632// A return value of OMPD_unknown signifies that the expression should not
6633// be captured.
6634static OpenMPDirectiveKind
6635getOpenMPCaptureRegionForClause(OpenMPDirectiveKind DKind,
6636 OpenMPClauseKind CKind,
6637 OpenMPDirectiveKind NameModifier) {
6638 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
6639
6640 switch (CKind) {
6641 case OMPC_if:
6642 switch (DKind) {
6643 case OMPD_target_parallel:
6644 // If this clause applies to the nested 'parallel' region, capture within
6645 // the 'target' region, otherwise do not capture.
6646 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
6647 CaptureRegion = OMPD_target;
6648 break;
6649 case OMPD_cancel:
6650 case OMPD_parallel:
6651 case OMPD_parallel_sections:
6652 case OMPD_parallel_for:
6653 case OMPD_parallel_for_simd:
6654 case OMPD_target:
6655 case OMPD_target_simd:
6656 case OMPD_target_parallel_for:
6657 case OMPD_target_parallel_for_simd:
6658 case OMPD_target_teams:
6659 case OMPD_target_teams_distribute:
6660 case OMPD_target_teams_distribute_simd:
6661 case OMPD_target_teams_distribute_parallel_for:
6662 case OMPD_target_teams_distribute_parallel_for_simd:
6663 case OMPD_teams_distribute_parallel_for:
6664 case OMPD_teams_distribute_parallel_for_simd:
6665 case OMPD_distribute_parallel_for:
6666 case OMPD_distribute_parallel_for_simd:
6667 case OMPD_task:
6668 case OMPD_taskloop:
6669 case OMPD_taskloop_simd:
6670 case OMPD_target_data:
6671 case OMPD_target_enter_data:
6672 case OMPD_target_exit_data:
6673 case OMPD_target_update:
6674 // Do not capture if-clause expressions.
6675 break;
6676 case OMPD_threadprivate:
6677 case OMPD_taskyield:
6678 case OMPD_barrier:
6679 case OMPD_taskwait:
6680 case OMPD_cancellation_point:
6681 case OMPD_flush:
6682 case OMPD_declare_reduction:
6683 case OMPD_declare_simd:
6684 case OMPD_declare_target:
6685 case OMPD_end_declare_target:
6686 case OMPD_teams:
6687 case OMPD_simd:
6688 case OMPD_for:
6689 case OMPD_for_simd:
6690 case OMPD_sections:
6691 case OMPD_section:
6692 case OMPD_single:
6693 case OMPD_master:
6694 case OMPD_critical:
6695 case OMPD_taskgroup:
6696 case OMPD_distribute:
6697 case OMPD_ordered:
6698 case OMPD_atomic:
6699 case OMPD_distribute_simd:
6700 case OMPD_teams_distribute:
6701 case OMPD_teams_distribute_simd:
6702 llvm_unreachable("Unexpected OpenMP directive with if-clause");
6703 case OMPD_unknown:
6704 llvm_unreachable("Unknown OpenMP directive");
6705 }
6706 break;
6707 case OMPC_schedule:
6708 case OMPC_dist_schedule:
6709 case OMPC_firstprivate:
6710 case OMPC_lastprivate:
6711 case OMPC_reduction:
6712 case OMPC_linear:
6713 case OMPC_default:
6714 case OMPC_proc_bind:
6715 case OMPC_final:
6716 case OMPC_num_threads:
6717 case OMPC_safelen:
6718 case OMPC_simdlen:
6719 case OMPC_collapse:
6720 case OMPC_private:
6721 case OMPC_shared:
6722 case OMPC_aligned:
6723 case OMPC_copyin:
6724 case OMPC_copyprivate:
6725 case OMPC_ordered:
6726 case OMPC_nowait:
6727 case OMPC_untied:
6728 case OMPC_mergeable:
6729 case OMPC_threadprivate:
6730 case OMPC_flush:
6731 case OMPC_read:
6732 case OMPC_write:
6733 case OMPC_update:
6734 case OMPC_capture:
6735 case OMPC_seq_cst:
6736 case OMPC_depend:
6737 case OMPC_device:
6738 case OMPC_threads:
6739 case OMPC_simd:
6740 case OMPC_map:
6741 case OMPC_num_teams:
6742 case OMPC_thread_limit:
6743 case OMPC_priority:
6744 case OMPC_grainsize:
6745 case OMPC_nogroup:
6746 case OMPC_num_tasks:
6747 case OMPC_hint:
6748 case OMPC_defaultmap:
6749 case OMPC_unknown:
6750 case OMPC_uniform:
6751 case OMPC_to:
6752 case OMPC_from:
6753 case OMPC_use_device_ptr:
6754 case OMPC_is_device_ptr:
6755 llvm_unreachable("Unexpected OpenMP clause.");
6756 }
6757 return CaptureRegion;
6758}
6759
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006760OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
6761 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006762 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006763 SourceLocation NameModifierLoc,
6764 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006765 SourceLocation EndLoc) {
6766 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006767 Stmt *HelperValStmt = nullptr;
6768 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006769 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6770 !Condition->isInstantiationDependent() &&
6771 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006772 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006773 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006774 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006775
Richard Smith03a4aa32016-06-23 19:02:52 +00006776 ValExpr = MakeFullExpr(Val.get()).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006777
6778 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6779 CaptureRegion =
6780 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
6781 if (CaptureRegion != OMPD_unknown) {
6782 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
6783 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
6784 HelperValStmt = buildPreInits(Context, Captures);
6785 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006786 }
6787
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00006788 return new (Context)
6789 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
6790 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00006791}
6792
Alexey Bataev3778b602014-07-17 07:32:53 +00006793OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
6794 SourceLocation StartLoc,
6795 SourceLocation LParenLoc,
6796 SourceLocation EndLoc) {
6797 Expr *ValExpr = Condition;
6798 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
6799 !Condition->isInstantiationDependent() &&
6800 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00006801 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00006802 if (Val.isInvalid())
6803 return nullptr;
6804
Richard Smith03a4aa32016-06-23 19:02:52 +00006805 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00006806 }
6807
6808 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
6809}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006810ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
6811 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00006812 if (!Op)
6813 return ExprError();
6814
6815 class IntConvertDiagnoser : public ICEConvertDiagnoser {
6816 public:
6817 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00006818 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00006819 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
6820 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006821 return S.Diag(Loc, diag::err_omp_not_integral) << T;
6822 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006823 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
6824 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006825 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
6826 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006827 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
6828 QualType T,
6829 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006830 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
6831 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006832 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
6833 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006834 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006835 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006836 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006837 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
6838 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006839 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
6840 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006841 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
6842 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006843 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00006844 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00006845 }
Alexey Bataeved09d242014-05-28 05:53:51 +00006846 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
6847 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00006848 llvm_unreachable("conversion functions are permitted");
6849 }
6850 } ConvertDiagnoser;
6851 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
6852}
6853
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006854static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00006855 OpenMPClauseKind CKind,
6856 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006857 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
6858 !ValExpr->isInstantiationDependent()) {
6859 SourceLocation Loc = ValExpr->getExprLoc();
6860 ExprResult Value =
6861 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
6862 if (Value.isInvalid())
6863 return false;
6864
6865 ValExpr = Value.get();
6866 // The expression must evaluate to a non-negative integer value.
6867 llvm::APSInt Result;
6868 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00006869 Result.isSigned() &&
6870 !((!StrictlyPositive && Result.isNonNegative()) ||
6871 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006872 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00006873 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6874 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006875 return false;
6876 }
6877 }
6878 return true;
6879}
6880
Alexey Bataev568a8332014-03-06 06:15:19 +00006881OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
6882 SourceLocation StartLoc,
6883 SourceLocation LParenLoc,
6884 SourceLocation EndLoc) {
6885 Expr *ValExpr = NumThreads;
Alexey Bataev568a8332014-03-06 06:15:19 +00006886
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006887 // OpenMP [2.5, Restrictions]
6888 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00006889 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
6890 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00006891 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00006892
Alexey Bataeved09d242014-05-28 05:53:51 +00006893 return new (Context)
6894 OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00006895}
6896
Alexey Bataev62c87d22014-03-21 04:51:18 +00006897ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006898 OpenMPClauseKind CKind,
6899 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006900 if (!E)
6901 return ExprError();
6902 if (E->isValueDependent() || E->isTypeDependent() ||
6903 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006904 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006905 llvm::APSInt Result;
6906 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
6907 if (ICE.isInvalid())
6908 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006909 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
6910 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00006911 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006912 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
6913 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00006914 return ExprError();
6915 }
Alexander Musman09184fe2014-09-30 05:29:28 +00006916 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
6917 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
6918 << E->getSourceRange();
6919 return ExprError();
6920 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006921 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
6922 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006923 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006924 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00006925 return ICE;
6926}
6927
6928OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
6929 SourceLocation LParenLoc,
6930 SourceLocation EndLoc) {
6931 // OpenMP [2.8.1, simd construct, Description]
6932 // The parameter of the safelen clause must be a constant
6933 // positive integer expression.
6934 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
6935 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006936 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00006937 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006938 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00006939}
6940
Alexey Bataev66b15b52015-08-21 11:14:16 +00006941OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
6942 SourceLocation LParenLoc,
6943 SourceLocation EndLoc) {
6944 // OpenMP [2.8.1, simd construct, Description]
6945 // The parameter of the simdlen clause must be a constant
6946 // positive integer expression.
6947 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
6948 if (Simdlen.isInvalid())
6949 return nullptr;
6950 return new (Context)
6951 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
6952}
6953
Alexander Musman64d33f12014-06-04 07:53:32 +00006954OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
6955 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00006956 SourceLocation LParenLoc,
6957 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00006958 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006959 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00006960 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00006961 // The parameter of the collapse clause must be a constant
6962 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00006963 ExprResult NumForLoopsResult =
6964 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
6965 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00006966 return nullptr;
6967 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00006968 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00006969}
6970
Alexey Bataev10e775f2015-07-30 11:36:16 +00006971OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
6972 SourceLocation EndLoc,
6973 SourceLocation LParenLoc,
6974 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006975 // OpenMP [2.7.1, loop construct, Description]
6976 // OpenMP [2.8.1, simd construct, Description]
6977 // OpenMP [2.9.6, distribute construct, Description]
6978 // The parameter of the ordered clause must be a constant
6979 // positive integer expression if any.
6980 if (NumForLoops && LParenLoc.isValid()) {
6981 ExprResult NumForLoopsResult =
6982 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
6983 if (NumForLoopsResult.isInvalid())
6984 return nullptr;
6985 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00006986 } else
6987 NumForLoops = nullptr;
6988 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00006989 return new (Context)
6990 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
6991}
6992
Alexey Bataeved09d242014-05-28 05:53:51 +00006993OMPClause *Sema::ActOnOpenMPSimpleClause(
6994 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
6995 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00006996 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00006997 switch (Kind) {
6998 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00006999 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00007000 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
7001 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007002 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007003 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00007004 Res = ActOnOpenMPProcBindClause(
7005 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
7006 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007007 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007008 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007009 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007010 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007011 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007012 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007013 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007014 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007015 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007016 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007017 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00007018 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007019 case OMPC_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007020 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007021 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007022 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007023 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007024 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007025 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007026 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007027 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007028 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007029 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007030 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007031 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007032 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007033 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007034 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007035 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007036 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007037 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007038 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007039 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007040 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007041 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007042 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007043 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007044 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007045 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007046 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007047 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007048 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007049 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007050 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007051 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007052 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007053 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007054 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007055 llvm_unreachable("Clause is not allowed.");
7056 }
7057 return Res;
7058}
7059
Alexey Bataev6402bca2015-12-28 07:25:51 +00007060static std::string
7061getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
7062 ArrayRef<unsigned> Exclude = llvm::None) {
7063 std::string Values;
7064 unsigned Bound = Last >= 2 ? Last - 2 : 0;
7065 unsigned Skipped = Exclude.size();
7066 auto S = Exclude.begin(), E = Exclude.end();
7067 for (unsigned i = First; i < Last; ++i) {
7068 if (std::find(S, E, i) != E) {
7069 --Skipped;
7070 continue;
7071 }
7072 Values += "'";
7073 Values += getOpenMPSimpleClauseTypeName(K, i);
7074 Values += "'";
7075 if (i == Bound - Skipped)
7076 Values += " or ";
7077 else if (i != Bound + 1 - Skipped)
7078 Values += ", ";
7079 }
7080 return Values;
7081}
7082
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007083OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
7084 SourceLocation KindKwLoc,
7085 SourceLocation StartLoc,
7086 SourceLocation LParenLoc,
7087 SourceLocation EndLoc) {
7088 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00007089 static_assert(OMPC_DEFAULT_unknown > 0,
7090 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007091 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007092 << getListOfPossibleValues(OMPC_default, /*First=*/0,
7093 /*Last=*/OMPC_DEFAULT_unknown)
7094 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007095 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007096 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00007097 switch (Kind) {
7098 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007099 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007100 break;
7101 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007102 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007103 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007104 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007105 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00007106 break;
7107 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007108 return new (Context)
7109 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007110}
7111
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007112OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
7113 SourceLocation KindKwLoc,
7114 SourceLocation StartLoc,
7115 SourceLocation LParenLoc,
7116 SourceLocation EndLoc) {
7117 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007118 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00007119 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
7120 /*Last=*/OMPC_PROC_BIND_unknown)
7121 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007122 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007123 }
Alexey Bataeved09d242014-05-28 05:53:51 +00007124 return new (Context)
7125 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007126}
7127
Alexey Bataev56dafe82014-06-20 07:16:17 +00007128OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007129 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007130 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007131 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007132 SourceLocation EndLoc) {
7133 OMPClause *Res = nullptr;
7134 switch (Kind) {
7135 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007136 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
7137 assert(Argument.size() == NumberOfElements &&
7138 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007139 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007140 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
7141 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
7142 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
7143 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
7144 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007145 break;
7146 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00007147 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
7148 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
7149 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
7150 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007151 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00007152 case OMPC_dist_schedule:
7153 Res = ActOnOpenMPDistScheduleClause(
7154 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
7155 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
7156 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007157 case OMPC_defaultmap:
7158 enum { Modifier, DefaultmapKind };
7159 Res = ActOnOpenMPDefaultmapClause(
7160 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
7161 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00007162 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
7163 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007164 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00007165 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007166 case OMPC_num_threads:
7167 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007168 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007169 case OMPC_collapse:
7170 case OMPC_default:
7171 case OMPC_proc_bind:
7172 case OMPC_private:
7173 case OMPC_firstprivate:
7174 case OMPC_lastprivate:
7175 case OMPC_shared:
7176 case OMPC_reduction:
7177 case OMPC_linear:
7178 case OMPC_aligned:
7179 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007180 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007181 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007182 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007183 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007184 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007185 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007186 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007187 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007188 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007189 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007190 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007191 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007192 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007193 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007194 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007195 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007196 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007197 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007198 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007199 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007200 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007201 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007202 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007203 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007204 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007205 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007206 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007207 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007208 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007209 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007210 llvm_unreachable("Clause is not allowed.");
7211 }
7212 return Res;
7213}
7214
Alexey Bataev6402bca2015-12-28 07:25:51 +00007215static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
7216 OpenMPScheduleClauseModifier M2,
7217 SourceLocation M1Loc, SourceLocation M2Loc) {
7218 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
7219 SmallVector<unsigned, 2> Excluded;
7220 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
7221 Excluded.push_back(M2);
7222 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
7223 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
7224 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
7225 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
7226 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
7227 << getListOfPossibleValues(OMPC_schedule,
7228 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
7229 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7230 Excluded)
7231 << getOpenMPClauseName(OMPC_schedule);
7232 return true;
7233 }
7234 return false;
7235}
7236
Alexey Bataev56dafe82014-06-20 07:16:17 +00007237OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00007238 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00007239 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00007240 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
7241 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
7242 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
7243 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
7244 return nullptr;
7245 // OpenMP, 2.7.1, Loop Construct, Restrictions
7246 // Either the monotonic modifier or the nonmonotonic modifier can be specified
7247 // but not both.
7248 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
7249 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
7250 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
7251 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
7252 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
7253 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
7254 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
7255 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
7256 return nullptr;
7257 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007258 if (Kind == OMPC_SCHEDULE_unknown) {
7259 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00007260 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
7261 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
7262 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7263 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
7264 Exclude);
7265 } else {
7266 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
7267 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007268 }
7269 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
7270 << Values << getOpenMPClauseName(OMPC_schedule);
7271 return nullptr;
7272 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00007273 // OpenMP, 2.7.1, Loop Construct, Restrictions
7274 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
7275 // schedule(guided).
7276 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
7277 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
7278 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
7279 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
7280 diag::err_omp_schedule_nonmonotonic_static);
7281 return nullptr;
7282 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00007283 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00007284 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00007285 if (ChunkSize) {
7286 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
7287 !ChunkSize->isInstantiationDependent() &&
7288 !ChunkSize->containsUnexpandedParameterPack()) {
7289 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
7290 ExprResult Val =
7291 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
7292 if (Val.isInvalid())
7293 return nullptr;
7294
7295 ValExpr = Val.get();
7296
7297 // OpenMP [2.7.1, Restrictions]
7298 // chunk_size must be a loop invariant integer expression with a positive
7299 // value.
7300 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00007301 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
7302 if (Result.isSigned() && !Result.isStrictlyPositive()) {
7303 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00007304 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00007305 return nullptr;
7306 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +00007307 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
7308 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007309 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
7310 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
7311 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007312 }
7313 }
7314 }
7315
Alexey Bataev6402bca2015-12-28 07:25:51 +00007316 return new (Context)
7317 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00007318 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00007319}
7320
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007321OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
7322 SourceLocation StartLoc,
7323 SourceLocation EndLoc) {
7324 OMPClause *Res = nullptr;
7325 switch (Kind) {
7326 case OMPC_ordered:
7327 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
7328 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00007329 case OMPC_nowait:
7330 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
7331 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007332 case OMPC_untied:
7333 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
7334 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007335 case OMPC_mergeable:
7336 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
7337 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007338 case OMPC_read:
7339 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
7340 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00007341 case OMPC_write:
7342 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
7343 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007344 case OMPC_update:
7345 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
7346 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00007347 case OMPC_capture:
7348 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
7349 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007350 case OMPC_seq_cst:
7351 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
7352 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00007353 case OMPC_threads:
7354 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
7355 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007356 case OMPC_simd:
7357 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
7358 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00007359 case OMPC_nogroup:
7360 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
7361 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007362 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007363 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007364 case OMPC_num_threads:
7365 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007366 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007367 case OMPC_collapse:
7368 case OMPC_schedule:
7369 case OMPC_private:
7370 case OMPC_firstprivate:
7371 case OMPC_lastprivate:
7372 case OMPC_shared:
7373 case OMPC_reduction:
7374 case OMPC_linear:
7375 case OMPC_aligned:
7376 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007377 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007378 case OMPC_default:
7379 case OMPC_proc_bind:
7380 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007381 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007382 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00007383 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007384 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007385 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007386 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007387 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007388 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00007389 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007390 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007391 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007392 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007393 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007394 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007395 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007396 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007397 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007398 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007399 llvm_unreachable("Clause is not allowed.");
7400 }
7401 return Res;
7402}
7403
Alexey Bataev236070f2014-06-20 11:19:47 +00007404OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
7405 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007406 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00007407 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
7408}
7409
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007410OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
7411 SourceLocation EndLoc) {
7412 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
7413}
7414
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007415OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
7416 SourceLocation EndLoc) {
7417 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
7418}
7419
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007420OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
7421 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007422 return new (Context) OMPReadClause(StartLoc, EndLoc);
7423}
7424
Alexey Bataevdea47612014-07-23 07:46:59 +00007425OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
7426 SourceLocation EndLoc) {
7427 return new (Context) OMPWriteClause(StartLoc, EndLoc);
7428}
7429
Alexey Bataev67a4f222014-07-23 10:25:33 +00007430OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
7431 SourceLocation EndLoc) {
7432 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
7433}
7434
Alexey Bataev459dec02014-07-24 06:46:57 +00007435OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
7436 SourceLocation EndLoc) {
7437 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
7438}
7439
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007440OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
7441 SourceLocation EndLoc) {
7442 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
7443}
7444
Alexey Bataev346265e2015-09-25 10:37:12 +00007445OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
7446 SourceLocation EndLoc) {
7447 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
7448}
7449
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007450OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
7451 SourceLocation EndLoc) {
7452 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
7453}
7454
Alexey Bataevb825de12015-12-07 10:51:44 +00007455OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
7456 SourceLocation EndLoc) {
7457 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
7458}
7459
Alexey Bataevc5e02582014-06-16 07:08:35 +00007460OMPClause *Sema::ActOnOpenMPVarListClause(
7461 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
7462 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
7463 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007464 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00007465 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
7466 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
7467 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007468 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007469 switch (Kind) {
7470 case OMPC_private:
7471 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7472 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007473 case OMPC_firstprivate:
7474 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7475 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00007476 case OMPC_lastprivate:
7477 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7478 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00007479 case OMPC_shared:
7480 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
7481 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00007482 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00007483 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
7484 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00007485 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00007486 case OMPC_linear:
7487 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007488 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00007489 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007490 case OMPC_aligned:
7491 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
7492 ColonLoc, EndLoc);
7493 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007494 case OMPC_copyin:
7495 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
7496 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00007497 case OMPC_copyprivate:
7498 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
7499 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00007500 case OMPC_flush:
7501 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
7502 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007503 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00007504 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00007505 StartLoc, LParenLoc, EndLoc);
7506 break;
7507 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00007508 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
7509 DepLinMapLoc, ColonLoc, VarList, StartLoc,
7510 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007511 break;
Samuel Antao661c0902016-05-26 17:39:58 +00007512 case OMPC_to:
7513 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
7514 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00007515 case OMPC_from:
7516 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
7517 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00007518 case OMPC_use_device_ptr:
7519 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7520 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00007521 case OMPC_is_device_ptr:
7522 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
7523 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007524 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00007525 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00007526 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00007527 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00007528 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00007529 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007530 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007531 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007532 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00007533 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00007534 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007535 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007536 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007537 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007538 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007539 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007540 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007541 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007542 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00007543 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00007544 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007545 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00007546 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007547 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00007548 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007549 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00007550 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00007551 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00007552 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007553 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007554 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007555 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007556 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007557 llvm_unreachable("Clause is not allowed.");
7558 }
7559 return Res;
7560}
7561
Alexey Bataev90c228f2016-02-08 09:29:13 +00007562ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00007563 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00007564 ExprResult Res = BuildDeclRefExpr(
7565 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
7566 if (!Res.isUsable())
7567 return ExprError();
7568 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
7569 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
7570 if (!Res.isUsable())
7571 return ExprError();
7572 }
7573 if (VK != VK_LValue && Res.get()->isGLValue()) {
7574 Res = DefaultLvalueConversion(Res.get());
7575 if (!Res.isUsable())
7576 return ExprError();
7577 }
7578 return Res;
7579}
7580
Alexey Bataev60da77e2016-02-29 05:54:20 +00007581static std::pair<ValueDecl *, bool>
7582getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
7583 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007584 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
7585 RefExpr->containsUnexpandedParameterPack())
7586 return std::make_pair(nullptr, true);
7587
Alexey Bataevd985eda2016-02-10 11:29:16 +00007588 // OpenMP [3.1, C/C++]
7589 // A list item is a variable name.
7590 // OpenMP [2.9.3.3, Restrictions, p.1]
7591 // A variable that is part of another variable (as an array or
7592 // structure element) cannot appear in a private clause.
7593 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00007594 enum {
7595 NoArrayExpr = -1,
7596 ArraySubscript = 0,
7597 OMPArraySection = 1
7598 } IsArrayExpr = NoArrayExpr;
7599 if (AllowArraySection) {
7600 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
7601 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
7602 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7603 Base = TempASE->getBase()->IgnoreParenImpCasts();
7604 RefExpr = Base;
7605 IsArrayExpr = ArraySubscript;
7606 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
7607 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
7608 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
7609 Base = TempOASE->getBase()->IgnoreParenImpCasts();
7610 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
7611 Base = TempASE->getBase()->IgnoreParenImpCasts();
7612 RefExpr = Base;
7613 IsArrayExpr = OMPArraySection;
7614 }
7615 }
7616 ELoc = RefExpr->getExprLoc();
7617 ERange = RefExpr->getSourceRange();
7618 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00007619 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
7620 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
7621 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
7622 (S.getCurrentThisType().isNull() || !ME ||
7623 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
7624 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00007625 if (IsArrayExpr != NoArrayExpr)
7626 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
7627 << ERange;
7628 else {
7629 S.Diag(ELoc,
7630 AllowArraySection
7631 ? diag::err_omp_expected_var_name_member_expr_or_array_item
7632 : diag::err_omp_expected_var_name_member_expr)
7633 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
7634 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007635 return std::make_pair(nullptr, false);
7636 }
7637 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false);
7638}
7639
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007640OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
7641 SourceLocation StartLoc,
7642 SourceLocation LParenLoc,
7643 SourceLocation EndLoc) {
7644 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00007645 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00007646 for (auto &RefExpr : VarList) {
7647 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007648 SourceLocation ELoc;
7649 SourceRange ERange;
7650 Expr *SimpleRefExpr = RefExpr;
7651 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007652 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007653 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007654 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007655 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007656 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007657 ValueDecl *D = Res.first;
7658 if (!D)
7659 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007660
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007661 QualType Type = D->getType();
7662 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007663
7664 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7665 // A variable that appears in a private clause must not have an incomplete
7666 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007667 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007668 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007669 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007670
Alexey Bataev758e55e2013-09-06 18:03:48 +00007671 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7672 // in a Construct]
7673 // Variables with the predetermined data-sharing attributes may not be
7674 // listed in data-sharing attributes clauses, except for the cases
7675 // listed below. For these exceptions only, listing a predetermined
7676 // variable in a data-sharing attribute clause is allowed and overrides
7677 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007678 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007679 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00007680 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
7681 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007682 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00007683 continue;
7684 }
7685
Kelvin Libf594a52016-12-17 05:48:59 +00007686 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007687 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007688 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00007689 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007690 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7691 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00007692 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007693 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007694 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007695 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007696 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007697 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007698 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007699 continue;
7700 }
7701
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007702 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7703 // A list item cannot appear in both a map clause and a data-sharing
7704 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007705 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007706 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007707 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007708 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007709 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007710 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007711 CurrDir == OMPD_target_parallel_for_simd ||
7712 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007713 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007714 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007715 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007716 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7717 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7718 ConflictKind = WhereFoundClauseKind;
7719 return true;
7720 })) {
7721 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007722 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00007723 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00007724 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007725 ReportOriginalDSA(*this, DSAStack, D, DVar);
7726 continue;
7727 }
7728 }
7729
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007730 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
7731 // A variable of class type (or array thereof) that appears in a private
7732 // clause requires an accessible, unambiguous default constructor for the
7733 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00007734 // Generate helper private variable and initialize it with the default
7735 // value. The address of the original variable is replaced by the address of
7736 // the new private variable in CodeGen. This new variable is not added to
7737 // IdResolver, so the code in the OpenMP region uses original variable for
7738 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007739 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007740 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
7741 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00007742 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007743 if (VDPrivate->isInvalidDecl())
7744 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007745 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00007746 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007747
Alexey Bataev90c228f2016-02-08 09:29:13 +00007748 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007749 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00007750 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00007751 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00007752 Vars.push_back((VD || CurContext->isDependentContext())
7753 ? RefExpr->IgnoreParens()
7754 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00007755 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007756 }
7757
Alexey Bataeved09d242014-05-28 05:53:51 +00007758 if (Vars.empty())
7759 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007760
Alexey Bataev03b340a2014-10-21 03:16:40 +00007761 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
7762 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00007763}
7764
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007765namespace {
7766class DiagsUninitializedSeveretyRAII {
7767private:
7768 DiagnosticsEngine &Diags;
7769 SourceLocation SavedLoc;
7770 bool IsIgnored;
7771
7772public:
7773 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
7774 bool IsIgnored)
7775 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
7776 if (!IsIgnored) {
7777 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
7778 /*Map*/ diag::Severity::Ignored, Loc);
7779 }
7780 }
7781 ~DiagsUninitializedSeveretyRAII() {
7782 if (!IsIgnored)
7783 Diags.popMappings(SavedLoc);
7784 }
7785};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007786}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007787
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007788OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
7789 SourceLocation StartLoc,
7790 SourceLocation LParenLoc,
7791 SourceLocation EndLoc) {
7792 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007793 SmallVector<Expr *, 8> PrivateCopies;
7794 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00007795 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007796 bool IsImplicitClause =
7797 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
7798 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
7799
Alexey Bataeved09d242014-05-28 05:53:51 +00007800 for (auto &RefExpr : VarList) {
7801 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00007802 SourceLocation ELoc;
7803 SourceRange ERange;
7804 Expr *SimpleRefExpr = RefExpr;
7805 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007806 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007807 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00007808 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00007809 PrivateCopies.push_back(nullptr);
7810 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007811 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007812 ValueDecl *D = Res.first;
7813 if (!D)
7814 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007815
Alexey Bataev60da77e2016-02-29 05:54:20 +00007816 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00007817 QualType Type = D->getType();
7818 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007819
7820 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
7821 // A variable that appears in a private clause must not have an incomplete
7822 // type or a reference type.
7823 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00007824 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007825 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00007826 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007827
7828 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
7829 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00007830 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007831 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007832 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007833
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007834 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00007835 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007836 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007837 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00007838 TopDVar = DVar;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00007839 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007840 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
7841 // A list item that specifies a given variable may not appear in more
7842 // than one clause on the same directive, except that a variable may be
7843 // specified in both firstprivate and lastprivate clauses.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007844 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevf29276e2014-06-18 04:14:57 +00007845 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007846 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007847 << getOpenMPClauseName(DVar.CKind)
7848 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007849 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007850 continue;
7851 }
7852
7853 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7854 // in a Construct]
7855 // Variables with the predetermined data-sharing attributes may not be
7856 // listed in data-sharing attributes clauses, except for the cases
7857 // listed below. For these exceptions only, listing a predetermined
7858 // variable in a data-sharing attribute clause is allowed and overrides
7859 // the variable's predetermined data-sharing attributes.
7860 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
7861 // in a Construct, C/C++, p.2]
7862 // Variables with const-qualified type having no mutable member may be
7863 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00007864 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007865 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
7866 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00007867 << getOpenMPClauseName(DVar.CKind)
7868 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007869 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007870 continue;
7871 }
7872
Alexey Bataevf29276e2014-06-18 04:14:57 +00007873 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007874 // OpenMP [2.9.3.4, Restrictions, p.2]
7875 // A list item that is private within a parallel region must not appear
7876 // in a firstprivate clause on a worksharing construct if any of the
7877 // worksharing regions arising from the worksharing construct ever bind
7878 // to any of the parallel regions arising from the parallel construct.
Alexey Bataev549210e2014-06-24 04:39:47 +00007879 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00007880 !isOpenMPParallelDirective(CurrDir) &&
7881 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00007882 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007883 if (DVar.CKind != OMPC_shared &&
7884 (isOpenMPParallelDirective(DVar.DKind) ||
7885 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00007886 Diag(ELoc, diag::err_omp_required_access)
7887 << getOpenMPClauseName(OMPC_firstprivate)
7888 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007889 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00007890 continue;
7891 }
7892 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007893 // OpenMP [2.9.3.4, Restrictions, p.3]
7894 // A list item that appears in a reduction clause of a parallel construct
7895 // must not appear in a firstprivate clause on a worksharing or task
7896 // construct if any of the worksharing or task regions arising from the
7897 // worksharing or task construct ever bind to any of the parallel regions
7898 // arising from the parallel construct.
7899 // OpenMP [2.9.3.4, Restrictions, p.4]
7900 // A list item that appears in a reduction clause in worksharing
7901 // construct must not appear in a firstprivate clause in a task construct
7902 // encountered during execution of any of the worksharing regions arising
7903 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00007904 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007905 DVar = DSAStack->hasInnermostDSA(
7906 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7907 [](OpenMPDirectiveKind K) -> bool {
7908 return isOpenMPParallelDirective(K) ||
7909 isOpenMPWorksharingDirective(K);
7910 },
7911 false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007912 if (DVar.CKind == OMPC_reduction &&
7913 (isOpenMPParallelDirective(DVar.DKind) ||
7914 isOpenMPWorksharingDirective(DVar.DKind))) {
7915 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
7916 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007917 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007918 continue;
7919 }
7920 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007921
7922 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7923 // A list item that is private within a teams region must not appear in a
7924 // firstprivate clause on a distribute construct if any of the distribute
7925 // regions arising from the distribute construct ever bind to any of the
7926 // teams regions arising from the teams construct.
7927 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
7928 // A list item that appears in a reduction clause of a teams construct
7929 // must not appear in a firstprivate clause on a distribute construct if
7930 // any of the distribute regions arising from the distribute construct
7931 // ever bind to any of the teams regions arising from the teams construct.
7932 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
7933 // A list item may appear in a firstprivate or lastprivate clause but not
7934 // both.
7935 if (CurrDir == OMPD_distribute) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007936 DVar = DSAStack->hasInnermostDSA(
7937 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; },
7938 [](OpenMPDirectiveKind K) -> bool {
7939 return isOpenMPTeamsDirective(K);
7940 },
7941 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007942 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
7943 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007944 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007945 continue;
7946 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00007947 DVar = DSAStack->hasInnermostDSA(
7948 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
7949 [](OpenMPDirectiveKind K) -> bool {
7950 return isOpenMPTeamsDirective(K);
7951 },
7952 false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007953 if (DVar.CKind == OMPC_reduction &&
7954 isOpenMPTeamsDirective(DVar.DKind)) {
7955 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007956 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007957 continue;
7958 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00007959 DVar = DSAStack->getTopDSA(D, false);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007960 if (DVar.CKind == OMPC_lastprivate) {
7961 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
Alexey Bataevd985eda2016-02-10 11:29:16 +00007962 ReportOriginalDSA(*this, DSAStack, D, DVar);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007963 continue;
7964 }
7965 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007966 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
7967 // A list item cannot appear in both a map clause and a data-sharing
7968 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00007969 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Kelvin Lida681182017-01-10 18:08:18 +00007970 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00007971 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00007972 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00007973 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00007974 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00007975 CurrDir == OMPD_target_parallel_for_simd ||
7976 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00007977 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00007978 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00007979 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00007980 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
7981 OpenMPClauseKind WhereFoundClauseKind) -> bool {
7982 ConflictKind = WhereFoundClauseKind;
7983 return true;
7984 })) {
7985 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007986 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00007987 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00007988 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
7989 ReportOriginalDSA(*this, DSAStack, D, DVar);
7990 continue;
7991 }
7992 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00007993 }
7994
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007995 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00007996 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00007997 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00007998 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
7999 << getOpenMPClauseName(OMPC_firstprivate) << Type
8000 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
8001 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008002 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008003 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00008004 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008005 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00008006 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00008007 continue;
8008 }
8009
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008010 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008011 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
8012 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008013 // Generate helper private variable and initialize it with the value of the
8014 // original variable. The address of the original variable is replaced by
8015 // the address of the new private variable in the CodeGen. This new variable
8016 // is not added to IdResolver, so the code in the OpenMP region uses
8017 // original variable for proper diagnostics and variable capturing.
8018 Expr *VDInitRefExpr = nullptr;
8019 // For arrays generate initializer for single element and replace it by the
8020 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008021 if (Type->isArrayType()) {
8022 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00008023 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008024 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008025 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008026 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00008027 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00008028 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00008029 InitializedEntity Entity =
8030 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008031 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
8032
8033 InitializationSequence InitSeq(*this, Entity, Kind, Init);
8034 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
8035 if (Result.isInvalid())
8036 VDPrivate->setInvalidDecl();
8037 else
8038 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008039 // Remove temp variable declaration.
8040 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008041 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008042 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
8043 ".firstprivate.temp");
8044 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
8045 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00008046 AddInitializerToDecl(VDPrivate,
8047 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00008048 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008049 }
8050 if (VDPrivate->isInvalidDecl()) {
8051 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00008052 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008053 diag::note_omp_task_predetermined_firstprivate_here);
8054 }
8055 continue;
8056 }
8057 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00008058 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00008059 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
8060 RefExpr->getExprLoc());
8061 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008062 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008063 if (TopDVar.CKind == OMPC_lastprivate)
8064 Ref = TopDVar.PrivateCopy;
8065 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008066 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00008067 if (!IsOpenMPCapturedDecl(D))
8068 ExprCaptures.push_back(Ref->getDecl());
8069 }
Alexey Bataev417089f2016-02-17 13:19:37 +00008070 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00008071 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008072 Vars.push_back((VD || CurContext->isDependentContext())
8073 ? RefExpr->IgnoreParens()
8074 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00008075 PrivateCopies.push_back(VDPrivateRefExpr);
8076 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008077 }
8078
Alexey Bataeved09d242014-05-28 05:53:51 +00008079 if (Vars.empty())
8080 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008081
8082 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008083 Vars, PrivateCopies, Inits,
8084 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008085}
8086
Alexander Musman1bb328c2014-06-04 13:06:39 +00008087OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8088 SourceLocation StartLoc,
8089 SourceLocation LParenLoc,
8090 SourceLocation EndLoc) {
8091 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00008092 SmallVector<Expr *, 8> SrcExprs;
8093 SmallVector<Expr *, 8> DstExprs;
8094 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00008095 SmallVector<Decl *, 4> ExprCaptures;
8096 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008097 for (auto &RefExpr : VarList) {
8098 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008099 SourceLocation ELoc;
8100 SourceRange ERange;
8101 Expr *SimpleRefExpr = RefExpr;
8102 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008103 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00008104 // It will be analyzed later.
8105 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00008106 SrcExprs.push_back(nullptr);
8107 DstExprs.push_back(nullptr);
8108 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008109 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008110 ValueDecl *D = Res.first;
8111 if (!D)
8112 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008113
Alexey Bataev74caaf22016-02-20 04:09:36 +00008114 QualType Type = D->getType();
8115 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008116
8117 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
8118 // A variable that appears in a lastprivate clause must not have an
8119 // incomplete type or a reference type.
8120 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00008121 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00008122 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00008123 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00008124
8125 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8126 // in a Construct]
8127 // Variables with the predetermined data-sharing attributes may not be
8128 // listed in data-sharing attributes clauses, except for the cases
8129 // listed below.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008130 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008131 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
8132 DVar.CKind != OMPC_firstprivate &&
8133 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
8134 Diag(ELoc, diag::err_omp_wrong_dsa)
8135 << getOpenMPClauseName(DVar.CKind)
8136 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008137 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00008138 continue;
8139 }
8140
Alexey Bataevf29276e2014-06-18 04:14:57 +00008141 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8142 // OpenMP [2.14.3.5, Restrictions, p.2]
8143 // A list item that is private within a parallel region, or that appears in
8144 // the reduction clause of a parallel construct, must not appear in a
8145 // lastprivate clause on a worksharing construct if any of the corresponding
8146 // worksharing regions ever binds to any of the corresponding parallel
8147 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00008148 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00008149 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008150 !isOpenMPParallelDirective(CurrDir) &&
8151 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00008152 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008153 if (DVar.CKind != OMPC_shared) {
8154 Diag(ELoc, diag::err_omp_required_access)
8155 << getOpenMPClauseName(OMPC_lastprivate)
8156 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00008157 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008158 continue;
8159 }
8160 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00008161
8162 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
8163 // A list item may appear in a firstprivate or lastprivate clause but not
8164 // both.
8165 if (CurrDir == OMPD_distribute) {
8166 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
8167 if (DVar.CKind == OMPC_firstprivate) {
8168 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
8169 ReportOriginalDSA(*this, DSAStack, D, DVar);
8170 continue;
8171 }
8172 }
8173
Alexander Musman1bb328c2014-06-04 13:06:39 +00008174 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00008175 // A variable of class type (or array thereof) that appears in a
8176 // lastprivate clause requires an accessible, unambiguous default
8177 // constructor for the class type, unless the list item is also specified
8178 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00008179 // A variable of class type (or array thereof) that appears in a
8180 // lastprivate clause requires an accessible, unambiguous copy assignment
8181 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00008182 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008183 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00008184 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008185 D->hasAttrs() ? &D->getAttrs() : nullptr);
8186 auto *PseudoSrcExpr =
8187 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008188 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008189 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00008190 D->hasAttrs() ? &D->getAttrs() : nullptr);
8191 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00008192 // For arrays generate assignment operation for single element and replace
8193 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00008194 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00008195 PseudoDstExpr, PseudoSrcExpr);
8196 if (AssignmentOp.isInvalid())
8197 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00008198 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00008199 /*DiscardedValue=*/true);
8200 if (AssignmentOp.isInvalid())
8201 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008202
Alexey Bataev74caaf22016-02-20 04:09:36 +00008203 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008204 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008205 if (TopDVar.CKind == OMPC_firstprivate)
8206 Ref = TopDVar.PrivateCopy;
8207 else {
Alexey Bataev61205072016-03-02 04:57:40 +00008208 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00008209 if (!IsOpenMPCapturedDecl(D))
8210 ExprCaptures.push_back(Ref->getDecl());
8211 }
8212 if (TopDVar.CKind == OMPC_firstprivate ||
8213 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00008214 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00008215 ExprResult RefRes = DefaultLvalueConversion(Ref);
8216 if (!RefRes.isUsable())
8217 continue;
8218 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00008219 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
8220 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008221 if (!PostUpdateRes.isUsable())
8222 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00008223 ExprPostUpdates.push_back(
8224 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00008225 }
8226 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008227 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008228 Vars.push_back((VD || CurContext->isDependentContext())
8229 ? RefExpr->IgnoreParens()
8230 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00008231 SrcExprs.push_back(PseudoSrcExpr);
8232 DstExprs.push_back(PseudoDstExpr);
8233 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00008234 }
8235
8236 if (Vars.empty())
8237 return nullptr;
8238
8239 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00008240 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00008241 buildPreInits(Context, ExprCaptures),
8242 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00008243}
8244
Alexey Bataev758e55e2013-09-06 18:03:48 +00008245OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8246 SourceLocation StartLoc,
8247 SourceLocation LParenLoc,
8248 SourceLocation EndLoc) {
8249 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00008250 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008251 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00008252 SourceLocation ELoc;
8253 SourceRange ERange;
8254 Expr *SimpleRefExpr = RefExpr;
8255 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008256 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00008257 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00008258 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008259 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008260 ValueDecl *D = Res.first;
8261 if (!D)
8262 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008263
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008264 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008265 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
8266 // in a Construct]
8267 // Variables with the predetermined data-sharing attributes may not be
8268 // listed in data-sharing attributes clauses, except for the cases
8269 // listed below. For these exceptions only, listing a predetermined
8270 // variable in a data-sharing attribute clause is allowed and overrides
8271 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008272 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00008273 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
8274 DVar.RefExpr) {
8275 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
8276 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008277 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008278 continue;
8279 }
8280
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008281 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008282 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00008283 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00008284 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008285 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
8286 ? RefExpr->IgnoreParens()
8287 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008288 }
8289
Alexey Bataeved09d242014-05-28 05:53:51 +00008290 if (Vars.empty())
8291 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008292
8293 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
8294}
8295
Alexey Bataevc5e02582014-06-16 07:08:35 +00008296namespace {
8297class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
8298 DSAStackTy *Stack;
8299
8300public:
8301 bool VisitDeclRefExpr(DeclRefExpr *E) {
8302 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008303 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008304 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
8305 return false;
8306 if (DVar.CKind != OMPC_unknown)
8307 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00008308 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
8309 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
8310 false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00008311 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008312 return true;
8313 return false;
8314 }
8315 return false;
8316 }
8317 bool VisitStmt(Stmt *S) {
8318 for (auto Child : S->children()) {
8319 if (Child && Visit(Child))
8320 return true;
8321 }
8322 return false;
8323 }
Alexey Bataev23b69422014-06-18 07:08:49 +00008324 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00008325};
Alexey Bataev23b69422014-06-18 07:08:49 +00008326} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00008327
Alexey Bataev60da77e2016-02-29 05:54:20 +00008328namespace {
8329// Transform MemberExpression for specified FieldDecl of current class to
8330// DeclRefExpr to specified OMPCapturedExprDecl.
8331class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
8332 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
8333 ValueDecl *Field;
8334 DeclRefExpr *CapturedExpr;
8335
8336public:
8337 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
8338 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
8339
8340 ExprResult TransformMemberExpr(MemberExpr *E) {
8341 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
8342 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00008343 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008344 return CapturedExpr;
8345 }
8346 return BaseTransform::TransformMemberExpr(E);
8347 }
8348 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
8349};
8350} // namespace
8351
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008352template <typename T>
8353static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
8354 const llvm::function_ref<T(ValueDecl *)> &Gen) {
8355 for (auto &Set : Lookups) {
8356 for (auto *D : Set) {
8357 if (auto Res = Gen(cast<ValueDecl>(D)))
8358 return Res;
8359 }
8360 }
8361 return T();
8362}
8363
8364static ExprResult
8365buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
8366 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
8367 const DeclarationNameInfo &ReductionId, QualType Ty,
8368 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
8369 if (ReductionIdScopeSpec.isInvalid())
8370 return ExprError();
8371 SmallVector<UnresolvedSet<8>, 4> Lookups;
8372 if (S) {
8373 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
8374 Lookup.suppressDiagnostics();
8375 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
8376 auto *D = Lookup.getRepresentativeDecl();
8377 do {
8378 S = S->getParent();
8379 } while (S && !S->isDeclScope(D));
8380 if (S)
8381 S = S->getParent();
8382 Lookups.push_back(UnresolvedSet<8>());
8383 Lookups.back().append(Lookup.begin(), Lookup.end());
8384 Lookup.clear();
8385 }
8386 } else if (auto *ULE =
8387 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
8388 Lookups.push_back(UnresolvedSet<8>());
8389 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00008390 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008391 if (D == PrevD)
8392 Lookups.push_back(UnresolvedSet<8>());
8393 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
8394 Lookups.back().addDecl(DRD);
8395 PrevD = D;
8396 }
8397 }
8398 if (Ty->isDependentType() || Ty->isInstantiationDependentType() ||
8399 Ty->containsUnexpandedParameterPack() ||
8400 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
8401 return !D->isInvalidDecl() &&
8402 (D->getType()->isDependentType() ||
8403 D->getType()->isInstantiationDependentType() ||
8404 D->getType()->containsUnexpandedParameterPack());
8405 })) {
8406 UnresolvedSet<8> ResSet;
8407 for (auto &Set : Lookups) {
8408 ResSet.append(Set.begin(), Set.end());
8409 // The last item marks the end of all declarations at the specified scope.
8410 ResSet.addDecl(Set[Set.size() - 1]);
8411 }
8412 return UnresolvedLookupExpr::Create(
8413 SemaRef.Context, /*NamingClass=*/nullptr,
8414 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
8415 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
8416 }
8417 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8418 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
8419 if (!D->isInvalidDecl() &&
8420 SemaRef.Context.hasSameType(D->getType(), Ty))
8421 return D;
8422 return nullptr;
8423 }))
8424 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8425 if (auto *VD = filterLookupForUDR<ValueDecl *>(
8426 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
8427 if (!D->isInvalidDecl() &&
8428 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
8429 !Ty.isMoreQualifiedThan(D->getType()))
8430 return D;
8431 return nullptr;
8432 })) {
8433 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8434 /*DetectVirtual=*/false);
8435 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
8436 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
8437 VD->getType().getUnqualifiedType()))) {
8438 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
8439 /*DiagID=*/0) !=
8440 Sema::AR_inaccessible) {
8441 SemaRef.BuildBasePathArray(Paths, BasePath);
8442 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
8443 }
8444 }
8445 }
8446 }
8447 if (ReductionIdScopeSpec.isSet()) {
8448 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
8449 return ExprError();
8450 }
8451 return ExprEmpty();
8452}
8453
Alexey Bataevc5e02582014-06-16 07:08:35 +00008454OMPClause *Sema::ActOnOpenMPReductionClause(
8455 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
8456 SourceLocation ColonLoc, SourceLocation EndLoc,
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008457 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
8458 ArrayRef<Expr *> UnresolvedReductions) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00008459 auto DN = ReductionId.getName();
8460 auto OOK = DN.getCXXOverloadedOperator();
8461 BinaryOperatorKind BOK = BO_Comma;
8462
8463 // OpenMP [2.14.3.6, reduction clause]
8464 // C
8465 // reduction-identifier is either an identifier or one of the following
8466 // operators: +, -, *, &, |, ^, && and ||
8467 // C++
8468 // reduction-identifier is either an id-expression or one of the following
8469 // operators: +, -, *, &, |, ^, && and ||
8470 // FIXME: Only 'min' and 'max' identifiers are supported for now.
8471 switch (OOK) {
8472 case OO_Plus:
8473 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008474 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008475 break;
8476 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008477 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008478 break;
8479 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008480 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008481 break;
8482 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008483 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008484 break;
8485 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008486 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008487 break;
8488 case OO_AmpAmp:
8489 BOK = BO_LAnd;
8490 break;
8491 case OO_PipePipe:
8492 BOK = BO_LOr;
8493 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008494 case OO_New:
8495 case OO_Delete:
8496 case OO_Array_New:
8497 case OO_Array_Delete:
8498 case OO_Slash:
8499 case OO_Percent:
8500 case OO_Tilde:
8501 case OO_Exclaim:
8502 case OO_Equal:
8503 case OO_Less:
8504 case OO_Greater:
8505 case OO_LessEqual:
8506 case OO_GreaterEqual:
8507 case OO_PlusEqual:
8508 case OO_MinusEqual:
8509 case OO_StarEqual:
8510 case OO_SlashEqual:
8511 case OO_PercentEqual:
8512 case OO_CaretEqual:
8513 case OO_AmpEqual:
8514 case OO_PipeEqual:
8515 case OO_LessLess:
8516 case OO_GreaterGreater:
8517 case OO_LessLessEqual:
8518 case OO_GreaterGreaterEqual:
8519 case OO_EqualEqual:
8520 case OO_ExclaimEqual:
8521 case OO_PlusPlus:
8522 case OO_MinusMinus:
8523 case OO_Comma:
8524 case OO_ArrowStar:
8525 case OO_Arrow:
8526 case OO_Call:
8527 case OO_Subscript:
8528 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +00008529 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008530 case NUM_OVERLOADED_OPERATORS:
8531 llvm_unreachable("Unexpected reduction identifier");
8532 case OO_None:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008533 if (auto II = DN.getAsIdentifierInfo()) {
8534 if (II->isStr("max"))
8535 BOK = BO_GT;
8536 else if (II->isStr("min"))
8537 BOK = BO_LT;
8538 }
8539 break;
8540 }
8541 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008542 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +00008543 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008544 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +00008545
8546 SmallVector<Expr *, 8> Vars;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008547 SmallVector<Expr *, 8> Privates;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008548 SmallVector<Expr *, 8> LHSs;
8549 SmallVector<Expr *, 8> RHSs;
8550 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev61205072016-03-02 04:57:40 +00008551 SmallVector<Decl *, 4> ExprCaptures;
8552 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008553 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
8554 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008555 for (auto RefExpr : VarList) {
8556 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +00008557 // OpenMP [2.1, C/C++]
8558 // A list item is a variable or array section, subject to the restrictions
8559 // specified in Section 2.4 on page 42 and in each of the sections
8560 // describing clauses and directives for which a list appears.
8561 // OpenMP [2.14.3.3, Restrictions, p.1]
8562 // A variable that is part of another variable (as an array or
8563 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008564 if (!FirstIter && IR != ER)
8565 ++IR;
8566 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008567 SourceLocation ELoc;
8568 SourceRange ERange;
8569 Expr *SimpleRefExpr = RefExpr;
8570 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
8571 /*AllowArraySection=*/true);
8572 if (Res.second) {
8573 // It will be analyzed later.
8574 Vars.push_back(RefExpr);
8575 Privates.push_back(nullptr);
8576 LHSs.push_back(nullptr);
8577 RHSs.push_back(nullptr);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008578 // Try to find 'declare reduction' corresponding construct before using
8579 // builtin/overloaded operators.
8580 QualType Type = Context.DependentTy;
8581 CXXCastPath BasePath;
8582 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8583 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8584 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8585 if (CurContext->isDependentContext() &&
8586 (DeclareReductionRef.isUnset() ||
8587 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
8588 ReductionOps.push_back(DeclareReductionRef.get());
8589 else
8590 ReductionOps.push_back(nullptr);
Alexey Bataevc5e02582014-06-16 07:08:35 +00008591 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008592 ValueDecl *D = Res.first;
8593 if (!D)
8594 continue;
8595
Alexey Bataeva1764212015-09-30 09:22:36 +00008596 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008597 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
8598 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
8599 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +00008600 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008601 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008602 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
8603 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
8604 Type = ATy->getElementType();
8605 else
8606 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00008607 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00008608 } else
8609 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
8610 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +00008611
Alexey Bataevc5e02582014-06-16 07:08:35 +00008612 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
8613 // A variable that appears in a private clause must not have an incomplete
8614 // type or a reference type.
8615 if (RequireCompleteType(ELoc, Type,
8616 diag::err_omp_reduction_incomplete_type))
8617 continue;
8618 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +00008619 // A list item that appears in a reduction clause must not be
8620 // const-qualified.
8621 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008622 Diag(ELoc, diag::err_omp_const_reduction_list_item)
Alexey Bataevc5e02582014-06-16 07:08:35 +00008623 << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008624 if (!ASE && !OASE) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008625 bool IsDecl = !VD ||
8626 VD->isThisDeclarationADefinition(Context) ==
8627 VarDecl::DeclarationOnly;
8628 Diag(D->getLocation(),
Alexey Bataeva1764212015-09-30 09:22:36 +00008629 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +00008630 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +00008631 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008632 continue;
8633 }
8634 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
8635 // If a list-item is a reference type then it must bind to the same object
8636 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008637 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008638 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +00008639 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataeva1764212015-09-30 09:22:36 +00008640 DSARefChecker Check(DSAStack);
8641 if (Check.Visit(VDDef->getInit())) {
8642 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
8643 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
8644 continue;
8645 }
Alexey Bataevc5e02582014-06-16 07:08:35 +00008646 }
8647 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008648
Alexey Bataevc5e02582014-06-16 07:08:35 +00008649 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
8650 // in a Construct]
8651 // Variables with the predetermined data-sharing attributes may not be
8652 // listed in data-sharing attributes clauses, except for the cases
8653 // listed below. For these exceptions only, listing a predetermined
8654 // variable in a data-sharing attribute clause is allowed and overrides
8655 // the variable's predetermined data-sharing attributes.
8656 // OpenMP [2.14.3.6, Restrictions, p.3]
8657 // Any number of reduction clauses can be specified on the directive,
8658 // but a list item can appear only once in the reduction clauses for that
8659 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +00008660 DSAStackTy::DSAVarData DVar;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008661 DVar = DSAStack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008662 if (DVar.CKind == OMPC_reduction) {
8663 Diag(ELoc, diag::err_omp_once_referenced)
8664 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008665 if (DVar.RefExpr)
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008666 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008667 } else if (DVar.CKind != OMPC_unknown) {
8668 Diag(ELoc, diag::err_omp_wrong_dsa)
8669 << getOpenMPClauseName(DVar.CKind)
8670 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008671 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008672 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008673 }
8674
8675 // OpenMP [2.14.3.6, Restrictions, p.1]
8676 // A list item that appears in a reduction clause of a worksharing
8677 // construct must be shared in the parallel regions to which any of the
8678 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008679 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
8680 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00008681 !isOpenMPParallelDirective(CurrDir) &&
8682 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008683 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008684 if (DVar.CKind != OMPC_shared) {
8685 Diag(ELoc, diag::err_omp_required_access)
8686 << getOpenMPClauseName(OMPC_reduction)
8687 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev60da77e2016-02-29 05:54:20 +00008688 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008689 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00008690 }
8691 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008692
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008693 // Try to find 'declare reduction' corresponding construct before using
8694 // builtin/overloaded operators.
8695 CXXCastPath BasePath;
8696 ExprResult DeclareReductionRef = buildDeclareReductionRef(
8697 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec,
8698 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
8699 if (DeclareReductionRef.isInvalid())
8700 continue;
8701 if (CurContext->isDependentContext() &&
8702 (DeclareReductionRef.isUnset() ||
8703 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
8704 Vars.push_back(RefExpr);
8705 Privates.push_back(nullptr);
8706 LHSs.push_back(nullptr);
8707 RHSs.push_back(nullptr);
8708 ReductionOps.push_back(DeclareReductionRef.get());
8709 continue;
8710 }
8711 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
8712 // Not allowed reduction identifier is found.
8713 Diag(ReductionId.getLocStart(),
8714 diag::err_omp_unknown_reduction_identifier)
8715 << Type << ReductionIdRange;
8716 continue;
8717 }
8718
8719 // OpenMP [2.14.3.6, reduction clause, Restrictions]
8720 // The type of a list item that appears in a reduction clause must be valid
8721 // for the reduction-identifier. For a max or min reduction in C, the type
8722 // of the list item must be an allowed arithmetic data type: char, int,
8723 // float, double, or _Bool, possibly modified with long, short, signed, or
8724 // unsigned. For a max or min reduction in C++, the type of the list item
8725 // must be an allowed arithmetic data type: char, wchar_t, int, float,
8726 // double, or bool, possibly modified with long, short, signed, or unsigned.
8727 if (DeclareReductionRef.isUnset()) {
8728 if ((BOK == BO_GT || BOK == BO_LT) &&
8729 !(Type->isScalarType() ||
8730 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
8731 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
8732 << getLangOpts().CPlusPlus;
8733 if (!ASE && !OASE) {
8734 bool IsDecl = !VD ||
8735 VD->isThisDeclarationADefinition(Context) ==
8736 VarDecl::DeclarationOnly;
8737 Diag(D->getLocation(),
8738 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8739 << D;
8740 }
8741 continue;
8742 }
8743 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
8744 !getLangOpts().CPlusPlus && Type->isFloatingType()) {
8745 Diag(ELoc, diag::err_omp_clause_floating_type_arg);
8746 if (!ASE && !OASE) {
8747 bool IsDecl = !VD ||
8748 VD->isThisDeclarationADefinition(Context) ==
8749 VarDecl::DeclarationOnly;
8750 Diag(D->getLocation(),
8751 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8752 << D;
8753 }
8754 continue;
8755 }
8756 }
8757
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008758 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008759 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +00008760 D->hasAttrs() ? &D->getAttrs() : nullptr);
8761 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(),
8762 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008763 auto PrivateTy = Type;
Alexey Bataev1189bd02016-01-26 12:20:39 +00008764 if (OASE ||
Alexey Bataev60da77e2016-02-29 05:54:20 +00008765 (!ASE &&
8766 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
David Majnemer9d168222016-08-05 17:44:54 +00008767 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008768 // Create pseudo array type for private copy. The size for this array will
8769 // be generated during codegen.
8770 // For array subscripts or single variables Private Ty is the same as Type
8771 // (type of the variable or single array element).
8772 PrivateTy = Context.getVariableArrayType(
8773 Type, new (Context) OpaqueValueExpr(SourceLocation(),
8774 Context.getSizeType(), VK_RValue),
8775 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +00008776 } else if (!ASE && !OASE &&
8777 Context.getAsArrayType(D->getType().getNonReferenceType()))
8778 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008779 // Private copy.
Alexey Bataev60da77e2016-02-29 05:54:20 +00008780 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(),
8781 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008782 // Add initializer for private variable.
8783 Expr *Init = nullptr;
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008784 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
8785 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
8786 if (DeclareReductionRef.isUsable()) {
8787 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
8788 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
8789 if (DRD->getInitializer()) {
8790 Init = DRDRef;
8791 RHSVD->setInit(DRDRef);
8792 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008793 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008794 } else {
8795 switch (BOK) {
8796 case BO_Add:
8797 case BO_Xor:
8798 case BO_Or:
8799 case BO_LOr:
8800 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
8801 if (Type->isScalarType() || Type->isAnyComplexType())
8802 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
8803 break;
8804 case BO_Mul:
8805 case BO_LAnd:
8806 if (Type->isScalarType() || Type->isAnyComplexType()) {
8807 // '*' and '&&' reduction ops - initializer is '1'.
8808 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +00008809 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008810 break;
8811 case BO_And: {
8812 // '&' reduction op - initializer is '~0'.
8813 QualType OrigType = Type;
8814 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
8815 Type = ComplexTy->getElementType();
8816 if (Type->isRealFloatingType()) {
8817 llvm::APFloat InitValue =
8818 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
8819 /*isIEEE=*/true);
8820 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8821 Type, ELoc);
8822 } else if (Type->isScalarType()) {
8823 auto Size = Context.getTypeSize(Type);
8824 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
8825 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
8826 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8827 }
8828 if (Init && OrigType->isAnyComplexType()) {
8829 // Init = 0xFFFF + 0xFFFFi;
8830 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
8831 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
8832 }
8833 Type = OrigType;
8834 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008835 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008836 case BO_LT:
8837 case BO_GT: {
8838 // 'min' reduction op - initializer is 'Largest representable number in
8839 // the reduction list item type'.
8840 // 'max' reduction op - initializer is 'Least representable number in
8841 // the reduction list item type'.
8842 if (Type->isIntegerType() || Type->isPointerType()) {
8843 bool IsSigned = Type->hasSignedIntegerRepresentation();
8844 auto Size = Context.getTypeSize(Type);
8845 QualType IntTy =
8846 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
8847 llvm::APInt InitValue =
8848 (BOK != BO_LT)
8849 ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
8850 : llvm::APInt::getMinValue(Size)
8851 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
8852 : llvm::APInt::getMaxValue(Size);
8853 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
8854 if (Type->isPointerType()) {
8855 // Cast to pointer type.
8856 auto CastExpr = BuildCStyleCastExpr(
8857 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
8858 SourceLocation(), Init);
8859 if (CastExpr.isInvalid())
8860 continue;
8861 Init = CastExpr.get();
8862 }
8863 } else if (Type->isRealFloatingType()) {
8864 llvm::APFloat InitValue = llvm::APFloat::getLargest(
8865 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
8866 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
8867 Type, ELoc);
8868 }
8869 break;
8870 }
8871 case BO_PtrMemD:
8872 case BO_PtrMemI:
8873 case BO_MulAssign:
8874 case BO_Div:
8875 case BO_Rem:
8876 case BO_Sub:
8877 case BO_Shl:
8878 case BO_Shr:
8879 case BO_LE:
8880 case BO_GE:
8881 case BO_EQ:
8882 case BO_NE:
8883 case BO_AndAssign:
8884 case BO_XorAssign:
8885 case BO_OrAssign:
8886 case BO_Assign:
8887 case BO_AddAssign:
8888 case BO_SubAssign:
8889 case BO_DivAssign:
8890 case BO_RemAssign:
8891 case BO_ShlAssign:
8892 case BO_ShrAssign:
8893 case BO_Comma:
8894 llvm_unreachable("Unexpected reduction operation");
8895 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008896 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008897 if (Init && DeclareReductionRef.isUnset()) {
Richard Smith3beb7c62017-01-12 02:27:38 +00008898 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008899 } else if (!Init)
Richard Smith3beb7c62017-01-12 02:27:38 +00008900 ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008901 if (RHSVD->isInvalidDecl())
8902 continue;
8903 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008904 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
8905 << ReductionIdRange;
Alexey Bataev60da77e2016-02-29 05:54:20 +00008906 bool IsDecl =
8907 !VD ||
8908 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
8909 Diag(D->getLocation(),
8910 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
8911 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008912 continue;
8913 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008914 // Store initializer for single element in private copy. Will be used during
8915 // codegen.
8916 PrivateVD->setInit(RHSVD->getInit());
8917 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008918 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008919 ExprResult ReductionOp;
8920 if (DeclareReductionRef.isUsable()) {
8921 QualType RedTy = DeclareReductionRef.get()->getType();
8922 QualType PtrRedTy = Context.getPointerType(RedTy);
8923 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
8924 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
8925 if (!BasePath.empty()) {
8926 LHS = DefaultLvalueConversion(LHS.get());
8927 RHS = DefaultLvalueConversion(RHS.get());
8928 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8929 CK_UncheckedDerivedToBase, LHS.get(),
8930 &BasePath, LHS.get()->getValueKind());
8931 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
8932 CK_UncheckedDerivedToBase, RHS.get(),
8933 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008934 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +00008935 FunctionProtoType::ExtProtoInfo EPI;
8936 QualType Params[] = {PtrRedTy, PtrRedTy};
8937 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
8938 auto *OVE = new (Context) OpaqueValueExpr(
8939 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
8940 DefaultLvalueConversion(DeclareReductionRef.get()).get());
8941 Expr *Args[] = {LHS.get(), RHS.get()};
8942 ReductionOp = new (Context)
8943 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
8944 } else {
8945 ReductionOp = BuildBinOp(DSAStack->getCurScope(),
8946 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
8947 if (ReductionOp.isUsable()) {
8948 if (BOK != BO_LT && BOK != BO_GT) {
8949 ReductionOp =
8950 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8951 BO_Assign, LHSDRE, ReductionOp.get());
8952 } else {
8953 auto *ConditionalOp = new (Context) ConditionalOperator(
8954 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
8955 RHSDRE, Type, VK_LValue, OK_Ordinary);
8956 ReductionOp =
8957 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
8958 BO_Assign, LHSDRE, ConditionalOp);
8959 }
8960 ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
8961 }
8962 if (ReductionOp.isInvalid())
8963 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008964 }
8965
Alexey Bataev60da77e2016-02-29 05:54:20 +00008966 DeclRefExpr *Ref = nullptr;
8967 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00008968 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00008969 if (ASE || OASE) {
8970 TransformExprToCaptures RebuildToCapture(*this, D);
8971 VarsExpr =
8972 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
8973 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +00008974 } else {
8975 VarsExpr = Ref =
8976 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +00008977 }
8978 if (!IsOpenMPCapturedDecl(D)) {
8979 ExprCaptures.push_back(Ref->getDecl());
8980 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
8981 ExprResult RefRes = DefaultLvalueConversion(Ref);
8982 if (!RefRes.isUsable())
8983 continue;
8984 ExprResult PostUpdateRes =
8985 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
8986 SimpleRefExpr, RefRes.get());
8987 if (!PostUpdateRes.isUsable())
8988 continue;
8989 ExprPostUpdates.push_back(
8990 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +00008991 }
8992 }
Alexey Bataev60da77e2016-02-29 05:54:20 +00008993 }
8994 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
8995 Vars.push_back(VarsExpr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00008996 Privates.push_back(PrivateDRE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00008997 LHSs.push_back(LHSDRE);
8998 RHSs.push_back(RHSDRE);
8999 ReductionOps.push_back(ReductionOp.get());
Alexey Bataevc5e02582014-06-16 07:08:35 +00009000 }
9001
9002 if (Vars.empty())
9003 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +00009004
Alexey Bataevc5e02582014-06-16 07:08:35 +00009005 return OMPReductionClause::Create(
9006 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009007 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009008 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures),
9009 buildPostUpdate(*this, ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +00009010}
9011
Alexey Bataevecba70f2016-04-12 11:02:11 +00009012bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
9013 SourceLocation LinLoc) {
9014 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
9015 LinKind == OMPC_LINEAR_unknown) {
9016 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
9017 return true;
9018 }
9019 return false;
9020}
9021
9022bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
9023 OpenMPLinearClauseKind LinKind,
9024 QualType Type) {
9025 auto *VD = dyn_cast_or_null<VarDecl>(D);
9026 // A variable must not have an incomplete type or a reference type.
9027 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
9028 return true;
9029 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
9030 !Type->isReferenceType()) {
9031 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
9032 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
9033 return true;
9034 }
9035 Type = Type.getNonReferenceType();
9036
9037 // A list item must not be const-qualified.
9038 if (Type.isConstant(Context)) {
9039 Diag(ELoc, diag::err_omp_const_variable)
9040 << getOpenMPClauseName(OMPC_linear);
9041 if (D) {
9042 bool IsDecl =
9043 !VD ||
9044 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9045 Diag(D->getLocation(),
9046 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9047 << D;
9048 }
9049 return true;
9050 }
9051
9052 // A list item must be of integral or pointer type.
9053 Type = Type.getUnqualifiedType().getCanonicalType();
9054 const auto *Ty = Type.getTypePtrOrNull();
9055 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
9056 !Ty->isPointerType())) {
9057 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
9058 if (D) {
9059 bool IsDecl =
9060 !VD ||
9061 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9062 Diag(D->getLocation(),
9063 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9064 << D;
9065 }
9066 return true;
9067 }
9068 return false;
9069}
9070
Alexey Bataev182227b2015-08-20 10:54:39 +00009071OMPClause *Sema::ActOnOpenMPLinearClause(
9072 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
9073 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
9074 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009075 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009076 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +00009077 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009078 SmallVector<Decl *, 4> ExprCaptures;
9079 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009080 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +00009081 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +00009082 for (auto &RefExpr : VarList) {
9083 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009084 SourceLocation ELoc;
9085 SourceRange ERange;
9086 Expr *SimpleRefExpr = RefExpr;
9087 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9088 /*AllowArraySection=*/false);
9089 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +00009090 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009091 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009092 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +00009093 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +00009094 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009095 ValueDecl *D = Res.first;
9096 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +00009097 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +00009098
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009099 QualType Type = D->getType();
9100 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +00009101
9102 // OpenMP [2.14.3.7, linear clause]
9103 // A list-item cannot appear in more than one linear clause.
9104 // A list-item that appears in a linear clause cannot appear in any
9105 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009106 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +00009107 if (DVar.RefExpr) {
9108 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9109 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009110 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +00009111 continue;
9112 }
9113
Alexey Bataevecba70f2016-04-12 11:02:11 +00009114 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +00009115 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00009116 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +00009117
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009118 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009119 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
9120 D->hasAttrs() ? &D->getAttrs() : nullptr);
9121 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009122 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009123 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009124 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009125 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009126 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +00009127 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
9128 if (!IsOpenMPCapturedDecl(D)) {
9129 ExprCaptures.push_back(Ref->getDecl());
9130 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
9131 ExprResult RefRes = DefaultLvalueConversion(Ref);
9132 if (!RefRes.isUsable())
9133 continue;
9134 ExprResult PostUpdateRes =
9135 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
9136 SimpleRefExpr, RefRes.get());
9137 if (!PostUpdateRes.isUsable())
9138 continue;
9139 ExprPostUpdates.push_back(
9140 IgnoredValueConversions(PostUpdateRes.get()).get());
9141 }
9142 }
9143 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009144 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009145 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009146 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009147 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009148 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009149 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009150 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
9151
9152 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009153 Vars.push_back((VD || CurContext->isDependentContext())
9154 ? RefExpr->IgnoreParens()
9155 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009156 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +00009157 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +00009158 }
9159
9160 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009161 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009162
9163 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +00009164 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +00009165 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
9166 !Step->isInstantiationDependent() &&
9167 !Step->containsUnexpandedParameterPack()) {
9168 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009169 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +00009170 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009171 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009172 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +00009173
Alexander Musman3276a272015-03-21 10:12:56 +00009174 // Build var to save the step value.
9175 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009176 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +00009177 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +00009178 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +00009179 ExprResult CalcStep =
9180 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009181 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +00009182
Alexander Musman8dba6642014-04-22 13:09:42 +00009183 // Warn about zero linear step (it would be probably better specified as
9184 // making corresponding variables 'const').
9185 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +00009186 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
9187 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +00009188 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
9189 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +00009190 if (!IsConstant && CalcStep.isUsable()) {
9191 // Calculate the step beforehand instead of doing this on each iteration.
9192 // (This is not used if the number of iterations may be kfold-ed).
9193 CalcStepExpr = CalcStep.get();
9194 }
Alexander Musman8dba6642014-04-22 13:09:42 +00009195 }
9196
Alexey Bataev182227b2015-08-20 10:54:39 +00009197 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
9198 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009199 StepExpr, CalcStepExpr,
9200 buildPreInits(Context, ExprCaptures),
9201 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +00009202}
9203
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009204static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
9205 Expr *NumIterations, Sema &SemaRef,
9206 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +00009207 // Walk the vars and build update/final expressions for the CodeGen.
9208 SmallVector<Expr *, 8> Updates;
9209 SmallVector<Expr *, 8> Finals;
9210 Expr *Step = Clause.getStep();
9211 Expr *CalcStep = Clause.getCalcStep();
9212 // OpenMP [2.14.3.7, linear clause]
9213 // If linear-step is not specified it is assumed to be 1.
9214 if (Step == nullptr)
9215 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009216 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +00009217 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +00009218 }
Alexander Musman3276a272015-03-21 10:12:56 +00009219 bool HasErrors = false;
9220 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009221 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009222 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +00009223 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009224 SourceLocation ELoc;
9225 SourceRange ERange;
9226 Expr *SimpleRefExpr = RefExpr;
9227 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
9228 /*AllowArraySection=*/false);
9229 ValueDecl *D = Res.first;
9230 if (Res.second || !D) {
9231 Updates.push_back(nullptr);
9232 Finals.push_back(nullptr);
9233 HasErrors = true;
9234 continue;
9235 }
9236 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
9237 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts())
9238 ->getMemberDecl();
9239 }
9240 auto &&Info = Stack->isLoopControlVariable(D);
Alexander Musman3276a272015-03-21 10:12:56 +00009241 Expr *InitExpr = *CurInit;
9242
9243 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +00009244 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +00009245 Expr *CapturedRef;
9246 if (LinKind == OMPC_LINEAR_uval)
9247 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
9248 else
9249 CapturedRef =
9250 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
9251 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
9252 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009253
9254 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009255 ExprResult Update;
9256 if (!Info.first) {
9257 Update =
9258 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
9259 InitExpr, IV, Step, /* Subtract */ false);
9260 } else
9261 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009262 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
9263 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +00009264
9265 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009266 ExprResult Final;
9267 if (!Info.first) {
9268 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
9269 InitExpr, NumIterations, Step,
9270 /* Subtract */ false);
9271 } else
9272 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009273 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
9274 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009275
Alexander Musman3276a272015-03-21 10:12:56 +00009276 if (!Update.isUsable() || !Final.isUsable()) {
9277 Updates.push_back(nullptr);
9278 Finals.push_back(nullptr);
9279 HasErrors = true;
9280 } else {
9281 Updates.push_back(Update.get());
9282 Finals.push_back(Final.get());
9283 }
Richard Trieucc3949d2016-02-18 22:34:54 +00009284 ++CurInit;
9285 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +00009286 }
9287 Clause.setUpdates(Updates);
9288 Clause.setFinals(Finals);
9289 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +00009290}
9291
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009292OMPClause *Sema::ActOnOpenMPAlignedClause(
9293 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
9294 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
9295
9296 SmallVector<Expr *, 8> Vars;
9297 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +00009298 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9299 SourceLocation ELoc;
9300 SourceRange ERange;
9301 Expr *SimpleRefExpr = RefExpr;
9302 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9303 /*AllowArraySection=*/false);
9304 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009305 // It will be analyzed later.
9306 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009307 }
Alexey Bataev1efd1662016-03-29 10:59:56 +00009308 ValueDecl *D = Res.first;
9309 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009310 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009311
Alexey Bataev1efd1662016-03-29 10:59:56 +00009312 QualType QType = D->getType();
9313 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009314
9315 // OpenMP [2.8.1, simd construct, Restrictions]
9316 // The type of list items appearing in the aligned clause must be
9317 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009318 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009319 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +00009320 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009321 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009322 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009323 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +00009324 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009325 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +00009326 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009327 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +00009328 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009329 continue;
9330 }
9331
9332 // OpenMP [2.8.1, simd construct, Restrictions]
9333 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +00009334 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00009335 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009336 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
9337 << getOpenMPClauseName(OMPC_aligned);
9338 continue;
9339 }
9340
Alexey Bataev1efd1662016-03-29 10:59:56 +00009341 DeclRefExpr *Ref = nullptr;
9342 if (!VD && IsOpenMPCapturedDecl(D))
9343 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
9344 Vars.push_back(DefaultFunctionArrayConversion(
9345 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
9346 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009347 }
9348
9349 // OpenMP [2.8.1, simd construct, Description]
9350 // The parameter of the aligned clause, alignment, must be a constant
9351 // positive integer expression.
9352 // If no optional parameter is specified, implementation-defined default
9353 // alignments for SIMD instructions on the target platforms are assumed.
9354 if (Alignment != nullptr) {
9355 ExprResult AlignResult =
9356 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
9357 if (AlignResult.isInvalid())
9358 return nullptr;
9359 Alignment = AlignResult.get();
9360 }
9361 if (Vars.empty())
9362 return nullptr;
9363
9364 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
9365 EndLoc, Vars, Alignment);
9366}
9367
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009368OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9369 SourceLocation StartLoc,
9370 SourceLocation LParenLoc,
9371 SourceLocation EndLoc) {
9372 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009373 SmallVector<Expr *, 8> SrcExprs;
9374 SmallVector<Expr *, 8> DstExprs;
9375 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +00009376 for (auto &RefExpr : VarList) {
9377 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
9378 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009379 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009380 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009381 SrcExprs.push_back(nullptr);
9382 DstExprs.push_back(nullptr);
9383 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009384 continue;
9385 }
9386
Alexey Bataeved09d242014-05-28 05:53:51 +00009387 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009388 // OpenMP [2.1, C/C++]
9389 // A list item is a variable name.
9390 // OpenMP [2.14.4.1, Restrictions, p.1]
9391 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +00009392 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009393 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009394 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
9395 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009396 continue;
9397 }
9398
9399 Decl *D = DE->getDecl();
9400 VarDecl *VD = cast<VarDecl>(D);
9401
9402 QualType Type = VD->getType();
9403 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
9404 // It will be analyzed later.
9405 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009406 SrcExprs.push_back(nullptr);
9407 DstExprs.push_back(nullptr);
9408 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009409 continue;
9410 }
9411
9412 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
9413 // A list item that appears in a copyin clause must be threadprivate.
9414 if (!DSAStack->isThreadPrivate(VD)) {
9415 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +00009416 << getOpenMPClauseName(OMPC_copyin)
9417 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009418 continue;
9419 }
9420
9421 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9422 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +00009423 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009424 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009425 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009426 auto *SrcVD =
9427 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
9428 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009429 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009430 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
9431 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009432 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
9433 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009434 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009435 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009436 // For arrays generate assignment operation for single element and replace
9437 // it by the original array element in CodeGen.
9438 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
9439 PseudoDstExpr, PseudoSrcExpr);
9440 if (AssignmentOp.isInvalid())
9441 continue;
9442 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
9443 /*DiscardedValue=*/true);
9444 if (AssignmentOp.isInvalid())
9445 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009446
9447 DSAStack->addDSA(VD, DE, OMPC_copyin);
9448 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009449 SrcExprs.push_back(PseudoSrcExpr);
9450 DstExprs.push_back(PseudoDstExpr);
9451 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009452 }
9453
Alexey Bataeved09d242014-05-28 05:53:51 +00009454 if (Vars.empty())
9455 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009456
Alexey Bataevf56f98c2015-04-16 05:39:01 +00009457 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9458 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009459}
9460
Alexey Bataevbae9a792014-06-27 10:37:06 +00009461OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9462 SourceLocation StartLoc,
9463 SourceLocation LParenLoc,
9464 SourceLocation EndLoc) {
9465 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +00009466 SmallVector<Expr *, 8> SrcExprs;
9467 SmallVector<Expr *, 8> DstExprs;
9468 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009469 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009470 assert(RefExpr && "NULL expr in OpenMP linear clause.");
9471 SourceLocation ELoc;
9472 SourceRange ERange;
9473 Expr *SimpleRefExpr = RefExpr;
9474 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
9475 /*AllowArraySection=*/false);
9476 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009477 // It will be analyzed later.
9478 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009479 SrcExprs.push_back(nullptr);
9480 DstExprs.push_back(nullptr);
9481 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009482 }
Alexey Bataeve122da12016-03-17 10:50:17 +00009483 ValueDecl *D = Res.first;
9484 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +00009485 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009486
Alexey Bataeve122da12016-03-17 10:50:17 +00009487 QualType Type = D->getType();
9488 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009489
9490 // OpenMP [2.14.4.2, Restrictions, p.2]
9491 // A list item that appears in a copyprivate clause may not appear in a
9492 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +00009493 if (!VD || !DSAStack->isThreadPrivate(VD)) {
9494 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +00009495 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
9496 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +00009497 Diag(ELoc, diag::err_omp_wrong_dsa)
9498 << getOpenMPClauseName(DVar.CKind)
9499 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +00009500 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009501 continue;
9502 }
9503
9504 // OpenMP [2.11.4.2, Restrictions, p.1]
9505 // All list items that appear in a copyprivate clause must be either
9506 // threadprivate or private in the enclosing context.
9507 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +00009508 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009509 if (DVar.CKind == OMPC_shared) {
9510 Diag(ELoc, diag::err_omp_required_access)
9511 << getOpenMPClauseName(OMPC_copyprivate)
9512 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +00009513 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009514 continue;
9515 }
9516 }
9517 }
9518
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009519 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009520 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009521 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009522 << getOpenMPClauseName(OMPC_copyprivate) << Type
9523 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009524 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +00009525 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009526 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +00009527 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009528 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +00009529 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +00009530 continue;
9531 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009532
Alexey Bataevbae9a792014-06-27 10:37:06 +00009533 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
9534 // A variable of class type (or array thereof) that appears in a
9535 // copyin clause requires an accessible, unambiguous copy assignment
9536 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009537 Type = Context.getBaseElementType(Type.getNonReferenceType())
9538 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +00009539 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009540 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
9541 D->hasAttrs() ? &D->getAttrs() : nullptr);
9542 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00009543 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +00009544 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
9545 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +00009546 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +00009547 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009548 PseudoDstExpr, PseudoSrcExpr);
9549 if (AssignmentOp.isInvalid())
9550 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +00009551 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +00009552 /*DiscardedValue=*/true);
9553 if (AssignmentOp.isInvalid())
9554 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009555
9556 // No need to mark vars as copyprivate, they are already threadprivate or
9557 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +00009558 assert(VD || IsOpenMPCapturedDecl(D));
9559 Vars.push_back(
9560 VD ? RefExpr->IgnoreParens()
9561 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +00009562 SrcExprs.push_back(PseudoSrcExpr);
9563 DstExprs.push_back(PseudoDstExpr);
9564 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +00009565 }
9566
9567 if (Vars.empty())
9568 return nullptr;
9569
Alexey Bataeva63048e2015-03-23 06:18:07 +00009570 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9571 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +00009572}
9573
Alexey Bataev6125da92014-07-21 11:26:11 +00009574OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9575 SourceLocation StartLoc,
9576 SourceLocation LParenLoc,
9577 SourceLocation EndLoc) {
9578 if (VarList.empty())
9579 return nullptr;
9580
9581 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
9582}
Alexey Bataevdea47612014-07-23 07:46:59 +00009583
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009584OMPClause *
9585Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
9586 SourceLocation DepLoc, SourceLocation ColonLoc,
9587 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9588 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009589 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009590 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +00009591 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009592 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +00009593 return nullptr;
9594 }
9595 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009596 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
9597 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009598 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009599 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009600 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
9601 /*Last=*/OMPC_DEPEND_unknown, Except)
9602 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009603 return nullptr;
9604 }
9605 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +00009606 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009607 llvm::APSInt DepCounter(/*BitWidth=*/32);
9608 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
9609 if (DepKind == OMPC_DEPEND_sink) {
9610 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
9611 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
9612 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009613 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009614 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009615 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
9616 DSAStack->getParentOrderedRegionParam()) {
9617 for (auto &RefExpr : VarList) {
9618 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +00009619 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009620 // It will be analyzed later.
9621 Vars.push_back(RefExpr);
9622 continue;
9623 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009624
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009625 SourceLocation ELoc = RefExpr->getExprLoc();
9626 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
9627 if (DepKind == OMPC_DEPEND_sink) {
9628 if (DepCounter >= TotalDepCount) {
9629 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
9630 continue;
9631 }
9632 ++DepCounter;
9633 // OpenMP [2.13.9, Summary]
9634 // depend(dependence-type : vec), where dependence-type is:
9635 // 'sink' and where vec is the iteration vector, which has the form:
9636 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
9637 // where n is the value specified by the ordered clause in the loop
9638 // directive, xi denotes the loop iteration variable of the i-th nested
9639 // loop associated with the loop directive, and di is a constant
9640 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +00009641 if (CurContext->isDependentContext()) {
9642 // It will be analyzed later.
9643 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009644 continue;
9645 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009646 SimpleExpr = SimpleExpr->IgnoreImplicit();
9647 OverloadedOperatorKind OOK = OO_None;
9648 SourceLocation OOLoc;
9649 Expr *LHS = SimpleExpr;
9650 Expr *RHS = nullptr;
9651 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
9652 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
9653 OOLoc = BO->getOperatorLoc();
9654 LHS = BO->getLHS()->IgnoreParenImpCasts();
9655 RHS = BO->getRHS()->IgnoreParenImpCasts();
9656 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
9657 OOK = OCE->getOperator();
9658 OOLoc = OCE->getOperatorLoc();
9659 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9660 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
9661 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
9662 OOK = MCE->getMethodDecl()
9663 ->getNameInfo()
9664 .getName()
9665 .getCXXOverloadedOperator();
9666 OOLoc = MCE->getCallee()->getExprLoc();
9667 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
9668 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
9669 }
9670 SourceLocation ELoc;
9671 SourceRange ERange;
9672 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
9673 /*AllowArraySection=*/false);
9674 if (Res.second) {
9675 // It will be analyzed later.
9676 Vars.push_back(RefExpr);
9677 }
9678 ValueDecl *D = Res.first;
9679 if (!D)
9680 continue;
9681
9682 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
9683 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
9684 continue;
9685 }
9686 if (RHS) {
9687 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
9688 RHS, OMPC_depend, /*StrictlyPositive=*/false);
9689 if (RHSRes.isInvalid())
9690 continue;
9691 }
9692 if (!CurContext->isDependentContext() &&
9693 DSAStack->getParentOrderedRegionParam() &&
9694 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
9695 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
9696 << DSAStack->getParentLoopControlVariable(
9697 DepCounter.getZExtValue());
9698 continue;
9699 }
9700 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009701 } else {
9702 // OpenMP [2.11.1.1, Restrictions, p.3]
9703 // A variable that is part of another variable (such as a field of a
9704 // structure) but is not an array element or an array section cannot
9705 // appear in a depend clause.
9706 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
9707 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
9708 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
9709 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
9710 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
Alexey Bataev31300ed2016-02-04 11:27:03 +00009711 (ASE &&
9712 !ASE->getBase()
9713 ->getType()
9714 .getNonReferenceType()
9715 ->isPointerType() &&
9716 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009717 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
9718 << 0 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009719 continue;
9720 }
9721 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009722 Vars.push_back(RefExpr->IgnoreParenImpCasts());
9723 }
9724
9725 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
9726 TotalDepCount > VarList.size() &&
9727 DSAStack->getParentOrderedRegionParam()) {
9728 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
9729 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
9730 }
9731 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
9732 Vars.empty())
9733 return nullptr;
9734 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009735 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
9736 DepKind, DepLoc, ColonLoc, Vars);
9737 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
9738 DSAStack->addDoacrossDependClause(C, OpsOffs);
9739 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009740}
Michael Wonge710d542015-08-07 16:16:36 +00009741
9742OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9743 SourceLocation LParenLoc,
9744 SourceLocation EndLoc) {
9745 Expr *ValExpr = Device;
Michael Wonge710d542015-08-07 16:16:36 +00009746
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009747 // OpenMP [2.9.1, Restrictions]
9748 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00009749 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
9750 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009751 return nullptr;
9752
Michael Wonge710d542015-08-07 16:16:36 +00009753 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9754}
Kelvin Li0bff7af2015-11-23 05:32:03 +00009755
9756static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
9757 DSAStackTy *Stack, CXXRecordDecl *RD) {
9758 if (!RD || RD->isInvalidDecl())
9759 return true;
9760
9761 auto QTy = SemaRef.Context.getRecordType(RD);
9762 if (RD->isDynamicClass()) {
9763 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9764 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
9765 return false;
9766 }
9767 auto *DC = RD;
9768 bool IsCorrect = true;
9769 for (auto *I : DC->decls()) {
9770 if (I) {
9771 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
9772 if (MD->isStatic()) {
9773 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9774 SemaRef.Diag(MD->getLocation(),
9775 diag::note_omp_static_member_in_target);
9776 IsCorrect = false;
9777 }
9778 } else if (auto *VD = dyn_cast<VarDecl>(I)) {
9779 if (VD->isStaticDataMember()) {
9780 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
9781 SemaRef.Diag(VD->getLocation(),
9782 diag::note_omp_static_member_in_target);
9783 IsCorrect = false;
9784 }
9785 }
9786 }
9787 }
9788
9789 for (auto &I : RD->bases()) {
9790 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
9791 I.getType()->getAsCXXRecordDecl()))
9792 IsCorrect = false;
9793 }
9794 return IsCorrect;
9795}
9796
9797static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
9798 DSAStackTy *Stack, QualType QTy) {
9799 NamedDecl *ND;
9800 if (QTy->isIncompleteType(&ND)) {
9801 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
9802 return false;
9803 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
David Majnemer9d168222016-08-05 17:44:54 +00009804 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
Kelvin Li0bff7af2015-11-23 05:32:03 +00009805 return false;
9806 }
9807 return true;
9808}
9809
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009810/// \brief Return true if it can be proven that the provided array expression
9811/// (array section or array subscript) does NOT specify the whole size of the
9812/// array whose base type is \a BaseQTy.
9813static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
9814 const Expr *E,
9815 QualType BaseQTy) {
9816 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9817
9818 // If this is an array subscript, it refers to the whole size if the size of
9819 // the dimension is constant and equals 1. Also, an array section assumes the
9820 // format of an array subscript if no colon is used.
9821 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
9822 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9823 return ATy->getSize().getSExtValue() != 1;
9824 // Size can't be evaluated statically.
9825 return false;
9826 }
9827
9828 assert(OASE && "Expecting array section if not an array subscript.");
9829 auto *LowerBound = OASE->getLowerBound();
9830 auto *Length = OASE->getLength();
9831
9832 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +00009833 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009834 if (LowerBound) {
9835 llvm::APSInt ConstLowerBound;
9836 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
9837 return false; // Can't get the integer value as a constant.
9838 if (ConstLowerBound.getSExtValue())
9839 return true;
9840 }
9841
9842 // If we don't have a length we covering the whole dimension.
9843 if (!Length)
9844 return false;
9845
9846 // If the base is a pointer, we don't have a way to get the size of the
9847 // pointee.
9848 if (BaseQTy->isPointerType())
9849 return false;
9850
9851 // We can only check if the length is the same as the size of the dimension
9852 // if we have a constant array.
9853 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
9854 if (!CATy)
9855 return false;
9856
9857 llvm::APSInt ConstLength;
9858 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9859 return false; // Can't get the integer value as a constant.
9860
9861 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
9862}
9863
9864// Return true if it can be proven that the provided array expression (array
9865// section or array subscript) does NOT specify a single element of the array
9866// whose base type is \a BaseQTy.
9867static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +00009868 const Expr *E,
9869 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009870 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
9871
9872 // An array subscript always refer to a single element. Also, an array section
9873 // assumes the format of an array subscript if no colon is used.
9874 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
9875 return false;
9876
9877 assert(OASE && "Expecting array section if not an array subscript.");
9878 auto *Length = OASE->getLength();
9879
9880 // If we don't have a length we have to check if the array has unitary size
9881 // for this dimension. Also, we should always expect a length if the base type
9882 // is pointer.
9883 if (!Length) {
9884 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
9885 return ATy->getSize().getSExtValue() != 1;
9886 // We cannot assume anything.
9887 return false;
9888 }
9889
9890 // Check if the length evaluates to 1.
9891 llvm::APSInt ConstLength;
9892 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
9893 return false; // Can't get the integer value as a constant.
9894
9895 return ConstLength.getSExtValue() != 1;
9896}
9897
Samuel Antao661c0902016-05-26 17:39:58 +00009898// Return the expression of the base of the mappable expression or null if it
9899// cannot be determined and do all the necessary checks to see if the expression
9900// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +00009901// components of the expression.
9902static Expr *CheckMapClauseExpressionBase(
9903 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +00009904 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
9905 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009906 SourceLocation ELoc = E->getExprLoc();
9907 SourceRange ERange = E->getSourceRange();
9908
9909 // The base of elements of list in a map clause have to be either:
9910 // - a reference to variable or field.
9911 // - a member expression.
9912 // - an array expression.
9913 //
9914 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
9915 // reference to 'r'.
9916 //
9917 // If we have:
9918 //
9919 // struct SS {
9920 // Bla S;
9921 // foo() {
9922 // #pragma omp target map (S.Arr[:12]);
9923 // }
9924 // }
9925 //
9926 // We want to retrieve the member expression 'this->S';
9927
9928 Expr *RelevantExpr = nullptr;
9929
Samuel Antao5de996e2016-01-22 20:21:36 +00009930 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
9931 // If a list item is an array section, it must specify contiguous storage.
9932 //
9933 // For this restriction it is sufficient that we make sure only references
9934 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009935 // exist except in the rightmost expression (unless they cover the whole
9936 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +00009937 //
9938 // r.ArrS[3:5].Arr[6:7]
9939 //
9940 // r.ArrS[3:5].x
9941 //
9942 // but these would be valid:
9943 // r.ArrS[3].Arr[6:7]
9944 //
9945 // r.ArrS[3].x
9946
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009947 bool AllowUnitySizeArraySection = true;
9948 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +00009949
Dmitry Polukhin644a9252016-03-11 07:58:34 +00009950 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +00009951 E = E->IgnoreParenImpCasts();
9952
9953 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
9954 if (!isa<VarDecl>(CurE->getDecl()))
9955 break;
9956
9957 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009958
9959 // If we got a reference to a declaration, we should not expect any array
9960 // section before that.
9961 AllowUnitySizeArraySection = false;
9962 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +00009963
9964 // Record the component.
9965 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent(
9966 CurE, CurE->getDecl()));
Samuel Antao5de996e2016-01-22 20:21:36 +00009967 continue;
9968 }
9969
9970 if (auto *CurE = dyn_cast<MemberExpr>(E)) {
9971 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
9972
9973 if (isa<CXXThisExpr>(BaseE))
9974 // We found a base expression: this->Val.
9975 RelevantExpr = CurE;
9976 else
9977 E = BaseE;
9978
9979 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
9980 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
9981 << CurE->getSourceRange();
9982 break;
9983 }
9984
9985 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
9986
9987 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
9988 // A bit-field cannot appear in a map clause.
9989 //
9990 if (FD->isBitField()) {
Samuel Antao661c0902016-05-26 17:39:58 +00009991 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
9992 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +00009993 break;
9994 }
9995
9996 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
9997 // If the type of a list item is a reference to a type T then the type
9998 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +00009999 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010000
10001 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
10002 // A list item cannot be a variable that is a member of a structure with
10003 // a union type.
10004 //
10005 if (auto *RT = CurType->getAs<RecordType>())
10006 if (RT->isUnionType()) {
10007 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
10008 << CurE->getSourceRange();
10009 break;
10010 }
10011
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010012 // If we got a member expression, we should not expect any array section
10013 // before that:
10014 //
10015 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
10016 // If a list item is an element of a structure, only the rightmost symbol
10017 // of the variable reference can be an array section.
10018 //
10019 AllowUnitySizeArraySection = false;
10020 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010021
10022 // Record the component.
10023 CurComponents.push_back(
10024 OMPClauseMappableExprCommon::MappableComponent(CurE, FD));
Samuel Antao5de996e2016-01-22 20:21:36 +000010025 continue;
10026 }
10027
10028 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
10029 E = CurE->getBase()->IgnoreParenImpCasts();
10030
10031 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
10032 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10033 << 0 << CurE->getSourceRange();
10034 break;
10035 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010036
10037 // If we got an array subscript that express the whole dimension we
10038 // can have any array expressions before. If it only expressing part of
10039 // the dimension, we can only have unitary-size array expressions.
10040 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
10041 E->getType()))
10042 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000010043
10044 // Record the component - we don't have any declaration associated.
10045 CurComponents.push_back(
10046 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010047 continue;
10048 }
10049
10050 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010051 E = CurE->getBase()->IgnoreParenImpCasts();
10052
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010053 auto CurType =
10054 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10055
Samuel Antao5de996e2016-01-22 20:21:36 +000010056 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10057 // If the type of a list item is a reference to a type T then the type
10058 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000010059 if (CurType->isReferenceType())
10060 CurType = CurType->getPointeeType();
10061
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010062 bool IsPointer = CurType->isAnyPointerType();
10063
10064 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010065 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
10066 << 0 << CurE->getSourceRange();
10067 break;
10068 }
10069
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010070 bool NotWhole =
10071 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
10072 bool NotUnity =
10073 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
10074
Samuel Antaodab51bb2016-07-18 23:22:11 +000010075 if (AllowWholeSizeArraySection) {
10076 // Any array section is currently allowed. Allowing a whole size array
10077 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010078 //
10079 // If this array section refers to the whole dimension we can still
10080 // accept other array sections before this one, except if the base is a
10081 // pointer. Otherwise, only unitary sections are accepted.
10082 if (NotWhole || IsPointer)
10083 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000010084 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000010085 // A unity or whole array section is not allowed and that is not
10086 // compatible with the properties of the current array section.
10087 SemaRef.Diag(
10088 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
10089 << CurE->getSourceRange();
10090 break;
10091 }
Samuel Antao90927002016-04-26 14:54:23 +000010092
10093 // Record the component - we don't have any declaration associated.
10094 CurComponents.push_back(
10095 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr));
Samuel Antao5de996e2016-01-22 20:21:36 +000010096 continue;
10097 }
10098
10099 // If nothing else worked, this is not a valid map clause expression.
10100 SemaRef.Diag(ELoc,
10101 diag::err_omp_expected_named_var_member_or_array_expression)
10102 << ERange;
10103 break;
10104 }
10105
10106 return RelevantExpr;
10107}
10108
10109// Return true if expression E associated with value VD has conflicts with other
10110// map information.
Samuel Antao90927002016-04-26 14:54:23 +000010111static bool CheckMapConflicts(
10112 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
10113 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000010114 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
10115 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010116 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000010117 SourceLocation ELoc = E->getExprLoc();
10118 SourceRange ERange = E->getSourceRange();
10119
10120 // In order to easily check the conflicts we need to match each component of
10121 // the expression under test with the components of the expressions that are
10122 // already in the stack.
10123
Samuel Antao5de996e2016-01-22 20:21:36 +000010124 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010125 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010126 "Map clause expression with unexpected base!");
10127
10128 // Variables to help detecting enclosing problems in data environment nests.
10129 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000010130 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000010131
Samuel Antao90927002016-04-26 14:54:23 +000010132 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
10133 VD, CurrentRegionOnly,
10134 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000010135 StackComponents,
10136 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000010137
Samuel Antao5de996e2016-01-22 20:21:36 +000010138 assert(!StackComponents.empty() &&
10139 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000010140 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000010141 "Map clause expression with unexpected base!");
10142
Samuel Antao90927002016-04-26 14:54:23 +000010143 // The whole expression in the stack.
10144 auto *RE = StackComponents.front().getAssociatedExpression();
10145
Samuel Antao5de996e2016-01-22 20:21:36 +000010146 // Expressions must start from the same base. Here we detect at which
10147 // point both expressions diverge from each other and see if we can
10148 // detect if the memory referred to both expressions is contiguous and
10149 // do not overlap.
10150 auto CI = CurComponents.rbegin();
10151 auto CE = CurComponents.rend();
10152 auto SI = StackComponents.rbegin();
10153 auto SE = StackComponents.rend();
10154 for (; CI != CE && SI != SE; ++CI, ++SI) {
10155
10156 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
10157 // At most one list item can be an array item derived from a given
10158 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000010159 if (CurrentRegionOnly &&
10160 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
10161 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
10162 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
10163 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
10164 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000010165 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000010166 << CI->getAssociatedExpression()->getSourceRange();
10167 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
10168 diag::note_used_here)
10169 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000010170 return true;
10171 }
10172
10173 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000010174 if (CI->getAssociatedExpression()->getStmtClass() !=
10175 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000010176 break;
10177
10178 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000010179 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000010180 break;
10181 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000010182 // Check if the extra components of the expressions in the enclosing
10183 // data environment are redundant for the current base declaration.
10184 // If they are, the maps completely overlap, which is legal.
10185 for (; SI != SE; ++SI) {
10186 QualType Type;
10187 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000010188 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010189 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000010190 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
10191 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000010192 auto *E = OASE->getBase()->IgnoreParenImpCasts();
10193 Type =
10194 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
10195 }
10196 if (Type.isNull() || Type->isAnyPointerType() ||
10197 CheckArrayExpressionDoesNotReferToWholeSize(
10198 SemaRef, SI->getAssociatedExpression(), Type))
10199 break;
10200 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010201
10202 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10203 // List items of map clauses in the same construct must not share
10204 // original storage.
10205 //
10206 // If the expressions are exactly the same or one is a subset of the
10207 // other, it means they are sharing storage.
10208 if (CI == CE && SI == SE) {
10209 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000010210 if (CKind == OMPC_map)
10211 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10212 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010213 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010214 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10215 << ERange;
10216 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010217 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10218 << RE->getSourceRange();
10219 return true;
10220 } else {
10221 // If we find the same expression in the enclosing data environment,
10222 // that is legal.
10223 IsEnclosedByDataEnvironmentExpr = true;
10224 return false;
10225 }
10226 }
10227
Samuel Antao90927002016-04-26 14:54:23 +000010228 QualType DerivedType =
10229 std::prev(CI)->getAssociatedDeclaration()->getType();
10230 SourceLocation DerivedLoc =
10231 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000010232
10233 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10234 // If the type of a list item is a reference to a type T then the type
10235 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010236 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010237
10238 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
10239 // A variable for which the type is pointer and an array section
10240 // derived from that variable must not appear as list items of map
10241 // clauses of the same construct.
10242 //
10243 // Also, cover one of the cases in:
10244 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10245 // If any part of the original storage of a list item has corresponding
10246 // storage in the device data environment, all of the original storage
10247 // must have corresponding storage in the device data environment.
10248 //
10249 if (DerivedType->isAnyPointerType()) {
10250 if (CI == CE || SI == SE) {
10251 SemaRef.Diag(
10252 DerivedLoc,
10253 diag::err_omp_pointer_mapped_along_with_derived_section)
10254 << DerivedLoc;
10255 } else {
10256 assert(CI != CE && SI != SE);
10257 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
10258 << DerivedLoc;
10259 }
10260 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10261 << RE->getSourceRange();
10262 return true;
10263 }
10264
10265 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
10266 // List items of map clauses in the same construct must not share
10267 // original storage.
10268 //
10269 // An expression is a subset of the other.
10270 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000010271 if (CKind == OMPC_map)
10272 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
10273 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000010274 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000010275 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
10276 << ERange;
10277 }
Samuel Antao5de996e2016-01-22 20:21:36 +000010278 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
10279 << RE->getSourceRange();
10280 return true;
10281 }
10282
10283 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000010284 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000010285 if (!CurrentRegionOnly && SI != SE)
10286 EnclosingExpr = RE;
10287
10288 // The current expression is a subset of the expression in the data
10289 // environment.
10290 IsEnclosedByDataEnvironmentExpr |=
10291 (!CurrentRegionOnly && CI != CE && SI == SE);
10292
10293 return false;
10294 });
10295
10296 if (CurrentRegionOnly)
10297 return FoundError;
10298
10299 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
10300 // If any part of the original storage of a list item has corresponding
10301 // storage in the device data environment, all of the original storage must
10302 // have corresponding storage in the device data environment.
10303 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
10304 // If a list item is an element of a structure, and a different element of
10305 // the structure has a corresponding list item in the device data environment
10306 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000010307 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000010308 // data environment prior to the task encountering the construct.
10309 //
10310 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
10311 SemaRef.Diag(ELoc,
10312 diag::err_omp_original_storage_is_shared_and_does_not_contain)
10313 << ERange;
10314 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
10315 << EnclosingExpr->getSourceRange();
10316 return true;
10317 }
10318
10319 return FoundError;
10320}
10321
Samuel Antao661c0902016-05-26 17:39:58 +000010322namespace {
10323// Utility struct that gathers all the related lists associated with a mappable
10324// expression.
10325struct MappableVarListInfo final {
10326 // The list of expressions.
10327 ArrayRef<Expr *> VarList;
10328 // The list of processed expressions.
10329 SmallVector<Expr *, 16> ProcessedVarList;
10330 // The mappble components for each expression.
10331 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
10332 // The base declaration of the variable.
10333 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
10334
10335 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
10336 // We have a list of components and base declarations for each entry in the
10337 // variable list.
10338 VarComponents.reserve(VarList.size());
10339 VarBaseDeclarations.reserve(VarList.size());
10340 }
10341};
10342}
10343
10344// Check the validity of the provided variable list for the provided clause kind
10345// \a CKind. In the check process the valid expressions, and mappable expression
10346// components and variables are extracted and used to fill \a Vars,
10347// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
10348// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
10349static void
10350checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
10351 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
10352 SourceLocation StartLoc,
10353 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
10354 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010355 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
10356 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000010357 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010358
Samuel Antao90927002016-04-26 14:54:23 +000010359 // Keep track of the mappable components and base declarations in this clause.
10360 // Each entry in the list is going to have a list of components associated. We
10361 // record each set of the components so that we can build the clause later on.
10362 // In the end we should have the same amount of declarations and component
10363 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000010364
Samuel Antao661c0902016-05-26 17:39:58 +000010365 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000010366 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010367 SourceLocation ELoc = RE->getExprLoc();
10368
Kelvin Li0bff7af2015-11-23 05:32:03 +000010369 auto *VE = RE->IgnoreParenLValueCasts();
10370
10371 if (VE->isValueDependent() || VE->isTypeDependent() ||
10372 VE->isInstantiationDependent() ||
10373 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000010374 // We can only analyze this information once the missing information is
10375 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000010376 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010377 continue;
10378 }
10379
10380 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010381
Samuel Antao5de996e2016-01-22 20:21:36 +000010382 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000010383 SemaRef.Diag(ELoc,
10384 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000010385 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000010386 continue;
10387 }
10388
Samuel Antao90927002016-04-26 14:54:23 +000010389 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
10390 ValueDecl *CurDeclaration = nullptr;
10391
10392 // Obtain the array or member expression bases if required. Also, fill the
10393 // components array with all the components identified in the process.
Samuel Antao661c0902016-05-26 17:39:58 +000010394 auto *BE =
10395 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind);
Samuel Antao5de996e2016-01-22 20:21:36 +000010396 if (!BE)
10397 continue;
10398
Samuel Antao90927002016-04-26 14:54:23 +000010399 assert(!CurComponents.empty() &&
10400 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000010401
Samuel Antao90927002016-04-26 14:54:23 +000010402 // For the following checks, we rely on the base declaration which is
10403 // expected to be associated with the last component. The declaration is
10404 // expected to be a variable or a field (if 'this' is being mapped).
10405 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
10406 assert(CurDeclaration && "Null decl on map clause.");
10407 assert(
10408 CurDeclaration->isCanonicalDecl() &&
10409 "Expecting components to have associated only canonical declarations.");
10410
10411 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
10412 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000010413
10414 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000010415 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000010416
10417 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000010418 // threadprivate variables cannot appear in a map clause.
10419 // OpenMP 4.5 [2.10.5, target update Construct]
10420 // threadprivate variables cannot appear in a from clause.
10421 if (VD && DSAS->isThreadPrivate(VD)) {
10422 auto DVar = DSAS->getTopDSA(VD, false);
10423 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
10424 << getOpenMPClauseName(CKind);
10425 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010426 continue;
10427 }
10428
Samuel Antao5de996e2016-01-22 20:21:36 +000010429 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
10430 // A list item cannot appear in both a map clause and a data-sharing
10431 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000010432
Samuel Antao5de996e2016-01-22 20:21:36 +000010433 // Check conflicts with other map clause expressions. We check the conflicts
10434 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000010435 // environment, because the restrictions are different. We only have to
10436 // check conflicts across regions for the map clauses.
10437 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10438 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010439 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010440 if (CKind == OMPC_map &&
10441 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
10442 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000010443 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000010444
Samuel Antao661c0902016-05-26 17:39:58 +000010445 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000010446 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
10447 // If the type of a list item is a reference to a type T then the type will
10448 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000010449 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000010450
Samuel Antao661c0902016-05-26 17:39:58 +000010451 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
10452 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000010453 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000010454 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000010455 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
10456 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000010457 continue;
10458
Samuel Antao661c0902016-05-26 17:39:58 +000010459 if (CKind == OMPC_map) {
10460 // target enter data
10461 // OpenMP [2.10.2, Restrictions, p. 99]
10462 // A map-type must be specified in all map clauses and must be either
10463 // to or alloc.
10464 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
10465 if (DKind == OMPD_target_enter_data &&
10466 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
10467 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10468 << (IsMapTypeImplicit ? 1 : 0)
10469 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10470 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010471 continue;
10472 }
Samuel Antao661c0902016-05-26 17:39:58 +000010473
10474 // target exit_data
10475 // OpenMP [2.10.3, Restrictions, p. 102]
10476 // A map-type must be specified in all map clauses and must be either
10477 // from, release, or delete.
10478 if (DKind == OMPD_target_exit_data &&
10479 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
10480 MapType == OMPC_MAP_delete)) {
10481 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
10482 << (IsMapTypeImplicit ? 1 : 0)
10483 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
10484 << getOpenMPDirectiveName(DKind);
10485 continue;
10486 }
10487
10488 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10489 // A list item cannot appear in both a map clause and a data-sharing
10490 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000010491 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000010492 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000010493 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000010494 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
10495 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000010496 auto DVar = DSAS->getTopDSA(VD, false);
10497 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010498 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000010499 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000010500 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000010501 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
10502 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
10503 continue;
10504 }
10505 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010506 }
10507
Samuel Antao90927002016-04-26 14:54:23 +000010508 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000010509 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000010510
10511 // Store the components in the stack so that they can be used to check
10512 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000010513 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
10514 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000010515
10516 // Save the components and declaration to create the clause. For purposes of
10517 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000010518 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000010519 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
10520 MVLI.VarComponents.back().append(CurComponents.begin(),
10521 CurComponents.end());
10522 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
10523 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010524 }
Samuel Antao661c0902016-05-26 17:39:58 +000010525}
10526
10527OMPClause *
10528Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
10529 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
10530 SourceLocation MapLoc, SourceLocation ColonLoc,
10531 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
10532 SourceLocation LParenLoc, SourceLocation EndLoc) {
10533 MappableVarListInfo MVLI(VarList);
10534 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
10535 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010536
Samuel Antao5de996e2016-01-22 20:21:36 +000010537 // We need to produce a map clause even if we don't have variables so that
10538 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000010539 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10540 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
10541 MVLI.VarComponents, MapTypeModifier, MapType,
10542 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000010543}
Kelvin Li099bb8c2015-11-24 20:50:12 +000010544
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010545QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10546 TypeResult ParsedType) {
10547 assert(ParsedType.isUsable());
10548
10549 QualType ReductionType = GetTypeFromParser(ParsedType.get());
10550 if (ReductionType.isNull())
10551 return QualType();
10552
10553 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
10554 // A type name in a declare reduction directive cannot be a function type, an
10555 // array type, a reference type, or a type qualified with const, volatile or
10556 // restrict.
10557 if (ReductionType.hasQualifiers()) {
10558 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
10559 return QualType();
10560 }
10561
10562 if (ReductionType->isFunctionType()) {
10563 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
10564 return QualType();
10565 }
10566 if (ReductionType->isReferenceType()) {
10567 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
10568 return QualType();
10569 }
10570 if (ReductionType->isArrayType()) {
10571 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
10572 return QualType();
10573 }
10574 return ReductionType;
10575}
10576
10577Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
10578 Scope *S, DeclContext *DC, DeclarationName Name,
10579 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10580 AccessSpecifier AS, Decl *PrevDeclInScope) {
10581 SmallVector<Decl *, 8> Decls;
10582 Decls.reserve(ReductionTypes.size());
10583
10584 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
10585 ForRedeclaration);
10586 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
10587 // A reduction-identifier may not be re-declared in the current scope for the
10588 // same type or for a type that is compatible according to the base language
10589 // rules.
10590 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
10591 OMPDeclareReductionDecl *PrevDRD = nullptr;
10592 bool InCompoundScope = true;
10593 if (S != nullptr) {
10594 // Find previous declaration with the same name not referenced in other
10595 // declarations.
10596 FunctionScopeInfo *ParentFn = getEnclosingFunction();
10597 InCompoundScope =
10598 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
10599 LookupName(Lookup, S);
10600 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
10601 /*AllowInlineNamespace=*/false);
10602 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
10603 auto Filter = Lookup.makeFilter();
10604 while (Filter.hasNext()) {
10605 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
10606 if (InCompoundScope) {
10607 auto I = UsedAsPrevious.find(PrevDecl);
10608 if (I == UsedAsPrevious.end())
10609 UsedAsPrevious[PrevDecl] = false;
10610 if (auto *D = PrevDecl->getPrevDeclInScope())
10611 UsedAsPrevious[D] = true;
10612 }
10613 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
10614 PrevDecl->getLocation();
10615 }
10616 Filter.done();
10617 if (InCompoundScope) {
10618 for (auto &PrevData : UsedAsPrevious) {
10619 if (!PrevData.second) {
10620 PrevDRD = PrevData.first;
10621 break;
10622 }
10623 }
10624 }
10625 } else if (PrevDeclInScope != nullptr) {
10626 auto *PrevDRDInScope = PrevDRD =
10627 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
10628 do {
10629 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
10630 PrevDRDInScope->getLocation();
10631 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
10632 } while (PrevDRDInScope != nullptr);
10633 }
10634 for (auto &TyData : ReductionTypes) {
10635 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
10636 bool Invalid = false;
10637 if (I != PreviousRedeclTypes.end()) {
10638 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
10639 << TyData.first;
10640 Diag(I->second, diag::note_previous_definition);
10641 Invalid = true;
10642 }
10643 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
10644 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
10645 Name, TyData.first, PrevDRD);
10646 DC->addDecl(DRD);
10647 DRD->setAccess(AS);
10648 Decls.push_back(DRD);
10649 if (Invalid)
10650 DRD->setInvalidDecl();
10651 else
10652 PrevDRD = DRD;
10653 }
10654
10655 return DeclGroupPtrTy::make(
10656 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
10657}
10658
10659void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
10660 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10661
10662 // Enter new function scope.
10663 PushFunctionScope();
10664 getCurFunction()->setHasBranchProtectedScope();
10665 getCurFunction()->setHasOMPDeclareReductionCombiner();
10666
10667 if (S != nullptr)
10668 PushDeclContext(S, DRD);
10669 else
10670 CurContext = DRD;
10671
10672 PushExpressionEvaluationContext(PotentiallyEvaluated);
10673
10674 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010675 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
10676 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
10677 // uses semantics of argument handles by value, but it should be passed by
10678 // reference. C lang does not support references, so pass all parameters as
10679 // pointers.
10680 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010681 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010682 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010683 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
10684 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
10685 // uses semantics of argument handles by value, but it should be passed by
10686 // reference. C lang does not support references, so pass all parameters as
10687 // pointers.
10688 // Create 'T omp_out;' variable.
10689 auto *OmpOutParm =
10690 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
10691 if (S != nullptr) {
10692 PushOnScopeChains(OmpInParm, S);
10693 PushOnScopeChains(OmpOutParm, S);
10694 } else {
10695 DRD->addDecl(OmpInParm);
10696 DRD->addDecl(OmpOutParm);
10697 }
10698}
10699
10700void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
10701 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10702 DiscardCleanupsInEvaluationContext();
10703 PopExpressionEvaluationContext();
10704
10705 PopDeclContext();
10706 PopFunctionScopeInfo();
10707
10708 if (Combiner != nullptr)
10709 DRD->setCombiner(Combiner);
10710 else
10711 DRD->setInvalidDecl();
10712}
10713
10714void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
10715 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10716
10717 // Enter new function scope.
10718 PushFunctionScope();
10719 getCurFunction()->setHasBranchProtectedScope();
10720
10721 if (S != nullptr)
10722 PushDeclContext(S, DRD);
10723 else
10724 CurContext = DRD;
10725
10726 PushExpressionEvaluationContext(PotentiallyEvaluated);
10727
10728 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010729 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
10730 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
10731 // uses semantics of argument handles by value, but it should be passed by
10732 // reference. C lang does not support references, so pass all parameters as
10733 // pointers.
10734 // Create 'T omp_priv;' variable.
10735 auto *OmpPrivParm =
10736 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010737 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
10738 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
10739 // uses semantics of argument handles by value, but it should be passed by
10740 // reference. C lang does not support references, so pass all parameters as
10741 // pointers.
10742 // Create 'T omp_orig;' variable.
10743 auto *OmpOrigParm =
10744 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000010745 if (S != nullptr) {
10746 PushOnScopeChains(OmpPrivParm, S);
10747 PushOnScopeChains(OmpOrigParm, S);
10748 } else {
10749 DRD->addDecl(OmpPrivParm);
10750 DRD->addDecl(OmpOrigParm);
10751 }
10752}
10753
10754void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D,
10755 Expr *Initializer) {
10756 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10757 DiscardCleanupsInEvaluationContext();
10758 PopExpressionEvaluationContext();
10759
10760 PopDeclContext();
10761 PopFunctionScopeInfo();
10762
10763 if (Initializer != nullptr)
10764 DRD->setInitializer(Initializer);
10765 else
10766 DRD->setInvalidDecl();
10767}
10768
10769Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
10770 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
10771 for (auto *D : DeclReductions.get()) {
10772 if (IsValid) {
10773 auto *DRD = cast<OMPDeclareReductionDecl>(D);
10774 if (S != nullptr)
10775 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
10776 } else
10777 D->setInvalidDecl();
10778 }
10779 return DeclReductions;
10780}
10781
David Majnemer9d168222016-08-05 17:44:54 +000010782OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000010783 SourceLocation StartLoc,
10784 SourceLocation LParenLoc,
10785 SourceLocation EndLoc) {
10786 Expr *ValExpr = NumTeams;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010787
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010788 // OpenMP [teams Constrcut, Restrictions]
10789 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010790 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
10791 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010792 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010793
10794 return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10795}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010796
10797OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
10798 SourceLocation StartLoc,
10799 SourceLocation LParenLoc,
10800 SourceLocation EndLoc) {
10801 Expr *ValExpr = ThreadLimit;
10802
10803 // OpenMP [teams Constrcut, Restrictions]
10804 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000010805 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
10806 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010807 return nullptr;
10808
David Majnemer9d168222016-08-05 17:44:54 +000010809 return new (Context)
10810 OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010811}
Alexey Bataeva0569352015-12-01 10:17:31 +000010812
10813OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
10814 SourceLocation StartLoc,
10815 SourceLocation LParenLoc,
10816 SourceLocation EndLoc) {
10817 Expr *ValExpr = Priority;
10818
10819 // OpenMP [2.9.1, task Constrcut]
10820 // The priority-value is a non-negative numerical scalar expression.
10821 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
10822 /*StrictlyPositive=*/false))
10823 return nullptr;
10824
10825 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10826}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010827
10828OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
10829 SourceLocation StartLoc,
10830 SourceLocation LParenLoc,
10831 SourceLocation EndLoc) {
10832 Expr *ValExpr = Grainsize;
10833
10834 // OpenMP [2.9.2, taskloop Constrcut]
10835 // The parameter of the grainsize clause must be a positive integer
10836 // expression.
10837 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
10838 /*StrictlyPositive=*/true))
10839 return nullptr;
10840
10841 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10842}
Alexey Bataev382967a2015-12-08 12:06:20 +000010843
10844OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
10845 SourceLocation StartLoc,
10846 SourceLocation LParenLoc,
10847 SourceLocation EndLoc) {
10848 Expr *ValExpr = NumTasks;
10849
10850 // OpenMP [2.9.2, taskloop Constrcut]
10851 // The parameter of the num_tasks clause must be a positive integer
10852 // expression.
10853 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
10854 /*StrictlyPositive=*/true))
10855 return nullptr;
10856
10857 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10858}
10859
Alexey Bataev28c75412015-12-15 08:19:24 +000010860OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
10861 SourceLocation LParenLoc,
10862 SourceLocation EndLoc) {
10863 // OpenMP [2.13.2, critical construct, Description]
10864 // ... where hint-expression is an integer constant expression that evaluates
10865 // to a valid lock hint.
10866 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
10867 if (HintExpr.isInvalid())
10868 return nullptr;
10869 return new (Context)
10870 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
10871}
10872
Carlo Bertollib4adf552016-01-15 18:50:31 +000010873OMPClause *Sema::ActOnOpenMPDistScheduleClause(
10874 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
10875 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
10876 SourceLocation EndLoc) {
10877 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
10878 std::string Values;
10879 Values += "'";
10880 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
10881 Values += "'";
10882 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10883 << Values << getOpenMPClauseName(OMPC_dist_schedule);
10884 return nullptr;
10885 }
10886 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010887 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010888 if (ChunkSize) {
10889 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10890 !ChunkSize->isInstantiationDependent() &&
10891 !ChunkSize->containsUnexpandedParameterPack()) {
10892 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
10893 ExprResult Val =
10894 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10895 if (Val.isInvalid())
10896 return nullptr;
10897
10898 ValExpr = Val.get();
10899
10900 // OpenMP [2.7.1, Restrictions]
10901 // chunk_size must be a loop invariant integer expression with a positive
10902 // value.
10903 llvm::APSInt Result;
10904 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10905 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10906 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
10907 << "dist_schedule" << ChunkSize->getSourceRange();
10908 return nullptr;
10909 }
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010910 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
10911 !CurContext->isDependentContext()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +000010912 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
10913 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10914 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010915 }
10916 }
10917 }
10918
10919 return new (Context)
10920 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000010921 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000010922}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010923
10924OMPClause *Sema::ActOnOpenMPDefaultmapClause(
10925 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
10926 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
10927 SourceLocation KindLoc, SourceLocation EndLoc) {
10928 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000010929 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010930 std::string Value;
10931 SourceLocation Loc;
10932 Value += "'";
10933 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
10934 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010935 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010936 Loc = MLoc;
10937 } else {
10938 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000010939 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010940 Loc = KindLoc;
10941 }
10942 Value += "'";
10943 Diag(Loc, diag::err_omp_unexpected_clause_value)
10944 << Value << getOpenMPClauseName(OMPC_defaultmap);
10945 return nullptr;
10946 }
10947
10948 return new (Context)
10949 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
10950}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000010951
10952bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
10953 DeclContext *CurLexicalContext = getCurLexicalContext();
10954 if (!CurLexicalContext->isFileContext() &&
10955 !CurLexicalContext->isExternCContext() &&
10956 !CurLexicalContext->isExternCXXContext()) {
10957 Diag(Loc, diag::err_omp_region_not_file_context);
10958 return false;
10959 }
10960 if (IsInOpenMPDeclareTargetContext) {
10961 Diag(Loc, diag::err_omp_enclosed_declare_target);
10962 return false;
10963 }
10964
10965 IsInOpenMPDeclareTargetContext = true;
10966 return true;
10967}
10968
10969void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
10970 assert(IsInOpenMPDeclareTargetContext &&
10971 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
10972
10973 IsInOpenMPDeclareTargetContext = false;
10974}
10975
David Majnemer9d168222016-08-05 17:44:54 +000010976void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
10977 CXXScopeSpec &ScopeSpec,
10978 const DeclarationNameInfo &Id,
10979 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10980 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000010981 LookupResult Lookup(*this, Id, LookupOrdinaryName);
10982 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
10983
10984 if (Lookup.isAmbiguous())
10985 return;
10986 Lookup.suppressDiagnostics();
10987
10988 if (!Lookup.isSingleResult()) {
10989 if (TypoCorrection Corrected =
10990 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
10991 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
10992 CTK_ErrorRecovery)) {
10993 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
10994 << Id.getName());
10995 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
10996 return;
10997 }
10998
10999 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
11000 return;
11001 }
11002
11003 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
11004 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
11005 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
11006 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
11007
11008 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
11009 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
11010 ND->addAttr(A);
11011 if (ASTMutationListener *ML = Context.getASTMutationListener())
11012 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
11013 checkDeclIsAllowedInOpenMPTarget(nullptr, ND);
11014 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
11015 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
11016 << Id.getName();
11017 }
11018 } else
11019 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
11020}
11021
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011022static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
11023 Sema &SemaRef, Decl *D) {
11024 if (!D)
11025 return;
11026 Decl *LD = nullptr;
11027 if (isa<TagDecl>(D)) {
11028 LD = cast<TagDecl>(D)->getDefinition();
11029 } else if (isa<VarDecl>(D)) {
11030 LD = cast<VarDecl>(D)->getDefinition();
11031
11032 // If this is an implicit variable that is legal and we do not need to do
11033 // anything.
11034 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011035 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11036 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11037 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011038 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011039 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011040 return;
11041 }
11042
11043 } else if (isa<FunctionDecl>(D)) {
11044 const FunctionDecl *FD = nullptr;
11045 if (cast<FunctionDecl>(D)->hasBody(FD))
11046 LD = const_cast<FunctionDecl *>(FD);
11047
11048 // If the definition is associated with the current declaration in the
11049 // target region (it can be e.g. a lambda) that is legal and we do not need
11050 // to do anything else.
11051 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011052 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11053 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11054 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011055 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011056 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011057 return;
11058 }
11059 }
11060 if (!LD)
11061 LD = D;
11062 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
11063 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
11064 // Outlined declaration is not declared target.
11065 if (LD->isOutOfLine()) {
11066 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11067 SemaRef.Diag(SL, diag::note_used_here) << SR;
11068 } else {
11069 DeclContext *DC = LD->getDeclContext();
11070 while (DC) {
11071 if (isa<FunctionDecl>(DC) &&
11072 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
11073 break;
11074 DC = DC->getParent();
11075 }
11076 if (DC)
11077 return;
11078
11079 // Is not declared in target context.
11080 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
11081 SemaRef.Diag(SL, diag::note_used_here) << SR;
11082 }
11083 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011084 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11085 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
11086 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011087 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011088 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011089 }
11090}
11091
11092static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
11093 Sema &SemaRef, DSAStackTy *Stack,
11094 ValueDecl *VD) {
11095 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
11096 return true;
11097 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
11098 return false;
11099 return true;
11100}
11101
11102void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) {
11103 if (!D || D->isInvalidDecl())
11104 return;
11105 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
11106 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
11107 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
11108 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11109 if (DSAStack->isThreadPrivate(VD)) {
11110 Diag(SL, diag::err_omp_threadprivate_in_target);
11111 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
11112 return;
11113 }
11114 }
11115 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
11116 // Problem if any with var declared with incomplete type will be reported
11117 // as normal, so no need to check it here.
11118 if ((E || !VD->getType()->isIncompleteType()) &&
11119 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
11120 // Mark decl as declared target to prevent further diagnostic.
11121 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011122 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11123 Context, OMPDeclareTargetDeclAttr::MT_To);
11124 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011125 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011126 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011127 }
11128 return;
11129 }
11130 }
11131 if (!E) {
11132 // Checking declaration inside declare target region.
11133 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
11134 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011135 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
11136 Context, OMPDeclareTargetDeclAttr::MT_To);
11137 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011138 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000011139 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000011140 }
11141 return;
11142 }
11143 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
11144}
Samuel Antao661c0902016-05-26 17:39:58 +000011145
11146OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
11147 SourceLocation StartLoc,
11148 SourceLocation LParenLoc,
11149 SourceLocation EndLoc) {
11150 MappableVarListInfo MVLI(VarList);
11151 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
11152 if (MVLI.ProcessedVarList.empty())
11153 return nullptr;
11154
11155 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11156 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11157 MVLI.VarComponents);
11158}
Samuel Antaoec172c62016-05-26 17:49:04 +000011159
11160OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
11161 SourceLocation StartLoc,
11162 SourceLocation LParenLoc,
11163 SourceLocation EndLoc) {
11164 MappableVarListInfo MVLI(VarList);
11165 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
11166 if (MVLI.ProcessedVarList.empty())
11167 return nullptr;
11168
11169 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11170 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
11171 MVLI.VarComponents);
11172}
Carlo Bertolli2404b172016-07-13 15:37:16 +000011173
11174OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11175 SourceLocation StartLoc,
11176 SourceLocation LParenLoc,
11177 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000011178 MappableVarListInfo MVLI(VarList);
11179 SmallVector<Expr *, 8> PrivateCopies;
11180 SmallVector<Expr *, 8> Inits;
11181
Carlo Bertolli2404b172016-07-13 15:37:16 +000011182 for (auto &RefExpr : VarList) {
11183 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
11184 SourceLocation ELoc;
11185 SourceRange ERange;
11186 Expr *SimpleRefExpr = RefExpr;
11187 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11188 if (Res.second) {
11189 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000011190 MVLI.ProcessedVarList.push_back(RefExpr);
11191 PrivateCopies.push_back(nullptr);
11192 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011193 }
11194 ValueDecl *D = Res.first;
11195 if (!D)
11196 continue;
11197
11198 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000011199 Type = Type.getNonReferenceType().getUnqualifiedType();
11200
11201 auto *VD = dyn_cast<VarDecl>(D);
11202
11203 // Item should be a pointer or reference to pointer.
11204 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000011205 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
11206 << 0 << RefExpr->getSourceRange();
11207 continue;
11208 }
Samuel Antaocc10b852016-07-28 14:23:26 +000011209
11210 // Build the private variable and the expression that refers to it.
11211 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
11212 D->hasAttrs() ? &D->getAttrs() : nullptr);
11213 if (VDPrivate->isInvalidDecl())
11214 continue;
11215
11216 CurContext->addDecl(VDPrivate);
11217 auto VDPrivateRefExpr = buildDeclRefExpr(
11218 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
11219
11220 // Add temporary variable to initialize the private copy of the pointer.
11221 auto *VDInit =
11222 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
11223 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11224 RefExpr->getExprLoc());
11225 AddInitializerToDecl(VDPrivate,
11226 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011227 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000011228
11229 // If required, build a capture to implement the privatization initialized
11230 // with the current list item value.
11231 DeclRefExpr *Ref = nullptr;
11232 if (!VD)
11233 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11234 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
11235 PrivateCopies.push_back(VDPrivateRefExpr);
11236 Inits.push_back(VDInitRefExpr);
11237
11238 // We need to add a data sharing attribute for this variable to make sure it
11239 // is correctly captured. A variable that shows up in a use_device_ptr has
11240 // similar properties of a first private variable.
11241 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
11242
11243 // Create a mappable component for the list item. List items in this clause
11244 // only need a component.
11245 MVLI.VarBaseDeclarations.push_back(D);
11246 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11247 MVLI.VarComponents.back().push_back(
11248 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000011249 }
11250
Samuel Antaocc10b852016-07-28 14:23:26 +000011251 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000011252 return nullptr;
11253
Samuel Antaocc10b852016-07-28 14:23:26 +000011254 return OMPUseDevicePtrClause::Create(
11255 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11256 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011257}
Carlo Bertolli70594e92016-07-13 17:16:49 +000011258
11259OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11260 SourceLocation StartLoc,
11261 SourceLocation LParenLoc,
11262 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000011263 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011264 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000011265 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000011266 SourceLocation ELoc;
11267 SourceRange ERange;
11268 Expr *SimpleRefExpr = RefExpr;
11269 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11270 if (Res.second) {
11271 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000011272 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011273 }
11274 ValueDecl *D = Res.first;
11275 if (!D)
11276 continue;
11277
11278 QualType Type = D->getType();
11279 // item should be a pointer or array or reference to pointer or array
11280 if (!Type.getNonReferenceType()->isPointerType() &&
11281 !Type.getNonReferenceType()->isArrayType()) {
11282 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
11283 << 0 << RefExpr->getSourceRange();
11284 continue;
11285 }
Samuel Antao6890b092016-07-28 14:25:09 +000011286
11287 // Check if the declaration in the clause does not show up in any data
11288 // sharing attribute.
11289 auto DVar = DSAStack->getTopDSA(D, false);
11290 if (isOpenMPPrivate(DVar.CKind)) {
11291 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
11292 << getOpenMPClauseName(DVar.CKind)
11293 << getOpenMPClauseName(OMPC_is_device_ptr)
11294 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11295 ReportOriginalDSA(*this, DSAStack, D, DVar);
11296 continue;
11297 }
11298
11299 Expr *ConflictExpr;
11300 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011301 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011302 [&ConflictExpr](
11303 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
11304 OpenMPClauseKind) -> bool {
11305 ConflictExpr = R.front().getAssociatedExpression();
11306 return true;
11307 })) {
11308 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
11309 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
11310 << ConflictExpr->getSourceRange();
11311 continue;
11312 }
11313
11314 // Store the components in the stack so that they can be used to check
11315 // against other clauses later on.
11316 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
11317 DSAStack->addMappableExpressionComponents(
11318 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
11319
11320 // Record the expression we've just processed.
11321 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
11322
11323 // Create a mappable component for the list item. List items in this clause
11324 // only need a component. We use a null declaration to signal fields in
11325 // 'this'.
11326 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
11327 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
11328 "Unexpected device pointer expression!");
11329 MVLI.VarBaseDeclarations.push_back(
11330 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
11331 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
11332 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011333 }
11334
Samuel Antao6890b092016-07-28 14:25:09 +000011335 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000011336 return nullptr;
11337
Samuel Antao6890b092016-07-28 14:25:09 +000011338 return OMPIsDevicePtrClause::Create(
11339 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
11340 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011341}